//
You are reading..
Twitterbots

How to build your Twitterbot part 2


So after building a very annoying bot in part 1 we will try to make it a bit smarter so it can do actually something useful.

Today we will give the bot the methods: get_friends, get_followers, to find out more about himself.

In order to perform some actions we will write the methods: follow_user,  retweet_somebody and favorite_some_tweet.

Follow user will follow a person from our list of persons, retweet_somebody will simply retweet somebody, and favorite_some_tweet will favorite a random tweet.So in a way the robot will mimic a typical user behavior on twitter.

def get_friends(username)
  begin
    result = Twitter.friend_ids(username)
    friends_ids = result.ids
    old_cursor = 0
    next_cursor = result.next_cursor
    while old_cursor != next_cursor and next_cursor != 0
      old_cursor = next_cursor
        result = Twitter.friend_ids username, :cursor => next_cursor
      friends_ids += result.ids
        next_cursor = result.next_cursor
    end
    return friends_ids
  rescue
    @log.error "Couldn't get friends"
  end
 end

 def get_followers(username)
  begin
    result = Twitter.follower_ids username
    followers_ids = result.ids
    old_cursor = 0
    next_cursor = result.next_cursor
    while old_cursor != next_cursor and next_cursor != 0
      old_cursor = next_cursor
      result = Twitter.follower_ids username, :cursor => next_cursor
        followers_ids += result.ids
      next_cursor = result.next_cursor
    end
    return followers_ids
  rescue
    @log.error "Could'nt get followers"
  end
 end

Those two methods are almost similar,  where for a given name we can get the follower resp. friends ids.So having those methods in the Twitterbot class we will use them in the initialization to have a bot that knows something about himself.

def initialize(config_file)
  [...]
  # Adding those lines to our initial init method
  #New find out what my friends are
  @friends_ids = self.get_friends(Twitter.user.screen_name)
  #Find out what my followers are
  @followers_ids = self.get_followers(Twitter.user.screen_name)
end

def retweet_somebody
         begin
            all_retweets = Twitter.retweeted_to_me(:count => 100)
            retweets = []
            #Strategy 1: Only keep english AND keyword AND more then 1 retweet
            all_retweets.each{|e| retweets << e if e.retweeted_status.user.lang == "en" && e.retweeted_status.text.include?(@twitter_config["keyword"]) && e.retweet_count > 1}
                        #Strategy 2: Just retweet the most retweeted retweet.
            #best_retweet = retweets.sort{|a,b| a.retweet_count.to_i  b.retweet_count.to_i} # retweet highly retweeted ones
            if retweets.length > 0
                best_retweet = retweets[rand(retweets.length)]
                Twitter.retweet(best_retweet.id)
                @log.info "Retweeted: #{best_retweet.retweeted_status.text} with RT:#{best_retweet.retweet_count}"
                return best_retweet
            else
                @log.info "Wanted to retweet but found not material matching #{@twitter_config["keyword"]}"
                return []
            end
        rescue
            @log.error "Failed to retweet #{best_retweet.retweeted_status.text}"
        end
 end

The favorite some tweet method works similiar like the retweet method, where we first get a bunch of tweets from our timeline and then consider tweets as favoritable candidates if those tweets have been retweeted by somebody before and if the tweet has been written by some of my followers. We could have come up with a different heuristic but this one works just fine.

def follow_user(user)
  begin
        Twitter.follow(user.screen_name)
        @log.info "Followed person #{user.screen_name}"
        rescue
         cleanup(user,@log)
            @log.error "Could not follow person #{user.sceen_name}"
        end
 end

The follow method simply makes the bot follow a given user. For it to work we will need to add the following lines to the init function in order to have a list of persons that we would like to follow:

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

  #Find out whom of the persons that i should follow i am already following
  @persons_to_follow_ids = @persons_to_follow_ids - @friends_ids

Having written all of those extra functions for the bot we can make our bot logic a bit more intelligent. We will simply roll a dice and depending on the outcome the bot will either follow a person, retweet a person, or facorite a tweet or at_message a person:

#Follow procedure only follow people on a chance 1/3
dice = rand(3)

if dice == 1

 #Chose up to 4 persons
 t.persons_to_follow_ids[0..rand(4)].each do |person_to_follow|

  #Get a User
  user = t.get_user(person_to_follow)

  #Follow
  if t.twitter_config["follow_people"] == true
   t.follow_user(user)
  end

  #At Message
  if t.twitter_config["message_people"] == true
   t.at_message(user)
  end
 end

elsif dice == 2

 #Retweet some of my friends
 if t.twitter_config["retweet_people"] == true
  t.retweet_somebody
 end

elsif dice == 3

 #Favorite some Tweet
 if t.twitter_config["favorite_tweets"] == true
  t.favorite_some_tweet
 end

else
 t.log.info "Skipped run this time"
end

We will call the bot periodically to perform one of the actions and see how he is perceived by persons. Please consider that all of the above is rather an experimental toy example of  a bot and shouldnt be used to build spam bots on Twitter.

Advertisements

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.

Discussion

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: