Advanced Python Project: How to make a Twitter bot and automate it?

Hello world 👋🏻 my name is Francisco, fcoterroba on the Internet and today I bring you a little post, very advanced this time in Python 🐍
Specifically, we are going to program a bot on Twitter, explaining how to request the keys, how to start programming it, what functions it can be given, how to deploy correctly, what libraries we need, etc.

This project is, from my point of view, the most complicated project that I have done to date on the page so, although I know that you are very interested in this part, I recommend that you first visit all my Python projects, which have a level somewhat lower than this and you can thus establish concepts correctly! ✅

In order, I recommend my post on How can we do a calculator in the terminal?, the project we did for generate QR codes.
We then move on to a project in which, using Free and public APIs, we were able to get a coin exchange with a graphical interface.
Finally, I recommend the last post that I have uploaded to date, in which we made a link shortener with graphical interface where you can automatically open and copy the generated links.

Before starting, although later I will explain what it is, I will I recommend visiting a post that I uploaded more than a month ago, in which I explain many of the most used computer terms in our day to day. Since, in this post, you will see words that you probably do not sound a lot. 🤯 You can reed the post here.

I also want to remind you that a few months ago I uploaded a video to my YouTube channel, very interesting, focused on home automation. Specifically, we connect, configure and install a smart light bulb 💡 with which you can change its color, turn it off, turn it on and much more simply by using your mobile phone and/or voice assistants such as Google, Alexa, etc. 👇🏻

Now yes, let's start!

What is a Twitter's bot?

According to Wikipedia, a Twitter bot or Twitterbot is software that controls a Twitter account through their official API.

Generally, the bot will be able to tweet, retweet, like, follow, unfollow, etc.

In short, a Twitter bot is usually an account or user profile where all, or almost all, actions are automated by a program or script.

What we'll do?

Well, I'm going to take advantage of the post to explain how to program a bot on Twitter but I want to do something that I already had in mind a few months ago, when I saw that people on Twitter like to play small games like RT or FAV if you're more taller than X (replacing X with the current famous person). Ejemplo:

Once our objective is defined, we begin.

FIRST STEP

To work with the Twitter API we need to create a Twitter account (if we don't already have one or we want our bot to have its own account, as is normal) and then register in the Twitter's developers page (only available in English)

We will simply have to click on Apply, at the top right and fill out the form indicating why we want access to the Twitter API.

Once we fill it out, we will reach this page and we will only have to wait for the email (it takes, at most, two days) in which they will give us the OK or ask us more questions about our development with said API

2️⃣ SECOND STEP 2️⃣

Once we have been given access to the API (check the email including the spam box), we will create un proyecto to which we will give a name, a description and in general, fill in all the information requested of us.

3️⃣ THIRD STEP 3️⃣

Let's start now with programming.
As I said before, I want to direct this project to a bot that tweets once a day as a survey, publishing the height of a famous person, the name of the aforementioned person and an image of the same.

To do this, I want to include the entire dataset in one file json.

I will take the images from a stable website like Wikipedia.

We would have something like this:

[
    {
        "appear": "False",
        "name": "Shrek",
        "height": "2.13 m",
        "img": "https://vignette.wikia.nocookie.net/shrekogro/images/9/98/Shrek.png/revision/latest?cb=20161204164724&path-prefix=es"
    },
    ...
    {
      	"appear": "False",
        "name": "Felipe VI",
        "height": "1.97 m",
        "img": "https://www.aboutespanol.com/thmb/ADj-DP6ByR_omi2FnIMReJHgnus=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/SAR_Principe_1024_px-597b9eeb3df78cbb7a257605.jpg"
    }
]

It is simply the name of the character, the height, an image with its internet link and a property called appear which by default will be false but which we will modify later in Python.

4️⃣ FOURTH STEP 4️⃣

Now yes, let's go with the python code:

The first thing we have to do is install, with pip, the package necessary to tweet.

pip install tweepy

Subsequently and in summary, we are going to import the library, create an object with our credentials (API keys) and use the method update_status to publish the tweet.

import tweepy
import json

# Abrimos el archivo json
with open('characters.json') as f:
  data = json.load(f)

# Nos autenticamos en Twitter
auth = tweepy.OAuthHandler("ESCRIBE TUS CREDENCIALES", "ESCRIBE TUS CREDENCIALES")
auth.set_access_token("ESCRIBE TUS CREDENCIALES", "ESCRIBE TUS CREDENCIALES")

# Creamos un objeto de la librería
api = tweepy.API(auth)

# Generamos un valor aleatorio para elegir el personaje del JSON
# Y posteriormente cambiamos el valor de su aparición para que
# No vuelva a salir
character = 0
while data[character]['appear'] == "True":
  character = int(random.uniform(0,len(data)))
  if data[character]['appear'] == "False":
    data[character]['appear'] = "True"
    break
    
# Abrimos el archivo json con permisos para escritura
with open('characters.json', 'w') as f:
  f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',',': ')))
  
# Creamos una variable para transformar metros a pies (medida comúnmente
# usada en EEUU)
height_in_foot = round(float(data[character]['height'][0:4]) * 3.281, 3)

# Guardamos el mensaje final
msg = f"RT si mides más que {data[character]['name']} --> {data[character]['height']}\n\nRT if you're taller than {data[character['name']} --> {height_in_foot} ft"

# Descargamos y borramos la imagen del enlace automáticamente
filename = "temp.jpg"
request = requests.get(data[character]['img'], stream=True)
if request.status_code == 200:
  with open(filename, 'wb') as image:
    for chunk in request:
      image.write(chunk)
      
# Tuiteamos el resultado final pasándole el parámetro de mensaje y la imagen.
api.update_with_media(filename, msg)

# Borramos la imagen al final de la ejecución
os.remove('temp.jpg')

And with this we would have our script ready! 🤓

It's like this, if we want, we can run the script whenever we want to tweet whenever we want, but the fun is in automating this process, right? 😉

5️⃣ FIFTH STEP

I have recently obtained a VPS on which I have installed the latest version of Debian 10, so we will work under this system.

There is a tool in Linux called crontab which serves solely and exclusively to carry out certain scripts or actions at a certain time of day.

Its configuration is simple, we will simply have to write the following command in the terminal:

crontab -e

Our text editor will then open with information in English.

But, in summary and with an example, if you want this script, as I do, to be executed daily, at 6:00 p.m., you must write the following, at the end of the file:

00 18 * * * cd /ruta/donde/esté/el_script && /ruta/de/python archivo.py

Save with CTRL + O and exit with CTRL + X


You can see the final result and since you are there, follow the bot on su Twitter oficial 🤖

And that would be all for today! I hope you liked doing it as much as I did! I also hope you have a great week and we'll see you here soon! Greetings and remember to follow me on the networks as TwitterFacebookInstagram and LinkedIn. 🤟🏻

Leave a Reply

Your email address will not be published. Required fields are marked *