Learn to Automate Twitter Posts using Python and Tweepy

a person automating Twitter posts using Python and Tweepy, with tweets, Twitter logos, and coding elements surrounding a laptop.

Twitter (now known as X) is a popular social media platform that connects people from all over the world. Mostly, it is popular for its real-time nature for breaking news, live events, and trending topics. I think every tech-savvy person in the world knows Twitter’s importance. But wait, what if you can automate your Tweets using a few lines of Python code, sounds interesting, right?

In this tutorial, you’ll learn how you can Automate Twitter (X) posts using Python and the Tweepy library. Tweepy is a Python library for the Twitter API that allows us to automate posting tweets, retrieving user timelines, retweeting, liking, and many more features.

At the end of this tutorial, you’ll be able to:

  • Set up Tweepy on your system and authenticate with the Twitter API.
  • Post automated tweets using a Python script.
  • Schedule Twitter posts using Python.
  • Automate media uploads (images/videos) to Twitter.
  • Explore additional functionalities like retweeting, liking tweets, and fetching user timelines.

So, let’s get started!

Read Also: Build a Web Scraper to Compare E-Commerce Prices Using Python

What is Tweepy?

Tweepy is a Python library that interacts with the Twitter API. It allows access to various Twitter functionalities, such as posting tweets, reading timelines, searching for tweets, following users, sending direct messages, etc., using Python code.

Why do You Automate Twitter (X) Posts?

Automating your tweets can be beneficial for several reasons:

  • Consistency: Regular posting can keep your audience engaged.
  • Time-saving: You can schedule your posts in advance and focus on other tasks.
  • Efficiency: Automation ensures that your posts go live at optimal times, even if you’re busy.

Requirements

Before we start coding, make sure the following requirements are satisfied:

1. Make sure Python is installed on your system (Python 3.x recommended).

2. You’ll need a Twitter Developer account to access Twitter API. You can apply for one here.

3. Install the Tweepy library using the following command:

pip install tweepy

Tweepy documentation: docs.tweepy.org

Important: Twitter (X) API Access Limitations

As of 2024, Twitter’s API (now X API) has several access tiers:

PlanMonthly CostPermissions
Free$0Read-only + limited OAuth, no tweeting
Basic$200Read/Write access, including tweets
Pro / Enterprise$$$Full access

⚠️ You cannot post tweets on the Free plan. To use update_status() or tweet images/videos, you must upgrade to the Basic plan.

More Info: Twitter/X API Pricing

Get Twitter (X) API credentials

Before we access the functionalities of Tweepy, we have to get the following Twitter API credentials:

  1. API Key
  2. API Key Secret
  3. Access Token
  4. Access Token Secret

These credentials will be used in our Python script to authenticate with Twitter.

How to Get Twitter (X) API Credentials

Step 1: Visit Twitter’s developer platform

Visit the Twitter developer platform from here developer.x.com. Next, sign up with your Google/apple account and choose a Twitter account that you want to work with.

sign in platform to x developer-platform

Step 2: Choose a plan

Choose a plan according to your needs.

x developer platform pricing list

Step 3: Describe your use cases

After you choose the plan, you have to describe the purpose of accessing Twitter’s API and agree to its terms.

describing use cases of x developer portal

Step 4: Get the Credentials

After completing the previous step, you may need to fill in some basic information related to the app you’re creating. Here the app means the bot we’re developing using the Python language which the Twitter API will use later.

After you feel some basic information, you will find the API key, API Secret Key, Access Token, and Access Token Secret under the “Projects and Apps” section on the left sidebar. Please note and keep those credentials safe, like passwords.

keys and tokens of x developer portal

Automating Twitter Posts with Python

Authenticate with Twitter API

First, let’s authenticate our Python code using the credentials we got before.

import tweepy

# Replace with your own credentials
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_SECRET = "your_access_secret"

# Authenticate with Twitter API
auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

api = tweepy.API(auth)

print("Authentication successful!")

If everything is set up correctly, you should see “Authentication successful!” printed on the console.

Post a Tweet

