DEV Community

Cover image for Making a Twitter bot with Python
Seema Saharan
Seema Saharan

Posted on • Edited on

Making a Twitter bot with Python

Do you use Twitter? If so, then you must come across some of the bots that like, retweet, follow, or even reply to your tweets. But have you ever wondered how they are made? Well, it's easy as filling water in a bottle. Haha! It's really not rocket science. So, let's get started and make a bot.

image

In Python, the twitter bot is just a few lines of code, less than 30.

Prerequisites for making one (Bot)

- tweepy module in Python.
- A twitter account, which you want to make a bot.
- Twitter developer account.
Enter fullscreen mode Exit fullscreen mode

Applying to the twitter developer account

To apply for the developer account on twitter, follow these steps:

  • Go to this link. You will get this kind of website after you visit the mentioned link. Alt Text

Make sure you've logged in to your Twitter account on which you want to make a bot.

Here, I'm using my new account BashWoman to make a bot, which will like, and retweet the hashtag #python3.

  • Click on apply, after doing that this type of screen will show up. Alt Text Select, apply for a developer account.
    • After this, you will get a number of options, why you want to apply for the developer account, here we are making a bot, so I will select Making a bot.

Alt Text

  • Now, on the next page, you have to fill some details. Do that.

Alt Text

  • Twitter will ask you some questions related to how you would use this account and the twitter data. We are just making this bot to like and retweet the posts so, select that only.

Alt Text

And

Alt Text

Else select no, just to keep it simple.
Enter all the details you'd do with this bot.

  • After filling all the details, you'll get an agreement page. Just accept all the terms and conditions. And then click on Submit application.

Alt Text

  • You will get a confirmation mail. Once you confirm that, a new window will open like this.

Alt Text

Click Get keys.

  • After this, what we wanted by this developer account is the keys. Save them somewhere, you'll need them soon.

Alt Text

Let's Code and understand it

Alt Text

You see there are no more than 30 lines in Python. Let's understand each and every line.

import tweepy
import time
Enter fullscreen mode Exit fullscreen mode

To communicate with Twitter API, we need some module, here we are using tweepy. You can install it easily.

pip install tweepy
Enter fullscreen mode Exit fullscreen mode

Once you install the module, write some more code.

# Authenticate to Twitter
CONSUMER_KEY = '<your-consumer-or-API-key-goes-here>'
CONSUMER_SECRET = '<your-consumer-or-API-secret-goes-here>'
ACCESS_KEY = '<your-access-key-goes-here>'
ACESS_SECRET = '<your-access-secret-goes-here>'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACESS_SECRET)
Enter fullscreen mode Exit fullscreen mode

This is used to authenticate your Twitter account. Remember these keys are of your account, don't share them to anyone, else they can access your data. That's why I have made some variables in which I will store the keys.

These keys will be found in your developer account, which you've saved a time ago.

auth variable is created to authenticate the account, Twitter uses OAuth to do this.

And, after that, we will set the tokens.

# Create API object
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
Enter fullscreen mode Exit fullscreen mode

This class provides a wrapper for the API as provided by Twitter. If you stuck somewhere, you can always refer to the tweepy documentation.

user = api.me()
search = '#python3'
numTweet = 500
for tweet in tweepy.Cursor(api.search, search).items(numTweet):
    try:
        print('Tweet Liked')
        tweet.favorite()
        print("Retweet done")
        tweet.retweet()
        time.sleep(10)
    except tweepy.TweepError as e:
        print(e.reason)
    except StopIteration:
        break
Enter fullscreen mode Exit fullscreen mode

Finally, we will tell the program to look for the keyword #python3 in a tweet and the number of tweets that will be processed once in a day. If you want to like, you can use tweepy.favorite() , and for retweet tweepy.retweet().
The reason, I'm using sleep is, twitter has some guidelines, you must follow otherwise, your account will be restricted. There is a limit for liking the number of tweets. If it gives some error, we can use tweepy.TweepError so that we know, what went wrong.

Now, it's time for the deployment. You can use any platform, I have used Render.

After creating an account on this, create a cron job, you can schedule the time, I prefer about 10 to 15 mins. It means your bot will run every 10 to 15 mins so that it won't violate the Twitter guidelines and your account will be safe and not get restricted.

Here's my bot.

Alt Text

It's time to build your own bot.
All the best.

Top comments (11)

Collapse
 
nav_devl profile image
Naveen Honest Raj

Hello Seema, loved your explanation πŸ”₯
I hope you are also aware of using Stream instead of Cursor in your approach to get the tweets containing the particular hashtag. It would be very helpful for beginner level readers to understand the differences and apply them accordingly. But this is cool. Your line-by-line explanation is πŸ‘ŒπŸ»πŸ‘ŒπŸ»

Collapse
 
seemasaharan profile image
Seema Saharan

Thank you so much.

Collapse
 
miketheyeti profile image
MikeTheYeti

This has gotten my bot project further than anything else I have done to date. I am a dilettante in Python and am making a twitter bot to practice.

I am stuck on how to reply to a tweet with one of a set of messages (I think I got random.choice to work). My scheme is to reply to tweets based off keywords.

Thanks so much for this work. I love watching my code actually work!!!

Collapse
 
seemasaharan profile image
Seema Saharan

I'm glad it helped.

Collapse
 
runtimeerror20 profile image
{Amogh Dixit}

Thanks a lot! I was looking for something like this for a long time. I really wanna try it out πŸ˜ƒ

Collapse
 
seemasaharan profile image
Seema Saharan

Welcome.πŸ˜€

Collapse
 
thevediwho profile image
Vaibhav Dwivedi

Very interesting. I was looking for something like this.

Collapse
 
seemasaharan profile image
Seema Saharan

I hope this will be helpful for you.

Collapse
 
santosh profile image
Santosh Kumar • Edited

Make one post on OAuth2 authentication from scratch.

By scratch I mean with just using requests library.

Collapse
 
seemasaharan profile image
Seema Saharan

Sure.

Collapse
 
blancoharsh profile image
Harsh #34

Hello,
first of all great explanation but i was wondering if there is any way to ,make a bot to retweet specific user's tweets?
thanks