AD: This post was reviewed by Grammarly, the Best Automated Proofreader.
Did you know that Twitter is filled with over 15% bots? Pretty crazy, right?!
In this article, we will create a different type of robot – a Twitter bot. Twitter bots control a Twitter account via the Twitter API. A Twitter bot is nothing but a script that performs specific task in a loop. We can use this bot for many applications like “follow/unfollow”, “tweet/retweet,” and “like any tweets”.
While you can create this project without a Raspberry Pi, I wanted to have the bot running 24/7 without using resources on my main computer. Ready to get started?!
Make Your Twitter Developer Account
The first thing we need is a Twitter account. If you don’t have one already, now is a great time to make one. Also, make sure that you link your phone number to the account because it is needed in the next step.
Once you have a twitter account with phone number linked, it’s time to create a Twitter app. To make a Twitter app first go to the Twitter’s Developer site. If you still haven’t linked your phone number, the site will will ask you to add it now.
Next, click on “Create an app”. This will take you to an application form, where you have to fill in details. Make sure you fill in real information, and submit the application. It might take a few hours or a couple of days for your application to get approved.
After your account is reviewed, you can create an app. Give it a name, and describe your app. Make sure you enter a URL in the field. If you don’t have a website, just add a valid URL.
The app will not be created if you leave the URL block empty. Also check the “Enable Sign in with Twitter” option. After the information is filled in, submit form, and you will be redirected to your application.
Here you will see three tabs, click on “Permissions” and select “Read, write and direct messages” and save it.
Next go to “Keys and tokens” and click on “Create Access Tokens” or “Regenerate Access Tokens”. You will notice some hash codes which we will use in our bot script. These are very important codes! DO NOT SHARE these with anyone, or they can gain access to your Twitter account!
Now that you have tokens for the Twitter API, you’ll need to setup the Raspberry Pi. If you are new to Raspberry Pi, here are a couple of resources to get you started:
- How to start with Raspberry Pi
- Connect to Raspberry Pi without a monitor
- How to get started with Raspberry Pi GPIO Pins
I recommend checking those out before continuing with this project.
Setting Up the Raspberry Pi
First power up the Raspberry Pi and open terminal. Next enter the following commands one by one:
sudo apt-get update sudo apt-get upgrade
These commands will update your Raspberry Pi. Make sure you have an active Internet connection.
Next we want to install Tweepy, a Python library for the Twitter API. This can be installed using pip command.
pip install Tweepy
Above command will download and install Tweepy on the Pi. Now we can start writing the code. Open a text editor or start nano editor through the terminal.
Create a Twitter Bot with the Raspberry Pi
We start by importing the packages required for the code.
import os import tweepy as tp from time import sleep
First, we import packages that will be used in the code. The package, tweepy, is imported as tp which will be used to connect and control our Twitter account . OS and time are preinstalled packages.
Next, we have to add the credentials used to log in into our Twitter account. These credentials are nothing but tokens/keys we generate using the Twitter app.
consumer_key = 'your-consumer-key' consumer_secret = 'your-consumer-secret' access_token = 'your-access-token' access_secret = 'your-access-secret'
In place of the hash you have to enter your keys. Replace the
'your-xxxx' with your account credentials. We saved the keys into variables so we can use them later to authenticate the Twitter login.
Now we have to authenticate our credentials so our bot can login to our account.
auth = tp.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tp.API(auth)
We use the authhandler function to validate the tokens. Next, we save the validation in a variable called, api. This is used for actions such tweeting/retweeting, liking, etc. Now we can start using the API to interact with our account.
user = api.me() print(user.name) print(user.location)
We can use the
me() function to fetch user data and print it to the terminal. The code,
user.location, prints our username and location. Use this code to verify that the script is working, and the connection is established.
Twitter Bot with Raspberry Pi Example
Now, let’s write some code that will follow everyone that is following you.
for follower in tp.Cursor(api.followers).items(): try: follower.follow() except: print("No more followers to follow")
In the above code we have used a for loop which iterates through our follower’s list and follows everyone back. I added a try-except block. This code follows everyone until there aren’t any accounts. Then, it will display the message from the except block.
Find Keywords & HashTags with Twitter Bot
Now let’s do something a little more complicated. Using tweepy’s search function we can search for keywords/hashtags on Twitter and favorite and retweet the post.
tag = ("arduino", "raspberrypi", "learnrobotics", "esp8266") for tweet in tp.Cursor(api.search, tag, result_type="mixed", lang="en").items(): try: tweet.favorite() print('Favorited the tweet') tweet.retweet() print('Retweeted the tweet') sleep(60) except tp.TweepError as e: print(e.reason)
Twitter Bot Code Walk-Through
Let’s examine this code further in a quick code walk-through.
tag = ("arduino", "raspberrypi", "learnrobotics", "esp8266") for tweet in tp.Cursor(api.search, tag, result_type="mixed", lang="en").items():
First we save some keywords. These are the words you want to look for in a tweet, I used arduino, raspberrypi, esp8266 and learnrobotics. You can use any words you want. Tweepy will search for tweets with these words. In the next line we have a for loop where we search the tag in the function
result_type can either be “popular”, “recent” or “mixes”. The phrase
lang="en" will only search for tweets that are in English.
Furthermore, let’s look at the code,
.items(). Here the item is empty but you can provide a parameter. (For example
item(10)). The bot will only select 10 tweets with this code. If you leave it empty, it will make the search longer, and all the tweets with these keywords will be selected.
try: tweet.favorite() print('Favorited the tweet') tweet.retweet() print('Retweeted the tweet') sleep(60)
There is another try block inside the for loop. First, the tweet is “favorited” using the
favorite() function. Then the
retweet() function retweets the tweet on your account. Finally,
sleep(60) pauses the loop for 60 seconds before selecting next tweet. You can increase or decrease the time in seconds. I recommend using a delay greater than 60 seconds because Twitter might disable your account for spamming.
except tp.TweepError as e: print(e.reason)
Finally, there is an except block. This block will throw an exception or warning if there is an error with the tweets. That’s all for the code, now you can save the file as
tweetbot.py and run the code through terminal using the following command:
To stop the execution, just close the terminal window. I added a copy of my code, below, that you can use as a starting point. Just enter your tokens/keys, and you are good to go.
Make Your Own Twitter Bots
In conclusion, Twitter bots aren’t too difficult to make once you have a straightforward procedure to follow. I encourage you to give this project a try! Make your own twitter bots and test the wide range of functions Tweepy provides. If you have any questions, feel free to ask in the comment section, below.
And finally, if you are interested in robotics, be sure to check out my ebook, Mini WiFi robot!
Like my work? Keep me caffeinated.