As we’re authenticated, let’s post a tweet using Python.

tweet_text = "Hello, Twitter! This is an automated tweet using Python Tweepy. #Python #Tweepy"
api.update_status(tweet_text)
print("Tweet posted successfully!")

❗ If you’re on the Free plan, you will get a 403 Forbidden error:
453 – You currently have access to a subset of X API V2 endpoints…

Schedule Tweets with a Timer

You can schedule your tweets with a timer. For example, you tweet something and you want to place the next tweet after a specific amount of time. You can easily schedule your tweets using the time module. Let’s see the example below.

import time

tweets = [
    "Automating tweets with Python is fun! #Python",
    "Tweepy makes Twitter automation easy. #Tweepy",
    "Follow me for more Python tips! #Coding"
]

for tweet in tweets:
    try:
        api.update_status(tweet)
        print(f"Tweet Posted: {tweet}")
        time.sleep(60)  # 1 minute delay
    except Exception as e:
        print("Failed to post:", e)

In the above code, after the first tweet, we schedule the next tweet after 1 minute (60 seconds) and the same thing for the upcoming one.

Post a Tweet with an Image

You can post your tweet with an image also using the media_upload() function.

image_path = "image.jpg"
tweet_text = "Check out this amazing photo! #Python #Tweepy"

media = api.media_upload(image_path)
api.update_status(status=tweet_text, media_ids=[media.media_id])

print("Tweet with image posted successfully!")

Post a Tweet with a Video

For video upload, we follow the same approach as the previous one.

video_path = "video.mp4"
tweet_text = "Watch this cool video! #Python #Automation"

media = api.media_upload(video_path, media_category="tweet_video")
api.update_status(status=tweet_text, media_ids=[media.media_id])

print("Tweet with video posted successfully!")

Retweeting Tweets

Twitter (currently X) allows users to share a tweet from another user with their own followers, it’s called retweeting. With the help of Tweepy, we can do the same task using a few lines of Python code. Let’s see an example:

tweet_id = "1234567890123456789"  # Replace with a valid tweet ID
api.retweet(tweet_id)
print("Tweet retweeted successfully!")

Like a Tweet

Linking a tweet is also possible using Tweepy. See the following example:

tweet_id = "1234567890123456789"  # Replace with a valid tweet ID
api.create_favorite(tweet_id)
print("Tweet liked successfully!")

Fetch the Latest Tweets from Timeline

Let’s learn how to fetch the latest tweets from the timeline:

public_tweets = api.home_timeline(count=5)
for tweet in public_tweets:
    print(tweet.text)

In the above code, we mentioned count=5 inside the home_timeline() function. In this scenario, only five of the latest tweets will be fetched. You can increase or decrease the number as per your requirements.

Follow a User

You can follow a user on Twitter using Tweepy.

user_to_follow = "TwitterUsername"
api.create_friendship(user_to_follow)
print(f"Followed {user_to_follow} successfully!")

📋Tweepy Functionality Table

Tweepy FunctionPurpose
update_status()Post a new tweet
media_upload()Upload image/video to tweet
retweet(id)Retweet a specific tweet by ID
create_favorite(id)Like a tweet by ID
home_timeline()Fetch recent tweets from timeline
create_friendship(username)Follow a user by username
destroy_status(id)Delete a tweet by ID
update_profile()Update your profile info
get_user(screen_name)Get user profile info
followers()Fetch recent tweets from the timeline
friends()Get the list of followers
lookup_users(user_ids)Get multiple users’ details by ID

Summary

In this tutorial, we learned how to automate Twitter posts using Python and Tweepy. We learned how to:

  • Set up Tweepy and get Twitter (currently X) Credentials.
  • Authenticate Python Code with Twitter API.
  • Post simple tweets using Python.
  • Schedule automated tweets.
  • Post tweets with images and videos.
  • Retweet, like tweets, fetch timelines and follow users.

With the help of this knowledge, you can build a powerful Twitter bot to increase your social media presence.

If you have any queries related to this topic, please reach out to me at contact@pyseek.com.

Happy Coding!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 211