Python from scratch — Part 3 (Twitter Bot)

Gonzalo Galante
5 min readAug 1, 2022

In this article we will see how to create a bot using the twitter API, to be able to leave it running we are going to use a small bash script that executes our code every X time.

What the bot will do is send a tweet in an interval of 60 seconds using 4 random hashtags from among the top 50 of the moment.

First things first, which is an API

An API (Application Programming Interface) is a mechanism of 2 components, 2 softwares that communicate with each other through protocols.

Basically an application which is called a client sends a request and another called a server sends a response. The API acts as a translator allowing both applications to communicate with each other even if they are designed in different languages.

There are 4 types but we will use (and later do) the REST APIs.

A simple example would be to have a front-end made with React which wants to access data from the user’s Google calendar, through a Google calendar API we can communicate both services with each other despite being designed in different languages.

What is Bash?

There will be an exclusive article about this, but not to leave this up in the air, we can say that bash is a command interpreter, which allows us to execute them directly from the console

In this case it will allow us to execute our .py file every certain time.

Twitter API Access

In order to use it, we will go to the following link and register.

https://developer.twitter.com

Once that is done, we will go to “Projects & App” → overview and generate an App.

With the creation of it we will obtain “bareer Token”, “Api key” and “API secret Key”, these 3 data we have to save them to later use in our code.

Finally we go to “Keys & Tokens” to generate the “Access Token and Secret”, which gives us 2 those 2 keys that we also have to write down.

Creating the bot

For this project we are going to use 3 libraries, pipenv, random and tweepy.

We create a folder where we will work and we are going to create 2 files, “exe.sh” (our BASH code), and main.py

In the terminal we position ourselves in the folder where we are working and we are going to execute the following command

pipenv shell
#This command will create a virtual environment for the library that we are going to
#use for the Twitter API not to be installed on the whole pc but only
#in this virtual environment
pipenv install tweepy
#With this we install tweepy only in the virtual environment

In our main.py we are going to import the libraries and add the 5 variables that are going to contain the keys that we saved before.

import tweepy
import random

#Twitter Data
bearer_token = "bearer_token"
consumer_key = "consumer_key"
consumer_secret = "consumer_secret"
access_token = "access_token"
access_token_secret = "access_token_secret"

Now what we will do is make a function that consults the API for current trends and saves them in a list.

def trends(woeid):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
trends = api.get_place_trends(id = woeid, exclude="hashtag")

trendings = []
for value in trends:
for trend in value['trends']:
trendings.append(trend['name'])
trendings = random.sample(trendings, 4)
print(trendings)
return trendings

The woeid parameter that we pass is the one that determines the location from where we want to bring the trends, in this case it can be from Argentina and the United States.

In this link you can find the one for your country.

The first thing we do is authenticate ourselves with the API using the keys that we generate at the beginning and instantiate it.

The function that returns the trends is “get_placed_trends” to which, apart from woeid, we pass the exclude parameter, to remove the “#” and thus be able to add it later, this serves to ensure that there are no double “##”.

In order to store the trends we use the for loop through “trends” and “name” and finally with “random.sample” we obtain 4 random values ​​from the original list.

Now yes, we are going to tweet whatever we want and add these trends automatically.

def tweet_video():

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

#US
trendings = trends(23424977)
body = f'Test Tweet EEUU #{trendings[0]} #{trendings[1]} #{trendings[2]} #{trendings[3]}'
api.update_status(body)
print(f'Us tweet: {body}')

#Ar
trendings = trends(23424747)
body = f'Test tweet Argentina #{trendings[0]} #{trendings[1]} #{trendings[2]} #{trendings[3]}'
api.update_status(body)
print(f'AR tweet: {body}')

return ("Successfully tweeted")

In this case we authenticate again but we call the “update_status” function which will upload the content that we pass to it, in our case “body” that has our tweet plus the hashtags.

With this we have everything ready, we need to be able to execute this automatically.

In our exe.sh file we will write the following.

#!/bin/bash

while true; do
python3 main.py
sleep 60;
done

What this will do is run the main.py file every 60 seconds.

If we want it to be faster we can lower the seconds placed after sleep, but there we can have a request saturation and that the API blocks us for a while.

And ready!

Starting from the fact that we close everything and we want to leave it working another day, what we will do is enter the folder pro terminal, activate the environment and execute our “exe.sh”

pipenv shell
./exe.sh

This will leave the terminal running and returning the prints that are in our code, when we want to stop it, it will be enough to press “Ctrl + C”

If we want to leave it running in the background we can put an “&” at the end.

./exe.sh

And to stop it, just put the following command in the terminal to obtain the process id.

ps -A

And then to remove it

kill {ID del proceso}

--

--