Making A Twitter Bot in Python

nicholas read
Chatbots Life
Published in
9 min readDec 27, 2019

--

So if you follow me on medium you know I am doing a project where I post to Github more often in 2020. To keep track of all of my commits I thought it would be cool to make a Twitter bot that logs every time I make a commit to my git hub and then tweets out my progress at the end of the day. It’s a simple bot but I really liked the process of making it and wanted to share how I did that with everyone.

In this post, I cover what my process looks like when I approach a task like this, I also cover the tools that I used and why I used them. This is a great opportunity to work with Python, the Twitter & Git APIs as well as Heroku. We will cover how to handle the cloud aspect with Heroku in the second part of this blog series. I am going to take you step by step through how I started this project with images of where to go to get your API keys and some code that is written in Python. This is designed to be a very easy and fun project and I think it is a great one for anyone starting out in programming that wants to expand their skills.

Step 1: How to start

This is always one of the hardest parts of any project, starting the damn thing. I always think it is helpful to think about the end goal and even write it down, then back into the steps that get you there. So for this project what is our end goal? We want to make a Twitter bot that tweets out if we have made a commit to our git hub page. Perfect, now that we have that goal in mind we can start putting the pieces together! We will need to use Twitter’s API to post the tweet, Git hubs API to access our post history, and then we will need to write the code in Python to drive this process. So far so good.

Top 4 Bot Tutorials

1. Building an Instagram Bot with Python and Selenium to Gain More Followers

2. Adding Chatbots to Your Stream Chat App Using Google’s Dialogflow

3. DialogFlow fulfillment — dynamic responses from Google Firestore

4. Chatbot Conference 2020

Step 2: Gathering our Materials & Creating Structure.

I always find it useful to open up a file and start adding some markdown or comments to give the project some structure. The first file we will make is a Twitter_bot.py. There are for main parts to this file the Imports, Keys for the APIs, Authentication, and Code.

Twitter API

Let’s go ahead and get our API keys through Twitters developer platform here before moving on. Fill in the information Twitter requires you to provide to get your keys (general things like what the bot is going to do, do you plan on gathering data, etc.) then you should come to a page like this after you confirm your email and Twitter account.

in the top right of the screen, you should see your profile name. Click the drop-down and navigate to get started. From here you can click the blue button on the right that says create an app to get your keys!!

After this process, you will finally have your keys ready for use in your code

WARNING!! Do not release your keys to anyone that is not supposed to have them and definitely don’t accidentally push them up to git hub.

Git hub API

Using the Git hub API is much easier than Twitter. We will only need to have the username and password for our git hub account on hand so make sure you sign up for a git hub account before proceeding.

Step 3: Writing the Bot

Imports

With a quick few Google searches we can find the appropriate API documentation for this project Twitter: tweepy , Github: PyGithub you can install both of these via the pip install command. We will also need to get the time these events happened at, so also make sure to install datetime to handle this. The final part is to import environ. We will go over this import when it comes to the keys. The first part of your file should look something like this

# Imports
from os import environ
from github import Github
from datetime import datetime
from tweepy import OAuthHandler
import tweepy
import time

Keys for the API’s

