Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS 

Set Gajim's away message to your last tweet

This Ruby code fetches the latest tweet from the Twitter RSS feed and then uses it to update the autoaway message in Gajim.

#!/usr/bin/ruby
# file: RGajim-updater.rb

require 'open-uri'
require 'rexml/document'
include REXML


class GajimUpdater

  attr_accessor :url, :user

  def initialize_doc()
    @user = 'jrobertson'
    @url = 'http://twitter.com/statuses/user_timeline/763224.rss'
  end

  def write_config(msg)
    filepath = '/home/james/.gajim/'
    filein = File.new(filepath + 'config','r')
    buffer = filein.read
    filein.close

    am = 'autoaway_message = '
    new_buffer = buffer.gsub(/#{am}.*/,am + msg)

    fileout = File.new(filepath + 'config','w')
    fileout.puts new_buffer
    fileout.close
    puts 'config file updated!'
  end

  def get_latest_msg()

    puts 'getting the latest tweet ...' 
    buffer = open(@url,
         'User-Agent' => 'RGajim-updater').read

    doc = Document.new(buffer)
    doc.root.elements['//item/title'].text.to_s[/[^#{@user} :].*/]
  end
end

if __FILE__ == $0 then

  g = GajimUpdater.new()
  g.url = 'http://twitter.com/statuses/user_timeline/763224.rss'
  g.user = 'jrobertson'
  title = g.get_latest_msg()
  g.write_config(title)

end

Twitter and Jaiku from the command line

The following instructions make it easy to post to Twitter and Jaiku from the command line. The instructions were copied from the article "Ubuntu Unleashed: Howto Twitter From the Command Line in Ubuntu!" [ubuntu-unleashed.com] and modified to post via Rorbuilder's ProjectX API.

sudo apt-get install curl

sudo gedit /usr/bin/jaitwit

Now Paste this in gEdit and simply replace "YourUsername" with your username and "YourPassword" with your twitter passwd, then replace the Jaiku variables (YourUsername, YourPassword, YourCity, YourAccessKey) and ctrl-s to save, then alt-F4 to exit!
curl http://rorbuilder.info/api/projectx.cgi?xml_project=%3Cproject%20name=%22micro_blog%22%3E%3Cmethods%3E%3Cmethod%20name=%22post2jaiku%22%3E%3Cparams%3E%3Cparam%20var=%22user%22%20val=%22YourUsername%22/%3E%3Cparam%20var=%22msg%22%20val=%22`echo $@|tr ' ' '+'`%22/%3E%3Cparam%20var=%22location%22%20val=%22YourCity%22/%3E%3Cparam%20var=%22apikey%22%20val=%22YourAccessKey%22/%3E%3C/params%3E%3C/method%3E%3Cmethod%20name=%22post2twitter%22%3E%3Cparams%3E%3Cparam%20var=%22user%22%20val=%22YourUsername%22/%3E%3Cparam%20var=%22msg%22%20val=%22`echo $@|tr ' ' '+'`%22/%3E%3Cparam%20var=%22password%22%20val=%22YourPassword%22/%3E%3C/params%3E%3C/method%3E%3C/methods%3E%3C/project%3E -o /dev/null
echo Message Sent!

Then chmod for exec privileges:
chmod +x /usr/bin/jaitwit

Then from the CLI type jaitwit followed by your message.
jaitwit "message here without the quotes"

Post to both Jaiku and Twitter

This XML code is the ProjectX API to post to both Twitter and Jaiku. This is a follow-up example from Post to Jaiku using ProjectX API [dzone.com]

xml_project = <<PROJECT
<project name='micro_blog'>
  <methods>
    <method name='post2jaiku'>
      <params>
        <param var='user' val='YourJaikuUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='location' val='YourCity'/>
        <param var='apikey' val='YourApiKey'/>
      </params>
    </method>
    <method name='post2twitter'>
      <params>
        <param var='user' val='YourTwitterUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='password' val='YourPassword'/>
      </params>
    </method>    
  </methods>
</project>"
PROJECT

Searching through your Twitter archive

This Ruby code downloads previous twitter entries as html files to a local file directory.
(1..5).each {|i| `wget --user=jrobertson --password=secret http://twitter.com/account/archive?page=#{i}`}

then using grep -i <keyword> * you can search for anything you've twittered in the past.

Note: Use Wget sparingly.

Send a message to Twitter using Ruby

This code updates your presence on your Twitter account.
require 'rubygems'
require 'twitter'

twitter ||= Twitter::Base.new('myusername', 'mypassword')
twitter.post('sending this from irb')

Reference: RSS Twitter Bot [dzone.com], twitter.rubyforge.org [rubyforge.org]
see also: Building a Twitter Agent with Ruby and Rails [rubyinside.com]

'Delete a Twitter entry' dissected

The following code was copied from my Twitter home page, it shows how to delete a twitter entry on the server.

raw HTML code with embedded JavaScript code.

<a href="/status/destroy/719423092" onclick="if (confirm('Sure you want to delete this update? There is NO undo!')) 
{var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 
'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); 
m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = 
document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); 
s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); f.appendChild(s);f.submit(); };return false;" 
title="Delete this update?">


same code as above but with comments.
<a href="/status/destroy/719423092" onclick="

                     // if the user clicks the 'OK' button the confirm function will return true
if (confirm('Sure you want to delete this update? There is NO undo!')) { 

  // -- dhtml: creating html elements on-the-fly -------------------------------
  var f = document.createElement('form'); // create the dhtml 'form' (<form/>) element
  f.style.display = 'none';               // hide the form
  this.parentNode.appendChild(f);         // append the form element to the parent of the current node (<a/>)
  f.method = 'POST';                      // add the method to the form
  f.action = this.href;                   // add the action using the href of the current node (<a/>)
    
  var m = document.createElement('input');   // create the input (<input/>) 'element' 
  m.setAttribute('type', 'hidden');          // set the input type to 'hidden'
  m.setAttribute('name', '_method');         // set the input name to '_method'
  m.setAttribute('value', 'delete');         // set the input value to 'delete'
  f.appendChild(m);                          // append the input element to the form element
  
  var s = document.createElement('input');   // create another input element
  s.setAttribute('type', 'hidden');          // set the type to 'hidden'
  s.setAttribute('name', 'authenticity_token'); // set the name to 'authenticity_token'
  
                                     // set the input element's value using a unique id.
  s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); 
  
  f.appendChild(s);                  // apend the input element to the form element
  // -- end of dhtml: creating html elements on-the-fly -------------------------------
  
  f.submit(); // post the form data back to the server to delete the record, 
              // just as if the user had pressed the submit button.
};

  return false; // returning false cancels the default <a href="..."> request. 
                 // However if JavaScript had been disabled for some reason the 
                 // <a href="..."> would have acted normally, meaning the record 
                 // would have been deleted from following the URL request directly.
 "

