Building a Twitter Bot with Python

Learn how to build a bot step by step

Jose Manu (CodingFun)
Towards Data Science

--

Would you imagine to have a Twitter bot that posts different tweets depending on the day of the week? This is possible with Python and Tweepy. Keep reading this story and you will find out how to build a Twitter Bot with Python.

Twitter Bot with Python
Photo by Sara Kurfeß on Unsplash

Setting up a Twitter Development Account and Tweepy

First of all, we need to install tweepy. We can easily install it in the terminal using the pip command:

pip install tweepy

Great, now we have the Python library Tweepy installed. Next, we need to create a Twitter developer account.

Twitter offers a developer platform that provides an API in oder to manage and perform certain activities within our Twitter account. You can have a look at the Twitter API documentation. There are multiple tasks that we can perform through this API. See below some of them:

  • Post and retrieve tweets
  • Follow and unfollow users
  • Post direct messages

However, before we are able to use the Twitter API end points, we need to create a developer account and generate our API keys. You can apply for a developer account directly here. After answering a few questions on how you plan to use the API and accept the Twitter Developer Agreement, you will be granted access to the Developer Dashboard.

Once you are granted access to the dashboard, login to the developer site and create your first App. This step will automatically generate your consumer API keys and access tokens that you should keep secret:

Building a Python Twitter Bot step by step
Twitter API keys

From the Twitter Development platform, we are able to edit the app permissions. I have granted my app permission to read, write and send direct messages.

Please note that the developer account should be linked to the Twitter account where you want to have the bot active. For instance, I use my Crypto News Twitter Account where I build the Twitter bot that I describe in this article.

Building a Twitter bot with Python and Tweepy

Ok, let’s start building our Twitter bot. As mentioned before, we will use the Tweepy library which will make much easier our job.

First, we import tweepy. Tweepy will manage for us the authentication to the API through our secret keys.

As shown in below extract of code, we do this by creating a OAuthHandler instance to handle our login by passing the consumer key and consumer secret as arguments.

Next, in order to be able to make requests to the API, we should send back an access token. For this reason, we use the auth.set_access_token method to store the access request token during our session.

Finally, we are ready to manage our Twitter Account through Python. Note that I have included XXX instead of my real secret keys. Replace XXX by your secret keys that you can obtain in your Twitter Developers Dashboard.

import tweepy 
import datetime
consumer_key = 'XXXX'
consumer_secret = 'XXXX'
access_token = 'XXX'
access_token_secret = 'XXXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)

Our variable api is where we store the auth settings. We will use it to make all requests to the Twitter API going forward.

We have completed half of the job. Next, we can use the update_status method in order to post tweets.

The idea of this twitter bot is to publish a different tweet depending on the day of the week. This can be easily done using if-statements to store the tweet to publish depending on today’s day. Let’s build the logic in our code.

import datetimedef publictweet():
if datetime.date.today().weekday() == 0:
tweettopublish = 'Hi everyone, today is Monday. #Monday '
if datetime.date.today().weekday() == 1:
tweettopublish = 'Enjoy your Tuesday. #Tuesday'
if datetime.date.today().weekday() == 2:
tweettopublish = 'Third week of the Week. #Wednesday'
if datetime.date.today().weekday() == 3:
tweettopublish = 'Thursday. I cannot wait for the Weekend'
if datetime.date.today().weekday() == 4:
tweettopublish = 'Friday...Finally'
if datetime.date.today().weekday() == 5:
tweettopublish = 'Great it is Saturday #weekend #Saturday'
if datetime.date.today().weekday() == 6:
tweettopublish = 'Sunday morning...#Weekend #enjoy '
api.update_status(tweettopublish)
print(tweettopublish)

We use the datetime libary with the weekday method to know what day is today. For instance, if today is Sunday and we run below code, we will get 6 as a result:

print(datetime.date.today().weekday())# above code will print 6 if today was Sunday, 0 if today was Monday, 1 if today was Tuesday and so on.

Therefore, only one of the if statements will be true. And therefore, that will be the Tweet that we will save in the variable tweettoppublish.

Finally, with the method update_status(tweettopublish), we are able to post the tweet in our Twitter timeline. As you can see below, today it is Sunday and therefore, by running the publictweet function, the API is positing the Sunday Tweet.

publictweet()
Building a Twitter Bot with Python
Building a Twitter Bot with Python

Other Functionalities to Include in a Python Twitter Bot

In addition to posting tweets, we can perform some other cool tasks with a Python Twitter Bot. We could for example:

Wrapping up

With only a few lines of code, we managed to build an amazing Twitter bot and we have it running now in our Twitter account!

Enjoy your new bot and feel free to expand it with new features! Thank you for reading!

Originally published at https://codingandfun.com on February 2, 2020.

--

--

Python for Finance. Learn step by step how to automate cool financial analysis tools.