Ruby twitter bot in 25 lines
Posted: November 30th, 2008 | Author: Andy | Filed under: ruby | No Comments »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
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 << "\"\" " 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