»
S
I
D
E
B
A
R
«
TwitterBot by Ruby
November 29th, 2007 by mootoh

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 :)

6 Responses  
Holy Moly » Blog Archive » write your own Twitter bot by Ruby writes:
February 24th, 2008 at 4:17 pm

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

netik writes:
March 8th, 2008 at 11:38 am

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 writes:
March 26th, 2008 at 11:22 pm

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))

//de writes:
November 17th, 2008 at 2:44 pm

Hello,

Thank you for the code and time you spent writing it.

Just wanted to mentioned there is an extra “r” in the line above where it should be:

gem install xmpp4r

mootoh writes:
November 17th, 2008 at 10:00 pm

//de:

thank you for pointing the typo. I fixed that.

dagobart writes:
February 10th, 2009 at 9:40 am

That’s a nice approach to use jabber and procmail to get immediately to know when some new follower subscribes to your bot.  

I developed a Twitter/Identica chatbot of my own, done in Ruby, and without any dependencies on Jabber or Procmail. Instead, it learns about new/lost follower via polling and follows them back or leaves them accordingly. Every new follower gets greeted with a little welcome message, and a basic help is right built in.

I do not need direct message processing, hence that’s not yet set up.

I’d like to see if you’d give it a try. It’s hosted at sourceforge: http://mb-chatbot.sourceforge.net/

Leave a Reply

»  Substance: WordPress   »  Style: Ahren Ahimsa