Twitter Bot using Python

If you ever thought of creating your own Twitter bot that can tweet, retweet, direct message etc., then this post is for you. We will be using Python with the help Tweepy library to create our own personal Twitter bot.

Steps

Apply for Twitter Developer Account

Open this link https://developer.twitter.com/en/apply-for-access.html and click on the Apply for developer account button

Fill up the application form and wait for approval form Twitter. After approval, you will be able to access the developer dashboard.

Open the Dashboard and create a new app.

After creating the app, click on the Details button and generate the Keys and tokens.

These keys will be used to authorize the bot.

Install Tweepy library using pip

  pip install tweepy

Let’s create a bot

Import the Tweepy module

import tweepy

Set the API keys

consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'

access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'

Authenticate Tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

Create a Tweepy API object

api = tweepy.API(auth)

Now using the API object you can access many tweepy functions. Refer to the tweepy API here https://tweepy.readthedocs.io/en/v3.6.0/api.html#tweepy-api-twitter-api-wrapper.

Examples

Read timeline

tweets = api.home_timeline()

Print the latest timeline tweet

print(tweets[-1].text)

Update status (New Tweet)

api.update_status("This is a new tweet from Tweepy")

Conclusion

Tweepy supports almost every Twitter API from tweeting to sending direct messages.

You can access the Twitter API Docs here https://developer.twitter.com/en/docs

Tweepy Docs here https://tweepy.readthedocs.io/en/v3.6.0/

Thank you for reading. 🙏