Creating a Twitter Bot (API v2) (2024)

ᵂ ᴬ ᴿ ᴿ Ξ ᴺ

·

Follow

10 min read

·

Jun 7, 2023

--

In this comprehensive guide, I will walk you step-by-step (32 steps in total) on a journey to create, authenticate and host your custom Twitter Bot using the Twitter API v2. By leveraging the power of Python and Tweepy, we’ll build a simple random number generating bot that’s hosted on an AWS EC2 instance within a Docker container. Our bot will be programmed to tweet at regular intervals using cron jobs.
n.b. For faster reading, you should be able to follow along by only reading the bold writing

What that guide will help you do:
1. Register for a Twitter developer account
2. Enhance and automate your Twitter account
3. Use Tweepy to invoke the Twitter API
4. Deploy to Docker and AWS
5. Use cron jobs to maintain a regular execution

Why Automate? The Beauty of Automation

Automation is a magnificent force that has the power to transform the ordinary into the extraordinary. It is akin to a magician’s wand, a leverage that unlocks unimaginable possibilities.

Automation is not just about accomplishing tasks, with automation, the realm of human achievement transcends boundaries, and the mundane becomes a canvas for innovation and efficiency.

Combining Social Media and Automation

Twitter serves as a vital channel for engaging with audiences, where a presence hinges on the ability to maintain an active account, featuring a steady stream of fresh tweets. While accomplishing this manually is possible, it is undoubtedly time-consuming. Instead, we can turn to the prowess of a Twitter Bot — a program that automates some or all of these activities — allowing us to reclaim precious time.
n.b. Although the bot here is super, duper simple, the script can be easily updated to include calls to other APIs and include additional functionality.

First, we need to create a directory that shall serve as the foundation for our grand endeavour. From here, we summon the powers of a virtual environment, forging an environment solely dedicated to our project’s needs.

Step 1: Create a new directory (I called mine twitter-bot)
Step 2: Change into the twitter-bot directory
Step 3: Create a virtual environment (I called mine my_venv)

From the command line:

$ mkdir twitter-bot
$ cd twitter-bot
$ python3 -m venv my_venv
Creating a Twitter Bot (API v2) (2)

It is now time to activate the virtual environment — the sanctuary in which we shall procure only the essential dependencies for our project.

n.b. I am using a Mac, this command may vary on alternative operating systems

Step 4: Activate the virtual environment

$ source ./my_venv/bin/activate

With the virtual environment successfully activated, we may proceed to download the dependencies required for this project. For this particular example, we shall solely require the Tweepy library.

Step 5: install Tweepy

$ pip3 install tweepy

Tweepy provides an elegant and efficient solution for our bot-building endeavours.
Tweepy is an open-source Python package that allows accessing the Twitter API.
At its core, Tweepy unveils a set of classes and methods that mirror the very essence of Twitter’s API endpoints.

I also downgraded the version of urllib3 as a work-around for compatibility issues later on whilst trying to connect with the Twitter API v2.

Step 6: Downgrade urllib3

$ pip3 install urllib3==1.26.6

We have now secured all the dependencies we require. To preserve this invaluable information for the future deployment of our bot on AWS, let us encapsulate them in a requirements.txt file.

Step 7: Save dependencies to requirements.txt file

$ pip3 freeze > requirements.txt
Creating a Twitter Bot (API v2) (3)

Prior to making any calls to the API, you must claim your authentication credentials. The official documentation of the Twitter API are our sacred scrolls, within its hallowed pages, you shall discover further insights into the API’s policies and limits, guiding you toward a realm of enlightened automation.

At its core, the Twitter API offers an assortment of HTTP endpoints, each providing access to a myriad of features. However, many features require the $100-a-month Basic account option (with enhanced access). Fortunately, our simple bot only requires the Free version.

Get a Twitter user before proceeding. I personally hooked up a fresh Twitter account with a shiny new Gmail address.

Step 8: Sign up on Twitter

Step 9: Go to the Twitter developer portal and apply for a developer account

Creating a Twitter Bot (API v2) (4)

Continue with the free account. Now, Twitter’s going to ask why you’re itching to access their precious API. Don’t sweat it, though. All you gotta do is tell them straight — the bot’s mission, the functionality, the whole shebang, just fill up that word quota.

