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 11-16 of 16 total

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>.
   1  
   2  require('rubygems')
   3  gem('twitter4r', '>=0.2.0')
   4  require('twitter')
   5  
   6  login = 'mylogin' # change this
   7  password = 'mypass' # change this
   8  friend = 'myfriend' # change this
   9  
  10  client = Twitter::Client.new(:login => login, :password => password)
  11  public_timeline = client.timeline_for(:public) do |status|
  12    # do something here with each individual status in timeline that is also returned
  13    puts status.text
  14  end
  15  
  16  # can also pass a block like above to process each individual status object returned in timeline
  17  friends_timeline = client.timeline_for(:friends) 
  18  
  19  # same as above with block if you want
  20  friend_timeline = client.timeline_for(:friend, friend)
  21  
  22  # Retrieve the user object (with all public profile information) for my friend
  23  user = Twitter::User.find(friend)
  24  
  25  # If I don't want to be friends any more I "defriend" the user...
  26  user.defriend
  27  
  28  # Now I realize that was a terrible mistake and "befriend" them...
  29  user.befriend
  30  
  31  # At this point I want to send them a private message to let them know I made a mistake
  32  # You can do this in two ways.
  33  message = Twitter::Message.create(:client => client, :user => user, 
  34    :text => "I didn't really mean to defriend you.  Sorry!")
  35  # OR...
  36  message = client.message(:post, "I didn't really mean to defriend you.  Sorry!", user)
  37  
  38  # Now I want to post a new status to my own timeline.
  39  # This can be done one of two ways...
  40  status = Twitter::Status.create(:client => client, :text => 'Sleeping off the beer from last night')
  41  # OR...
  42  status = client.status(:post, 'Sleeping off the beer from last night')
  43  
  44  # Now I realize my mother is on twitter and wouldn't like to see me talking about beer,
  45  # so assuming she doesn't have IM or SMS alerts we can delete the evidence....
  46  client.status(:delete, status)

tw.conf

// Example configuration file for tw.py.

   1  
   2  config = "tw.conf"
   3  username = "mcandre"
   4  rootauthurl = "http://twitter.com/statuses/"
   5  useragent = "tw.py 0.0.1"
   6  statusdelimeter1 = "<p class=\"entry-title entry-content\">"
   7  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.

   1  
   2  #! /bin/sh
   3  
   4  #Goto here
   5  here=/home/guillaume/Personal
   6  cd $here
   7  
   8  #BBC Lisbon weather id
   9  id=0048
  10  
  11  #BBC weather RSS feed address
  12  feed="http://feeds.bbc.co.uk/weather/feeds/rss/5day/world/${id}.xml"
  13  
  14  #City
  15  city=lisbon
  16  
  17  #temporary file
  18  file="weather${city}"
  19  
  20  #Weather twitter bot
  21  twitbot=weatherlisbon:*******
  22  
  23  #Timestamp the log file
  24  echo .>> $file.log
  25  date >> $file.log
  26  
  27  #Read the RSS feed and filter it
  28  curl $feed | grep 'title' | tail -n 1 | perl -wlne'm/title>(.*)<\/title/i && print $1' | sed -e "s/&#xB0;//g" > $file.txt
  29  
  30  #Read the forecast into a weather variable
  31  read weather < $file.txt
  32  
  33  #Twit the weather variable away
  34  curl --basic --user $twitbot --data status="$weather" http://twitter.com/statuses/update.xml >> $file.log

tw.py

