If you have ever thought about creating a twitter botthen you are the right place. We will be creating a twitter bot using Python programming language and if you are in process of learning Python, this will be a fun project to polish your programming skills. In this blog post you create your own twitter bot with Python and automate your repetitive tasks.
Setting up your Environment
The first thing is to access to twitter‘s API and you would need Twitter Development account. Here are the steps to follow.
- Apply for a Developer account here.
- Now create a new application in developers portal and keep your API keys and access tokens safe.
Preparing your Python Environment
You have to have python installed on your system. After that you will install Tweepy
, a python library to interact with Twitter API. Use pip
to install it.
pip install tweepy
Use of Twitter API allows your bot to perform actions like tweeting, retweeting and following users etc.
Building Twitter Bot with Python
Lets get to work now.
Authentication
Lets code, first we have to authenticate with Twitter’s API using Tweepy.
import tweepy
# Replace these with your API keys
consumer_key = 'YOUR_CONSUMER_KEY'
consumer_secret = 'YOUR_CONSUMER_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
Sending Tweets
Now that authentication is taken care of, lets send a tweet
api.update_status("Hello, world! This is my first tweet from my Twitter bot.")
You have just tweeted
Automating Likes and Retweets
We can automate liking or retweet a tweet using tweet’s ID. Here’s how
tweet_id = '1234567890'
api.create_favorite(tweet_id) # Like
api.retweet(tweet_id) # Retweet
Follow/Unfollow Users
You can follow or unfollow users by their usernames.
api.create_friendship('username')
api.destroy_friendship('username')
Enhancements for your Twitter Bot with Python
This can be further improved if you add following enhancements.
Directory Structure
Create a project folder twitter_bot
and navigate into it. Here is how it should looks like.
twitter_bot/
│
├── .env # Stores API keys and tokens securely
├── bot.py # Main script for your Twitter bot actions
└── requirements.txt # Python dependencies for your project
- Create
.env
file that hosts all your important information like API keys and access tokens. - Create
requirements.txt
, a text file to add dependencies for your project. - Create
bot.py
and this will be your main code file that contains main script.
Here is how you .ENV
file looks like
CONSUMER_KEY=your_consumer_key_here
CONSUMER_SECRET=your_consumer_secret_here
ACCESS_TOKEN=your_access_token_here
ACCESS_TOKEN_SECRET=your_access_token_secret_here
and your REQUIREMENTS.TXT
looks like this
tweepy==3.10.0
python-dotenv==0.15.0
Now main file BOT.PY
can have following code.
import tweepy
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Set up your Twitter API credentials
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
# Authenticate with the Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# Function to send a tweet
def tweet(message):
api.update_status(message)
print("Tweeted: " + message)
if __name__ == " __main__":
tweet("Hello, world! This is a tweet from my Twitter bot.")
Now in order to use this, open your terminal
and run following command.
pip install -r requirements.txt
This will install all the requirements for the project.
Now you can run your script like this.
python bot.py
Here is updated bot.py
with enhanced functions like searching tweets, replying, streaming, direct messages, and automated follow backs.
import tweepy
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Twitter API credentials
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
# Authenticate with the Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# Tweet a message
def tweet(message):
api.update_status(message)
print("Tweeted: " + message)
# Follow a user
def follow(username):
api.create_friendship(username)
print(f"Followed {username}")
# Unfollow a user
def unfollow(username):
api.destroy_friendship(username)
print(f"Unfollowed {username}")
# Like a tweet
def like(tweet_id):
api.create_favorite(tweet_id)
print(f"Liked tweet {tweet_id}")
# Unlike a tweet
def unlike(tweet_id):
api.destroy_favorite(tweet_id)
print(f"Unliked tweet {tweet_id}")
# Retweet
def retweet(tweet_id):
api.retweet(tweet_id)
print(f"Retweeted {tweet_id}")
# Search tweets
def search_tweets(query, count=10):
tweets = api.search(q=query, count=count)
for tweet in tweets:
print(f"{tweet.id} - {tweet.text}")
# Reply to a tweet
def reply_to_tweet(tweet_id, message):
api.update_status(status=message, in_reply_to_status_id=tweet_id, auto_populate_reply_metadata=True)
print(f"Replied to tweet {tweet_id}")
# Automated follow-back
def auto_follow_back():
for follower in tweepy.Cursor(api.followers).items():
if not follower.following:
follower.follow()
print(f"Followed back {follower.name}")
# Streaming class
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text)
def start_stream(keywords):
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)
myStream.filter(track=keywords)
# Send direct message
def send_direct_message(user_id, message):
api.send_direct_message(recipient_id=user_id, text=message)
print(f"DM sent to {user_id}")
if __name__ == " __main__":
# Example usage (comment out what you don't need)
tweet("Hello, Twitter World from my bot!")
follow("username_here")
unfollow("username_here")
like("tweet_id_here")
unlike("tweet_id_here")
retweet("tweet_id_here")
search_tweets("Python")
reply_to_tweet("tweet_id_here", "Thanks for tweeting!")
auto_follow_back()
send_direct_message("user_id_here", "Hello from the bot!")
# start_stream(["Python", "Tweepy"]) # Uncomment to start streaming
Now here under line #83, you will comment out the feature you are not using that API call. Lets say if you just want to send a tweet, in that case comment out everything below tweet function on line 85.
We can further improve this script by adding the option to accept command line arguments. In this case we wont have to edit the main bot file everything we have to do something. See below for updated file.
import tweepy
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Twitter API credentials
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
# Authenticate with the Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# Tweet a message
def tweet(message):
api.update_status(message)
print("Tweeted: " + message)
# Follow a user
def follow(username):
api.create_friendship(username)
print(f"Followed {username}")
# Unfollow a user
def unfollow(username):
api.destroy_friendship(username)
print(f"Unfollowed {username}")
# Like a tweet
def like(tweet_id):
api.create_favorite(tweet_id)
print(f"Liked tweet {tweet_id}")
# Unlike a tweet
def unlike(tweet_id):
api.destroy_favorite(tweet_id)
print(f"Unliked tweet {tweet_id}")
# Retweet
def retweet(tweet_id):
api.retweet(tweet_id)
print(f"Retweeted {tweet_id}")
# Search tweets
def search_tweets(query, count=10):
tweets = api.search(q=query, count=count)
for tweet in tweets:
print(f"{tweet.id} - {tweet.text}")
# Reply to a tweet
def reply_to_tweet(tweet_id, message):
api.update_status(status=message, in_reply_to_status_id=tweet_id, auto_populate_reply_metadata=True)
print(f"Replied to tweet {tweet_id}")
# Automated follow-back
def auto_follow_back():
for follower in tweepy.Cursor(api.followers).items():
if not follower.following:
follower.follow()
print(f"Followed back {follower.name}")
# Streaming class
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text)
def start_stream(keywords):
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)
myStream.filter(track=keywords)
# Send direct message
def send_direct_message(user_id, message):
api.send_direct_message(recipient_id=user_id, text=message)
print(f"DM sent to {user_id}")
# Initialize argument parser
parser = argparse.ArgumentParser(description="Twitter Bot - Perform actions on Twitter")
parser.add_argument('--action', help='Action to perform: tweet, follow, unfollow, like, unlike, retweet, search, reply, autofollowback, senddm, stream')
parser.add_argument('--param', nargs='*', help='Additional parameters for the action: message, username, tweet_id, query, user_id, keywords')
args = parser.parse_args()
if __name__ == " __main__":
if args.action and args.param:
if args.action == "tweet":
tweet(" ".join(args.param))
elif args.action == "follow":
follow(args.param[0])
elif args.action == "unfollow":
unfollow(args.param[0])
elif args.action == "like":
like(args.param[0])
elif args.action == "unlike":
unlike(args.param[0])
elif args.action == "retweet":
retweet(args.param[0])
elif args.action == "search":
search_tweets(" ".join(args.param))
elif args.action == "reply":
reply_to_tweet(args.param[0], " ".join(args.param[1:]))
elif args.action == "autofollowback":
auto_follow_back()
elif args.action == "senddm":
send_direct_message(args.param[0], " ".join(args.param[1:]))
elif args.action == "stream":
start_stream(args.param)
else:
print("Please specify an action and any necessary parameters.")
How to Use
With this modified script, you can now run one function at a time by specifying the action and any required parameters from the command line. Here are some examples:
Easier command line usage for Twitter bot with Python
Now it would be easier to send a tweet or performa any function from your terminal like this.
# Send a tweet
python bot.py --action tweet --param "This is a tweet from the command line.
# Follow someone
python bot.py --action follow --param username_here
# Like a tweet
python bot.py --action like --param tweet_id_here
# Search tweets
python bot.py --action search --param "Python programming"
# Reply to a Tweet
python bot.py --action reply --param tweet_id_here "Thanks for the info!"
This approach offers flexibility and makes it easy to integrate your Twitter bot into automated workflows or your own custom scripts.
Conclusion
Creating a Twitter bot with Python is a fun project that introduces you to the world of APIs and automation. Next project for yout try on would be to implement the same functionality using OOP in python.
May your bot be with you.
Check out our other posts related to Python programming here.
The post How to Create Your Own Twitter Bot with Python appeared first on TechTales.
Top comments (0)