Making A Twitter Bot in Python (2022)

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.

Making A Twitter Bot in Python (1)

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.

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

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 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.

Making A Twitter Bot in Python (2)

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!!

Making A Twitter Bot in Python (3)

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

Making A Twitter Bot in Python (4)

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.


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 file if you are going to make this bot public-facing at any point.

The 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 file should now contain this section

# adding our keysCONSUMER_KEY = environ['CONSUMER_KEY']
username = environ['username']
password = environ['password']
INTERVAL = 60 * 60 * 24
d =


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 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():
# if else block to check if todays date is in the list of dates of # reposif in days_updated:
api.update_status(f'yes he did, he updated: {}')
print('I tweeted that he pushed')
count +=1
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)


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.

Making A Twitter Bot in Python (5)

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:

if in days_updated:
api.update_status(f'yes he did, he updated: {} he is on a {count} day streak')
print('I tweeted that he pushed')
api.update_status(f'{didnt_push[randrange(3)]} he has broke a {count} day streak')
print(f'I tweeted that he did not push')
print('error duplicated tweet')

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.

Making A Twitter Bot in Python (6)

Link to my Twitter bot

Link to my Github project

Shameless plug for my twitter too

Making A Twitter Bot in Python (7)
Making A Twitter Bot in Python (9)

Top Articles

You might also like

Latest Posts

Article information

Author: Arline Emard IV

Last Updated: 11/15/2022

Views: 5880

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.