// Sets and views Twitter status

   1  
   2  #!/usr/bin/env python
   3  
   4  __author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
   5  __date__="17 Jun 2007 - 28 Jun 2007"
   6  __copyright__="Copyright 2007 Andrew Pennebaker"
   7  __license__="GPL"
   8  __version__="0.0.1"
   9  __credits__="Based on tweetyPy (http://muffinresearch.co.uk/archives/2007/03/24/tweetypy-python-based-cli-client-for-twitter/)"
  10  __URL__="http://snippets.dzone.com/posts/show/4150"
  11  
  12  import sys, getopt, getpass, urllib, urllib2
  13  
  14  import configreader
  15  
  16  STATUS_MODE="STATUS"
  17  VIEW_MODE="VIEW"
  18  COMMAND_MODE="COMMAND"
  19  
  20  COMMANDS="""Command\t\tMeaning
  21  
  22  d username\tDirect Text
  23  @username\tReply
  24  follow username\tReceive updates via phone or IM
  25  leave username\tStop following username
  26  leave all\tStop following all friends
  27  remove username\tRemove username from friends list
  28  delete username\tDelete username from friends list
  29  get username\tGet the last update from username
  30  get\tGet the most recent updates from all friends
  31  nudge username\tTwitter aks what the person is currently up to
  32  whois username\tGet username's bio
  33  add phonenumber\tSend text invite. If already a member, invite will turn into a friend request.
  34  accept username\tAccept username as a friend
  35  deny username\tDeny username as friend"""
  36  
  37  def usage():
  38  	print "Usage: %s [options]" % (sys.argv[0])
  39  	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
  40  	print "\n-u|--username <username> specified in tw.conf"
  41  	print "-s|--status mode"
  42  	print "-v|--view status"
  43  	print "-l|--list-commands List Twitter commands"
  44  	print "-c|--config <configfile>"
  45  	print "-h|--help"
  46  
  47  	sys.exit()
  48  
  49  def set_status(settings, status):
  50  	auth=urllib2.HTTPPasswordMgrWithDefaultRealm()
  51  	auth.add_password(None, settings["rootauthurl"], settings["username"], settings["password"])
  52  	authHandler=urllib2.HTTPBasicAuthHandler(auth)
  53  	opener=urllib2.build_opener(authHandler)
  54  
  55  	url="http://twitter.com/statuses/update.xml"
  56  	post=urllib.urlencode({"status":status})
  57  
  58  	request=urllib2.Request(url, post)
  59  	request.add_header("User-Agent", settings["useragent"])
  60  
  61  	try:
  62  		response=opener.open(request)
  63  	except IOError, e:
  64  		raise "Could not connect."
  65  
  66  def view_status(settings):
  67  	url="http://twitter.com/"+settings["username"]
  68  	message=""
  69  
  70  	statusdelimeter1=settings["statusdelimeter1"]
  71  	statusdelimeter2=settings["statusdelimeter2"]
  72  
  73  	try:
  74  		instream=urllib.urlopen(url)
  75  		for line in instream:
  76  			if statusdelimeter1 in line:
  77  				message=line[
  78  					line.index(statusdelimeter1)+len(statusdelimeter1):line.index(statusdelimeter2)
  79  				]
  80  				break
  81  		instream.close()
  82  
  83  		return message
  84  				
  85  	except IOError, e:
  86  		raise "Could not connect."
  87  
  88  def main():
  89  	global STATUS_MODE
  90  	global VIEW_MODE
  91  	global COMMAND_MODE
  92  	global COMMANDS
  93  
  94  	sysArgs=sys.argv[1:]
  95  
  96  	mode=STATUS_MODE
  97  
  98  	settings={
  99  		"config":"tw.conf",
 100  		"username":"mcandre",
 101  		"rootauthurl":"http://twitter.com/statuses/",
 102  		"useragent":sys.argv[0]+" "+__version__,
 103  		"statusdelimeter1":"<p class=\"entry-title entry-content\">",
 104  		"statusdelimeter2":"</p>"
 105  	}
 106  
 107  	optlist, args=[], []
 108  	try:
 109  		optlist, args=getopt.getopt(sysArgs, "u:svlc:h", ["username=", "status", "view", "list-commands", "config=", "help"])
 110  	except:
 111  		usage()
 112  
 113  	for option, value in optlist:
 114  		if option=="-c" or option=="--config":
 115  			settings["config"]=value
 116  
 117  	try:
 118  		configreader.load(open(settings["config"], "r"), settings)
 119  	except IOError, e:
 120  		pass
 121  
 122  	for option, value in optlist:
 123  		if option=="-h" or option=="--help":
 124  			usage()
 125  
 126  		elif option=="-u" or option=="--username":
 127  			settings["username"]=value
 128  		elif option=="-s" or option=="--status":
 129  			mode=STATUS_MODE
 130  		elif option=="-v" or option=="--view":
 131  			mode=VIEW_MODE
 132  		elif option=="-l" or option=="--list=commands":
 133  			mode=COMMAND_MODE
 134  
 135  	if mode==STATUS_MODE:
 136  		if len(args)<1:
 137  			usage()
 138  
 139  		message=" ".join(args)
 140  
 141  		settings["password"]=getpass.getpass()
 142  
 143  		set_status(settings, message)
 144  	elif mode==VIEW_MODE:
 145  		print view_status(settings)
 146  	elif mode==COMMAND_MODE:
 147  		print COMMANDS
 148  
 149  if __name__=="__main__":
 150  	try:
 151  		main()
 152  	except KeyboardInterrupt, e:
 153  		pass

RSS Twitter Bot

Republish an RSS feed on a twitter account. This was the source I used to run the Woot Twitter Bot before they took it over.

   1  
   2  require 'rubygems'
   3  require 'active_record'
   4  require 'simple-rss'
   5  require 'open-uri'
   6  require 'twitter'
   7  
   8  #twitter account to post to
   9  twitter_email = "yourtwitteremail@bla.com"
  10  twitter_password = "secret"
  11  
  12  #rss feed to post
  13  rss_url = "http://yoursite.com/index.xml"
  14  rss_user_agent = "http://twitter.com/yourbot"
  15  
  16  #sqlite db
  17  path_to_sqlite_db = "/PATH/TO/db.sqlite"
  18  
  19  
  20  ActiveRecord::Base.logger = Logger.new(STDERR)
  21  ActiveRecord::Base.colorize_logging = false
  22  
  23  ActiveRecord::Base.establish_connection(
  24      :adapter => "sqlite3",
  25      :dbfile  => path_to_sqlite_db
  26  )
  27  
  28  #uncomment this section the first time to create the table
  29  #
  30  #ActiveRecord::Schema.define do
  31  #    create_table :item do |table|
  32  #        table.column :title, :string
  33  #        table.column :link, :string
  34  #    end
  35  #end
  36  
  37  class Item < ActiveRecord::Base
  38    def to_s
  39      "#{self.title[0..(130-self.link.length)]} - #{self.link}"
  40    end
  41  end
  42  
  43  #run the beast
  44  rss_items = SimpleRSS.parse open(rss_url ,"User-Agent" => rss_user_agent)
  45  
  46  for item in rss_items.items
  47    Item.transaction do
  48      unless existing_item = Item.find(:all, :conditions => ["link=?", item.link]).first
  49        twitter ||= Twitter::Base.new(twitter_email, twitter_password)
  50        new_item = Item.create(:title => item.title, :link => item.link) 
  51        twitter.post(new_item.to_s)
  52      end
  53    end
  54  end


Run this once with the lines uncommented to create the DB, then slap it in your crontab.

Tumblr: Turn Twitter Posts into Quotes

Stick the following code in your Tumblr custom template to turn the posts from your Twitter feed into quotes.

YMMV. I use the Litewire theme and import my Twitter feed as Regular posts without titles.

I used to use this on timmorgan.org, but I don't any more. In fact, Tumblr has changed so much since I wrote this, I'm not sure it still works.

   1  
   2  <script type="text/javascript">
   3      onload = function() {
   4        var divs = document.getElementsByTagName('div');
   5        for(var i=0; i<divs.length; i++) {
   6          if(divs[i].className == 'regular' && divs[i].innerHTML.match(/\(via.*Twitter\s\//)) {
   7            divs[i].className = 'quote';
   8            var q = divs[i].innerHTML;
   9            var t = q.replace(/^\s*.*?:/, '').replace(/\(via [^\)]+\)/, '');
  10            size = (t.length > 75) ? 'medium' : 'short';
  11            try {
  12              divs[i].innerHTML = '<div class="quote_text"><span class="' + size + '">' + t + '</span></div><div class="source">' + q.match(/\((via [^\)]+)\)/)[1] + '</div>';
  13            } catch(e) {}
  14          }
  15        }
  16      }
  17  </script>
« Newer Snippets
Older Snippets »
Showing 11-16 of 16 total