You are reading..

How to build your Twitter bot Part 1

In case you want to build a Twitter bot, it is quite easy with ruby and a few gems. We will write a small bot that will know a list of target persons and try to follow them and chat them up with some pickup lines.

Well I know this is kind of close to spam, so please use caution, but in part 2 I will try to teach the bot to write something more sophisticated in order to be useful. Plus it might definitely make much more sense to have some state machine mechanism in the background to control the robot. But we will start with something easy now.

To get started all you will need in ruby are those libraries twitter, csv, logger, yaml. The twitter gem is great to handle everything that has to do with Twitter. The logger gem is great if you want to maintain a log file of all the things that are going on.The remaining csv and yaml gems are practical to write down some human readable config files. So that is the code we have so far.

require 'rubygems'
require 'twitter'
require 'csv'
require 'logger'
require 'yaml'

class Twitterbot
    attr_accessor :persons_to_text_ids, :twitter_config, :log

    def initialize(config_file)
        @twitter_config = YAML.load_file(config_file)
        @log = Logger.new(@twitter_config["log_file"])

        #Read in Pickup Lines
        @pickup_lines = CSV.read(@twitter_config["pickup_file"])

        #Read in People to Follow
        @persons_to_follow_ids = CSV.read(@twitter_config["persons_file"]).flatten.collect{|f| f.to_i}


Obviously we need some config file and a follower file. The config file will contain everything config parameter for a given account and the follower file will contain the followers per account that the account should follow.

#Config Twitterbot
consumer_key: "your consumer key"
consumer_secret: "your consumer secret"
access_token: "your access token"
access_token_secret: "your access token secret"

#Configure Behavior
persons_file: "your persons file.csv"
log_file: "your log file.log"
pickup_file: "your file with pickup lines.csv"
message_people: true

Ok lets have a look on the persons file. This is a simple .csv file where we will put a twitter id in each line:


And lets have a look at the pickup lines file. It should contain some “pickup lines” that the bot writes towards this person.

I've seen you are enthousiastic about xyz. Want to chat about it?
Have you heard about our xyz. I am quite interested in xyz. Do you want to be friends?

Well now we have everything that bot needs in order to get started. It only needs a method where he addresses the persons.

def at_message(user)
            pickup_line = "@#{user.screen_name} #{@pickup_lines[rand(@pickup_lines.length)]}"
            @log.info "At Messaged: #{pickup_line}"
            @log.error "Failed to adress member #{user.screen_name}"

So you see we are using the log to note down whatever the bot did. Well now its time for a test run. So fire up your ruby console (irb) and load yourself a bot and have a look if it addresses our first person in the list.

require 'init'
t = Twitterbot.new("your config file")
user = t.persons_to_text_ids[0]

I hope that works for you. If it does you can create a small robot.rb file that you going to call by a cronjob.

require 'init'

#Config Robot Client
if ARGV[0] == nil
    puts "You have to provide a config file e.g. ruby robot.rb twitter.yml"
    t = Twitterbot.new(ARGV[0])

if t.twitter_config["message_people"] == true

Finally the last thing left is to call the robot periodically using a cronjob. (Use: crontab -e) Lets suppose you want to call it every hour:

*/60 * * * * cd /home/plotti/twitterbot/;  ruby robot.rb your_config_file.yml

Tadaaa, you are done. Now you have  a bot that wakes up every hour and texts one of the people in the list.

As already mentioned, its not very useful and even quite spam like behavior, but I promise we will make the bot a bit smarter in the next episode in order to be useful.

Cheers Thomas


About plotti2k1

Thomas Plotkowiak is working at the MCM Institute in the Social Media and Mobile communication group which belongs to the University of St. Gallen. His PhD research in Social Media is researching how the structure of social networks like Facebook and Twitter influences the diffusion of information. His main focus of work is Twitter, since it allows public access (and has a nice API). Make sure to also have a look at his recent publications. Thomas majored 2008 in Computer Science and Economics at the University of Mannheim and was involved at the computer science institutes for software development and multimedia technoIogy: SWT and PI4. During his studies I focused on Artificial Intelligence, Multimedia Technology, Logistics and Business Informatics. In his diploma/master thesis he developed an adhoc p2p audio engine for 3D Games. Thomas was also a researcher for a year at the University of Waterloo in Canada and in the Macquarie University in Sydney. He was part of the CSIRO ICT researcher group. In his freetime thomas likes to swim in his houselake (drei weiher) and run and enjoy hiking in the Appenzell region. Otherwise you will find him coding ideas he recently had or enjoying a beer with colleagues in the MeetingPoint or Schwarzer Engel.


No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: