Home > TwitterHack > TwitterBot by Ruby

TwitterBot by Ruby

  • 2007-11-29 (Thu) 23:46

This tutorial describes how to write your own Twitter bot by Ruby.

Plan

  • Recieves DirectMessages, parses them and sends back responses.
  • Keeps on being connected in Twitter via Jabber protocol.
  • Written in Ruby !

Preparation

Twitter account

You need a twitter account for your bot.

Jabber ID

You need a Jabber ID for your bot to sit in Twitter. I use Jabber.JP service (free!), but you can choice whatever Jabber service you like.

If you use a GMail address for your bot, you can skip above step. (I could not connect to GTalk by GMail sub account, so took a different way)

Requirements

Code

#  Tiny Twitter Bot.
#
require 'rubygems'
require 'xmpp4r'
require 'kconv'
 
class Reciever
  attr_accessor :client
 
  # user : Jabber ID
  # pass : Password
  def initialize(user, pass)
    @end = false
    Jabber::debug = true
 
    # connect Jabber client to the Server
    @client = Jabber::Client.new(Jabber::JID.new(user), false)
    @client.connect
    @client.auth(pass)
    @client.send(Jabber::Presence::new)
 
    thread = Thread.current
 
    # a callback to parse recieved messages
    @client.add_message_callback do |message|
      unless message.type == :error
        if message.body =~ /Direct from (.*):/ # who sends DirectMessage ?
          sender = $1
          msg = message.body.split(/\r?\n/)
          msg.shift # cut Direct from ...
          msg.pop # cut last line, too
          body = msg.join
 
          #
          # do whatever you like in following lines :)
          #
          if body =~ /!abort/ # finish if told 'abort'
            @client.send(Jabber::Message::new(message.from, "d #{sender} aborting...").set_type(:chat))
            thread.wakeup
          else
            # it just echoes in this example
            xxx = Kconv.toutf8("d #{sender}\n#{message.body}")
            @client.send(Jabber::Message::new(message.from, xxx).set_type(:chat))
          end # if body
        end # if direct
      end # unless error
    end # callback
 
    @watcher = Thread.new do
      while not @end
        # saying "I'm alive!" to the Jabber server
        @client.send(Jabber::Presence::new)
        sleep 30
      end
    end
  end
 
  def close
    @client.close
    @end = true
    @watcher.join
  end
end # Reciever

After that, the only step remains is to create this Reciever class instance from main routine. To kill the bot, send Ctrl-C from the command line.

Let’s do some neat hacks at the lines parsing body by regexp.

Auto Follow

You need to follow your bot.

You may want your bot to counter-follow you automatically. I wrote a simple Procmail recipe and a tiny Ruby script. (original idea is にぽたん研究所::Twitter でイチイチ follow するのが面倒くさい

Procmail recipe

.procmailrc:

:0
* ^To:.your@bot.address
| counter_follow.rb

Ruby script to follow

counter_follow.rb:

#!/opt/local/bin/ruby
require 'open-uri'
 
ID = 'jabber bot ID'
PASSWORD = 'jabber bot password'
 
msg = ARGF.read
msg =~ /\s+http:\/\/twitter.com\/(\w+)$/
screen_name = $1
exit 1 unless screen_name
 
auth = {'Authorization' => 'Basic '+[ID+':'+PASSWORD].pack('m')}
open('http://twitter.com/friendships/create/'+screen_name+'.json', auth)

Usage

  1. Follow your bot from you Twitter account.

    follow bot_account

  2. Send a DirectMessage to your bot.

    d bot_account hello bot !

Conclusion

Wrapped up a recipe how to create a tiny Twitter bot.

There were some pitfalls (it can hang up if you don’t send messages in ‘chat type’, cannot get any responses if you send something periodically, or …) in creating Twitter bot. I hope this tutorial help someone creating their own Twitter bot.


Any feedbacks make me happy :)

Comments:2

netik 08-03-08 (Sat) 11:38

This code is no longer functional because non-threaded mode support was removed from xmpp4r.

Now I get this error when I try to run your code: /retina/lib/ruby/gems/1.8/gems/xmpp4r-0.3.2/lib/xmpp4r/stream.rb:44:in `initialize’: Non-threaded mode was removed from XMPP4R. (RuntimeError)

mootoh 08-03-26 (Wed) 23:22

netik:

use following code to go through.

x @client = Jabber::Client.new(Jabber::JID.new(user), false) o @client = Jabber::Client.new(Jabber::JID.new(user))

Comment Form
Remember personal info

Trackbacks:1

Trackback URL for this entry
http://blog.deadbeaf.org/twitterhack/twitterbot-by-ruby/trackback/
Listed below are links to weblogs that reference
TwitterBot by Ruby from mootoh.log
pingback from Holy Moly » Blog Archive » write your own Twitter bot by Ruby 08-02-24 (Sun) 16:17

[...] CODE und dessen erklaerlichen Erlaeuterungen schaut man sich besser selbst an [...]

Home > TwitterHack > TwitterBot by Ruby

Feeds

Return to page top