To start we need to load in our keys. In a separate file set your variable names for each of the keys. You need to make sure that the naming is consistent for both files. For me, I like to keep to the Twitter documentation suggestions for naming so I will use all caps. To run this locally feel free to ignore the environ['UNIQUE_KEY_NAME’] for the time being and just add your key as a string. This is fine for testing if the code works just to make sure you take them out before you make your bot public.

The reason we use environment variables here is that we will be pushing this up to a Git hub and we want to keep these keys private. Setting them as environment variables allow us to access the keys without putting them in the code this is why we imported environ from os back in the import section. So I strongly advise you to make a separate keys.py file if you are going to make this bot public-facing at any point.

The keys.py file should be set up like this:

CONSUMER_KEY    = 'Your consumer key from twitter here'
CONSUMER_SECRET = 'your consumer secret key from twitter here'
ACCESS_KEY = 'your access key from twitter here'
ACCESS_SECRET = 'your access secret key from twitter here'
username = 'your git hub user name here'
password = 'your git hub password here'

We are also going to set this bot to tweet every day so the interval is going to be set to 60 * 60 * 24 we will use this to make our bot sleep for this amount of time which is equal to 1 day. We will also declare a variable d to be today's date using a date time object. Your Twitter_bot.py file should now contain this section

# adding our keysCONSUMER_KEY = environ['CONSUMER_KEY']
CONSUMER_SECRET = environ['CONSUMER_SECRET']
ACCESS_KEY = environ['ACCESS_KEY']
ACCESS_SECRET = environ['ACCESS_SECRET']
username = environ['username']
password = environ['password']
INTERVAL = 60 * 60 * 24
d = datetime.today()

Authentication

Now we can authenticate our APIs. This lets our program talk with Twitter and request or post information. We are going to use the variable names api for Twitter and g for Git hub this is just for ease of use and to cut down on the number of keystrokes you need to perform. You can add the following code to Twitter_bot.py

# twitter and git hub api authenticationauth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
# git hub username and password
g = Github(username, password)

Code / Controle Flow

In thinking through this program I just want to check if I have tweeted then do some operation but for it to run indefinitely. So to do this we can set the while loop equal to True. Inside the while loop, we will pull down our list of repos and extract the date time object associated with each one them and put those into a list. We can then check if the current date is in our list of date time object and if that is true post a tweet and else tweet out that we didn’t post anything. I would also like to keep track of how many days in a row my streak is so I will add a count variable to the program and because it runs every day the count will update every time the program runs. Finally outside of our for loop we can add time.sleep(INTERVAL) to make the function wait for 24hours until it does it aging So in code it looks like this.

# while loop that runs indefinitely that check if my dates.
while True:
days_updated= []
count = 0
# for loop to get all the repo times and append them to a listfor repo in g.get_user().get_repos():
days_updated.append(repo.updated_at.date())
# if else block to check if todays date is in the list of dates of # reposif d.date() in days_updated:
api.update_status(f'yes he did, he updated: {repo.name}')
print('I tweeted that he pushed')
count +=1
else:
api.update_status(f"No he didn't he broke a {count} day long streak")
print('I tweeted that he did not push')
# this sleep operation takes the INTERVAL variable and sleeps for #24hrstime.sleep(INTERVAL)

AND JUST LIKE THAT YOU HAVE MADE A BOT!!!

If you run this program in your terminal with your keys input as a string, you will be able to see the program post to Twitter then wait for 24 hrs and go through the whole process again. So now you can tell all your friends “Look at me I can post to Twitter without actually going on Twitter how cool is that!!” You can navigate over to Twitter and see that your bot has posted.

This is a great first step but we have a few more steps to make this a proper bot.

Dealing With Errors

Within some timeframes, Twitter won’t allow you to post the same tweets so if a tweet is duplicated it will throw an error. We can get around this by using a try and except block around our if else statements. I have made mine a little fancy in the final codebook but if you just want to circumnavigate the error messages you can just do this:

try:
if d.date() in days_updated:
api.update_status(f'yes he did, he updated: {repo.name} he is on a {count} day streak')
print('I tweeted that he pushed')
else:
api.update_status(f'{didnt_push[randrange(3)]} he has broke a {count} day streak')
print(f'I tweeted that he did not push')
time.sleep(INTERVAL)
except:
print('error duplicated tweet')
pass

Next steps

Now some of you might have noticed a bit of a problem with this… You might be saying “ Great but I don’t want to keep my computer running this program all the time.” “what if I turn off my computer?” or “what if my wifi connection is interrupted and can’t post to Twitter, then what!!” that is exactly why we are going to push this up to the cloud and let it run on a web server rather than on our local machine!

Pushing This up to the Cloud

Check out part two where I walk you through how to get this pushed up to Heroku a cloud platform service supporting several programming languages including Python, node.js, and PHP.

Link to my Twitter bot

Link to my Github project

Shameless plug for my twitter too

Don’t forget to give us your 👏 !

--

--