Note: Twitter needs JavaScript for the web page to work properly, I've tried and it is not possible to delete a record without JavaScript. The authenticity_token has been altered by me to prevent any malicious activity on my Twitter account.

automate linking to Twitter users

this method searches for @some_user in a string (txt) and links found matches to the twitter-page of some_user

def link_twitter_user(txt)
	if match = txt.match(/.*?(@)((?:[a-z][a-z]+))(:|\s)/i)
		user = match[2]
		txt.gsub!(user, '<a href="http://twitter.com/' + user + '">' + user + '</a>')
	end
	txt
end

Twittering around in Ruby

This code uses the Twitter4R v0.2.0 which is a complete Ruby library that provides access to all documented Twitter REST APIs (and some experimental features).

Read more at:
http://twitter4r.rubyforge.org
http://snakesgemscoffee.blogspot.com/2007/07/twitter4r-020-release.html

You will first need to install the Twitter4R Ruby Gem: <tt>sudo gem install twitter4r</tt>.
require('rubygems')
gem('twitter4r', '>=0.2.0')
require('twitter')

login = 'mylogin' # change this
password = 'mypass' # change this
friend = 'myfriend' # change this

client = Twitter::Client.new(:login => login, :password => password)
public_timeline = client.timeline_for(:public) do |status|
  # do something here with each individual status in timeline that is also returned
  puts status.text
end

# can also pass a block like above to process each individual status object returned in timeline
friends_timeline = client.timeline_for(:friends) 

# same as above with block if you want
friend_timeline = client.timeline_for(:friend, friend)

# Retrieve the user object (with all public profile information) for my friend
user = Twitter::User.find(friend)

# If I don't want to be friends any more I "defriend" the user...
user.defriend

# Now I realize that was a terrible mistake and "befriend" them...
user.befriend

# At this point I want to send them a private message to let them know I made a mistake
# You can do this in two ways.
message = Twitter::Message.create(:client => client, :user => user, 
  :text => "I didn't really mean to defriend you.  Sorry!")
# OR...
message = client.message(:post, "I didn't really mean to defriend you.  Sorry!", user)

# Now I want to post a new status to my own timeline.
# This can be done one of two ways...
status = Twitter::Status.create(:client => client, :text => 'Sleeping off the beer from last night')
# OR...
status = client.status(:post, 'Sleeping off the beer from last night')

# Now I realize my mother is on twitter and wouldn't like to see me talking about beer,
# so assuming she doesn't have IM or SMS alerts we can delete the evidence....
client.status(:delete, status)

tw.conf

// Example configuration file for tw.py.

config = "tw.conf"
username = "mcandre"
rootauthurl = "http://twitter.com/statuses/"
useragent = "tw.py 0.0.1"
statusdelimeter1 = "<p class=\"entry-title entry-content\">"
statusdelimeter2 = "</p>"

Twitter bot weatherlisbon

This little bash script shows how to use curl, grep, tail, sed and perl one-liners in order to compose a bleeding-edge twitter bot.
This one returns daily weather forecasts for Lisbon city based on the BBC weather forecast rss feed.

#! /bin/sh

#Goto here
here=/home/guillaume/Personal
cd $here

#BBC Lisbon weather id
id=0048

#BBC weather RSS feed address
feed="http://feeds.bbc.co.uk/weather/feeds/rss/5day/world/${id}.xml"

#City
city=lisbon

#temporary file
file="weather${city}"

#Weather twitter bot
twitbot=weatherlisbon:*******

#Timestamp the log file
echo .>> $file.log
date >> $file.log

#Read the RSS feed and filter it
curl $feed | grep 'title' | tail -n 1 | perl -wlne'm/title>(.*)<\/title/i && print $1' | sed -e "s/&#xB0;//g" > $file.txt

#Read the forecast into a weather variable
read weather < $file.txt

#Twit the weather variable away
curl --basic --user $twitbot --data status="$weather" http://twitter.com/statuses/update.xml >> $file.log
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS