Ruby twitter bot in 25 lines

Using ruby to make a tiny twitter bot is so simple. So in 25 lines I used the twitter and hpricot gems to make a bot that pulls a random quote from the puerile b3ta.com/talk.

# Rakefile

require 'rake'
require 'twitter'
require 'hpricot'
require 'open-uri'
namespace :b3ta do
  desc 'find a random quote from b3ta.com/talk and post it to twitter'
  task :random_quote do
    hdoc = Hpricot(open('http://www.b3ta.com/talk').read)
    subs = []
    hdoc.search(".post1, .post2") do |post|
      username, subject = '', ''
      post.search(".username") do |un|
        username = un.inner_html
      end
      post.search("b") do |b|
        subject = b.inner_html.to_s.gsub(/<\/?[^>]*>/, "")
      end
      subs << "\"#{subject}\" #{username}" if subject != ''
    end
    message = subs[rand(subs.size - 1)]
    twitter = Twitter::Base.new('twitter_username','twitter_password')
    twitter.post(message)
    puts message
  end
end

To set it up and running, just put in a real twitter account and use “rake b3ta:random_quote”. Simple. Ok it may lack any error checking what so ever, but its still amazing what you can do with Ruby with such little code. (check out the rather offensive twitter feed here)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>