Creating a twitter bot in Python

I live in a village just outside Tunbridge Wells in Kent. Recently there have been several issues with the train line which have affected my commute to London. If I had known of the issues in advance I would have taken action such as working from home or driving to another station. To see what the bot is tweeting about check out it’s page. The reason I decided to publish to twitter was because they have good reliable infrastructure and it would enable others in the local community to benefit by being kept informed. In my case I simply follow @FrantStation and then click on the bell icon in the twitter app so that I’m informed of all tweets from this account.
Any tweets are pushed to the notification centre of my phone and from there are also pushed to my Smart Watch. I can be sat in a meeting at work and be made aware that trains are running late or cancelled, or if the account is noisy in the morning I may decide to work from home or drive to a different station.

So how much effort is it to create a bot which can push information in near real time ? Perhaps you are an IT company providing an SAAS service and would like to provide an easy way for customers to know if there is an outage of your service ? In the last case the monitoring code will be slightly different, perhaps you would use a library like requests to hit a web page and check that it returns 200, with any other response being tweeted out.

Well it turns out that the first version of this code (one big script) was only around 88 lines of code which included logic to make a SOAP request to national rail, extract the relevant information and send a tweet if the train was over 4 minutes late or cancelled. The rail bot is perhaps a little involved so let’s create something simpler.

Firstly head over to https://developer.twitter.com and click on the apply button. You will need to fill in a few details such as the purpose of the account and what it will be tweeting. Note that you might find the main account is blocked which is likely to be case if you have created a new account. In this case you will need to login to the main account and pass the captcha checks to confirm you are a human.
After apply the next step is to create what twitter call and application. In this part you will be able to generate / regenerate 4 keys.

  • API Key
  • API Secret Key
  • Access Token
  • Access Token Secret

Next for this demo we will want to install a few libraries / modules. In order to avoid creating any problems with existing libraries lets create a new virtual environment. If you are writing python code and not taking advantage of virtual environments, it really is about time you started to use them.

This tutorial assume you are using python 3 which already has the venv module available by default

Open up a terminal and make a new folder

  • mkdir TwitterBot
  • cd TwitterBot
  • python3 -m venv venv

The above will create a new subdirectory called venv with a various sub directories.

Assuming you are using linux / osx now type in

  • source venv/bin/activate

This will change you command prompt and ensure you are inside the virtual environment.

Now we want to install some libraries some type the following commands

  • pip install python-twitter
  • pip install requests

We have installed two modules.

  • python-twitter – this will enable us to send tweets from our code
  • requests – this make handling http requests easy. In the sample code we will check if a local web server is running and if it fails we will send a tweet.

Ok we are almost done. Next we want to run a web server. Installing a server such as apache is beyond the scope of this article. Lets just run a basic server using a single command. Open up a new terminal window and type the command below

  • python -m http.server 1234

The above command will start a web server listening on port 1234

Ok now we have a server up an running lets write some code. Save this file as Bot.py in the TwitterBot directory.


def checkServer():
    import requests
    try:
        response = requests.get('http://localhost:1234')
        if response.status_code != 200:
            return False
        else:
            return True
    except:
        return False

def sendTweet(message):
    import twitter
    import datetime
    now = datetime.datetime.now()
    dtNow = now.strftime("%Y-%m-%d %H:%M:%S")
    twitterApi = twitter.Api(consumer_key="YOUR_CONSUMER_KEY",
                             consumer_secret="YOUR_CONSUMER_SECRET",
                             access_token_key="YOUR_ACCESS_TOKEN",
                             access_token_secret="YOUR ACCESS KEY")
    twitterApi.PostUpdate("{} => {}".format(dtNow, message))

if __name__ == '__main__':
    serverStatus = checkServer()
    if not ServerStatus:
        sendTweet(" we are sorry but our server is down we are working to resolve the issue - please be patient")

The above is very simple and will simply check if a server is running / and if not tweet about the problem. As can be seen sending a tweet is very easy you need just 2 lines on code. One to create the object and set the keys and then a call to the PostUpdate method.

Next we probably want a way to schedule this.

On unix type the following

  • crontab -e

Now we need made a to make a scheduled entry to run our simple bot. Lets say we want to monitor and tweet every 5 minutes

*/5 * * * * source /Users/hugo/Projects/TwitterBot/venv/bin/activate && python /Users/hugo/Projects/TwitterBot/Bot.py >> /Users/hugo/Projects/TwitterBot/log.log 2>&1

 

The cron job will check if every minutes. In this case we need to stop the sample server before we will say anything sent out. So go back to the window in which you ran the command python3 -m http.server 1234 and press ctrl-c. When the cron job next runs it will start tweeting about the server being down.

0 Responses to “Creating a twitter bot in Python”



  1. Leave a Comment

Leave a comment