Creating Twitter Bot Using Tweepy

Aman Chourasiya
Analytics Vidhya
Published in
4 min readAug 30, 2020

Automating not so boring stuff

Twitter Icon

Automating our daily boring tasks is one thing and automating something that you love doing is altogether different things. The same task I tried to accomplish a task that I love i.e. is being active on social media. Yes, I tried automating my activities on twitter by using a popular python library named Tweepy.

Tweepy is a very interesting Python library which makes interacting with python developer API’s very easy and hides many low-level details that can be overwhelming for a beginner who is just starting to use REST API.

To get things started first we need to create a developer account with twitter and then you can create an app that will provide the following credentials that we have to use while creating a bot.

  • ACCESS_TOKEN
  • ACCESS_TOKEN_SECRET
  • API_KEY
  • API_SECRET_KEY

These credentials should be kept secret and should not be shared in any way, its a common mistake to put these details in source code and pushing it to GitHub so these should be used only from environment variables.

__API_KEY = os.environ['API_KEY']
__API_SECRET_KEY = os.environ['API_SECRET_KEY']
__ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
__ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']

And just one more thing to get started is that we need to install tweepy library via pip

To get this done quickly you can use my sample bot from Github, here is the link.

git clone https://github.com/amanchourasiya/twitter-bot
export ACCESS_TOKEN="<access token from twitter developer account>"
export ACCESS_TOKEN_SECRET="<access token from twitter developer account>"
export API_KEY="<api key from twitter developer account>"
export API_SECRET_KEY="<api secret key from twitter developer account>"
python3 bot.py

This bot is currently programmed to like and retweet tweets from specific accounts and this bot also filter tweets based on specific filters real-time.

Components used in this bot

There are not many components in this bot but it is extensible enough to be customized for different purposes.

1. Creating auth config for Twitter API

Creating an authenticated connection to twitter API using Tweepy required all four secret values that we get from the twitter developer account.

class Bot:
def __init__(self):
try:
__API_KEY = os.environ['API_KEY']
__API_SECRET_KEY = os.environ['API_SECRET_KEY']
__ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
__ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']
auth = tweepy.OAuthHandler(__API_KEY, __API_SECRET_KEY)
auth.set_access_token(__ACCESS_TOKEN, __ACCESS_TOKEN_SECRET)
self.api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
self.api.verify_credentials()
print('Authentication successful')
except KeyError:
print('Twitter credentials not supplied.')
except Exception as e:
print(e)

This handles creating OAuth connection with twitter API and also sets rate limit alerts and notifications, twitter has some set API usage limit and if we pass that limit then out API handler waits for that time and then again starts making calls to twitter API.

2. Creating utility functions.

Some utility functions should be created for basic use of this bot, these may include

  • Getting the top 20 tweets.
  • Getting 10 trending hashtags.
  • Fetching recent tweets from a specific user.
  • Get a list of all followers.

And this list can be endless as these are infinite use cases of twitter API and using these utility functions we can regulate our bot to trigger some functions based in the results of these functions.

e.g. suppose if we are planning to make a feature so that if a user retweets out tweet then we automatically follow that user, like this we can make multiple features and run them periodically.

3. Stream live data from twitter.

We can use Teeepy’s StreamListerner object to stream and filter live data from the twitter news feed and based on that we can instruct out our bot to make some decisions. This data can also be used to do live analysis to Twitter data.

class WorkerStreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
self.me = api.me()
def on_status(self, tweet):# Check if this tweet is just a mention
print(f'{tweet.user.name}: {tweet.text}')
print(f'{tweet.user.id}')# Check if tweet is reply
if tweet.in_reply_to_status_id is not None:
return
# Like and retweet if not done already
if not tweet.favorited:
try:
tweet.favorite()
except Exception as e:
print(f'Exception during favourite {e}')
if not tweet.retweeted:
try:
tweet.retweet()
except Exception as e:
print(f'Exception during retweet {e}')
print(f'{tweet.user.name}:{tweet.text}')def on_error(self, status):
print('Error detected')
stream.filter(track=["Hacking"], languages=["en"], is_async=True)

So like this, we can create stream object and filter data based on some targeted keywords, what this stream listener is doing is that whenever there is any tweet including a keyword Hacking then it will automatically like and retweet that tweet automatically.

This is just a sample of the capabilities of a twitter bot and much more can be achieved by going through all features of this API. My twitter-bot project is also in phase-1 as I am writing this blog.

Originally published at https://www.amanchourasiya.com.

Follow me for more blogs https://twitter.com/TechieAman

Personal blog https://www.amanchourasiya.com

--

--