Step 10: Fill in information required by Twitter

Creating a Twitter Bot (API v2) (5)

For authentication for the Twitter API v2 that we will be using, we need the following:
1. Consumer key (API Key)
2. Consumer secret (API Key Secret)
3. Bearer Token
4. Access Token
5. Access Token Secret

Step 11: Click User authentication settings (Set Up) — generate the keys that we need

Creating a Twitter Bot (API v2) (6)
Creating a Twitter Bot (API v2) (7)
Creating a Twitter Bot (API v2) (8)
Creating a Twitter Bot (API v2) (9)

The Python Script

Let’s keep it basic for this example — we’re just showing off how to connect and flex with the latest Twitter API. But don’t let me cramp your style. Run wild, write your own script, call other APIs or AIs. Case in point, I cooked up a spicy example using ChatGPT, a.k.a @geezer__bot. Get creative with it if you want to.

Step 12: Write your Python script

import tweepy
import random

# credentials to access Twitter API
API_KEY='YOUR_API_KEY_HERE'
API_KEY_SECRET='YOUR_API_KEY_SECRET_HERE'

BEARER_TOKEN='YOUR_BEARER_TOKEN_HERE'

ACCESS_TOKEN='YOUR_ACCESS_TOKEN_HERE'
ACCESS_TOKEN_SECRET='YOUR_ACCESS_TOKEN_SECRET_HERE'

# create an OAuthHandler instance
client = tweepy.Client(
BEARER_TOKEN,
API_KEY,
API_KEY_SECRET,
ACCESS_TOKEN,
ACCESS_TOKEN_SECRET,
)

# create a tweet
def tweet_random_number():
random_number = random.randint(1, 100)
client.create_tweet(text=str(random_number))

# main function
def main():
tweet_random_number()

# call main function
if __name__ == "__main__":
main()

A simple script that returns a random number between 1 and 100. We should be able to run this script and a random number between 1 and 100 be tweeted

Step 13: Test the script

Creating a Twitter Bot (API v2) (10)

And if we go over to Twitter…. we have a random number Tweet:

Creating a Twitter Bot (API v2) (11)

Wahooo, the script ran and we got our result. To set a regular Tweeting pattern we will use cron jobs once we’ve uploaded the bot onto a server, this will see the bot tweeting based on time intervals.

Putting Our Twitter Bot into a Docker Container

A Twitter bot chilling on your local machine isn’t much good, we want this bot rocking round-the-clock. Now, there’s a bunch of ways to play this. I’m gonna show you how to make the magic happen with Docker and a free gig from AWS.

Step 14: Download Docker from https://www.docker.com/

Now, create a file called Dockerfile (with no file extension)

Creating a Twitter Bot (API v2) (12)

Step 15: Create a Dockerfile containing the following code:

FROM python:3.9

COPY main.py /

COPY requirements.txt /tmp

RUN pip3 install -r /tmp/requirements.txt

WORKDIR /

CMD ["python3", "main.py"]

Now from the command line, we can build the docker image to test locally.
Build the docker image from the command line:

$ docker build . -t number-bot

We can test run this docker image by running:

$ docker run number-bot

This command should now make your twitter bot tweet another random number if all is working well.

We will be deploying to an AWS EC2 Ubuntu instance. For that, we need to build the docker image with that in mind. We need to go back to the directory on our computer and rebuild the docker image with a different flag.

Step 16: Build docker image (With ubuntu platform in mind)

$ docker build . --platform linux/amd64 -t number-bot

Step 17: Export and compress the docker image

$ docker image save number-bot:latest -o number-bot.tar

For more about what’s going on here https://docs.docker.com/engine/reference/commandline/save/

By running this command, Docker will create a tar archive file named `number-bot.tar` containing the image layers and metadata. This file can then be shared or transferred to another machine.

Gzipping the tar file helps to reduce its size, making it more efficient for storage and transfer.

Step 18: gzip the file

$ gzip number-bot.tar

Running this command will compress the `number-bot.tar` file using gzip compression algorithm, resulting in a new file named `number-bot.tar.gz`.

Deploying Twitter Bot to AWS

We’re heading straight into the heart of the action, where we’ll set up an Amazon AWS EC2 instance. You’re going to need an AWS account. But don’t worry, it’s not going to break the bank. We’re talking about their free tier offering, a golden ticket to the main event.

n.b. You should be careful when running something on AWS. Costs can potentially sky rocket if you make a error or get hacked. Consider setting a hard price cap to avoid tears.

Step 19: Sign up to AWS https://aws.amazon.com/

Step 20: Launch a new EC2 instance, selecting the Ubuntu Server as the base image

Creating a Twitter Bot (API v2) (13)

Step 21: Create a new key pair

Creating a Twitter Bot (API v2) (14)

Step 22: Save key pair in the project directory (twitter-bot)

Creating a Twitter Bot (API v2) (15)

Step 23: Go to the page of your new EC2 instance and click the ‘connect’ button on the top right of the screen, a window should pop up with the details on how to connect with your instance.

Creating a Twitter Bot (API v2) (16)

We are now going to connect and install docker on your EC2 instance.

Step 24: Go to the directory where we just saved the key pair and enter the following command into the terminal:

$ chmod 400 number-bot.pem

Step 25: Run the example for connecting with ssh (with your AWS EC2 address)

$ ssh -i "number-bot.pem" ubuntu@ec2-32-53-149-13.compute-1.amazonaws.com

Now that we connected to our AWS EC2 instance, we need to upgrade a few things, download Docker onto the instance and give some user access permissions:

Step 26: Run the following commands from in your ssh connection

ubuntu~$ sudo apt-get update
ubuntu~$ sudo apt install docker.io
ubuntu~$ sudo usermod -aG docker ubuntu
ubuntu~$ exit

The command `sudo apt-get update` is used to update the package lists for repositories on an Ubuntu-based system.

After executing these commands, “ubuntu” will be able to run Docker commands without needing to use sudo.

Finally, Hosting Your Twitter Bot

From your local rig, you’re gonna launch the bot’s Docker image straight into your EC2 instance. Now don’t get antsy, depending on the strength of your internet connection this might take a minute or two.

Step 27: Upload docker image to your EC2 instance

scp -i 'number-bot.pem' number-bot.tar.gz ubuntu@ec2-44-63-949-11.compute-1.amazonaws.com:/tmp

Once uploaded, reconnect via ssh.

Step 28: Reconnect with your EC2 instance

$ ssh -i "number-bot.pem" ubuntu@ec2-42-23-249-11.compute-1.amazonaws.com

Once connected, run the following commands to decompress and import the Docker image:

Step 29: Decompress and import the Docker image

ubuntu~$ gunzip /tmp/number-bot.tar.gz
ubuntu~$ docker image load -i /tmp/number-bot.tar

The Docker image should now be fully loaded and ready to run from the EC2 instance.

Step 30: Run the Docker image

ubuntu~$ docker run number-bot

Another Tweet! Great! Our EC2 instance is humming like a well-tuned motor and our script is firing on all cylinders. But are we done? no. We’re about to supercharge this baby with cron job. Cron jobs allow users to automate tasks on Unix based operating systems.

Step 31: Open/Edit the crontab

ubuntu~$ crontab -e

The following command will run `docker run number-bot` every 2 minutes

Step 32: Add this cron job to the file, save & exit

*/2 * * * * docker run number-bot

Now, give your peepers a feast on your bot’s Twitter account. Your bot is now laying down tweets like a Vegas card dealer, dropping a random numbers every two minutes. No pause, no breaks, just non-stop action.

Creating a Twitter Bot (API v2) (17)

Signing Off

To stop running the docker container, get the number ID of the container running with the following command:

ubuntu~$ docker ps

The container ID will be displayed, copy it and then run:

ubuntu~$ docker stop CONTAINER_ID

You may at this point want to stop your AWS EC2 instance, you can restart it again if required/when you’re happy to do so.

Conclusion

Consider the bot in this guide as the seed money for your Twitter automation enterprise. Remember to dive deep into the Tweepy API documentation. Who knows? You might strike gold with a bot so ingenious it shakes up the Twittersphere. The rules of the game are simple: dream big, bot bigger!

Creating a Twitter Bot (API v2) (2024)
Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5856

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.