Writing a Twitter Bot

Table of contents

No heading

No headings in the article.

Hi,
This will be an introduction to writing a Twitter Bot to reply to conversations for Beginners. I will be using  Python for coding the Bot.
Twitter Bot are a common these days and are used for different purposes, one may use bot for his/her personal account to reply for the tweets  mentioning them  or one may use them to follow some user and retweet their tweets .

Twitter provides  huge set of functionality through its APIs .You can nearly perform all the tasks that can be performed on the twitter site through these APIs. And good part is that they provide it for free.

Getting API keys from twitter

  • Create a Twitter app to get the credentials which can be done at https://apps.twitter.com/ . On successful creation of an app select your app and you will be redirected to app page:



  • You will be provided with following credentials  which can accessed through keys and access tokens tab:
    • Consumer Key (API Key)
    • Consumer Secret (API Secret)
    • Access Token
    • Access Token Secret

Documentation for the twitter API can be accessed on https://dev.twitter.com/docs

Creating a bot

I will be using  Twython module for accessing twitter API.

Installing Twython

Twython can be easily installed using pip package manger or easy install

$ easy_install twython
$ pip install twython

Documentation of Twython can be seen here https://twython.readthedocs.io/en/latest/index.html

Once the installation of the package is done we can seamlessly use the twitter API through Twython.
I will be using Twitter Search API for fetching the tweets which our bot will be replying for. I encourage to read the difference between Search and Stream API of twitter.
#importing the Twython module
from twython import Twython
#creating an object of Twython with our credentials of twitter app
twitter=Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
 Main task of Twitter bot will be 
  • Searching for the mentions for a username(@abc)
  • replying to the tweet with that mention
#reading the last id from the file to be passed as since_id which will only fetch the tweets with id>since_id
#for the first run this should be skipped as we want to fetch all the tweets 
fo = open("last_id.txt", "r")
id=int(fo.read())
print "id is",id
# Close opened file
fo.close()
#searching for the tweets
results = twitter.search(q='@username',since_id=last_id)

#many arguments can be passed to the search function which can be seen in the Twython documentation's searching section

#fetching the tweets from twitter
if results.get('statuses'):
  #Iterating over the cursor for the tweets
  for result in results['statuses']:
    print"tweet is",json.dumps(result)
    id=result['id']
    fo = open("last_id.txt", "w")
    fo.write(str(id))
    fo.close()
    twitter.update_status(status='write your message here',in_replyto                          status_id=result['id'])
    print "status posted"


Here to prevent fetching same tweet again and again and for replying to a particular tweet I am using the ID field .
This section can be run in an infinite loop which can put to sleep after each iteration .

For the very first run since_id should be removed and the last id that is fetched from twitter can be stored in a file and can be used as input for since_id field for subsequent calls to twitter, which will avoid duplication.



Thanks for Reading, also checkout my Youtube Channel for interesting content.
Happy Reading