How to Post Tweets Programmatically to X Using Python

SOPA Images/GettyImages
facebooktwitterreddit

Automating your posts to X (formerly Twitter) can be extremely useful for developers managing multiple accounts, automating updates, or scheduling posts, and it’s easy to do with a simple Python script.

Before you begin

We’ve already covered creating the X app by signing into the developer page, which provides you with access codes for this script. So check that out first if you need to.

Also, if you are new to Python or are interested in more scripts, we have a long list of projects that will help you get started. Everything from writing your first script to a script that breaks secret codes is there for you to check out.

Writing a Python script to post to X

Install the necessary Python libraries

To interact with the X API and authenticate with OAuth 1.0a, we’ll need the requests and requests-OAuth lib libraries. Open your terminal or command prompt and run the following commands to install them:

pip install requests requests-oauthlib

Set up your Python script

With the libraries installed, we can start writing the script that will post a tweet to X using OAuth 1.0a. Here’s a breakdown of how the script works:

  • We use the OAuth1 class from the requests-oauthlib library to authenticate using your API credentials. This is required for the X API v2’s “Tweet Post” endpoint.
  • We send a POST request to the endpoint https://api.twitter.com/2/tweets, with the tweet content as the payload. The API expects JSON-formatted data.
  • If the tweet is successfully posted, the server returns a status code 201. If there’s an issue (such as invalid credentials or API limits), the script will print the error message returned by X.

The full Python script

import requests

from requests_oauthlib import OAuth1

# Replace these with your actual API keys and tokens

api_key = 'YOUR_API_KEY'

api_secret = 'YOUR_API_SECRET'

access_token = 'YOUR_ACCESS_TOKEN'

access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET'

# Set up the OAuth1 authentication

auth = OAuth1(api_key, api_secret, access_token, access_token_secret)

# Define the tweet text

tweet_text = "THIS IS YOUR TWEET"

# X API v2 endpoint for posting tweets

url = "https://api.twitter.com/2/tweets"

# Data payload (tweet content)

payload = {

    “text”: tweet_text

}

# Make the request to post a tweet using OAuth1 authentication

response = requests.post(url, auth=auth, json=payload)

# Check if the request was successful

if response.status_code == 201:

    print("Tweet successfully posted!")

else:

    print(f"Failed to post tweet. Status code: {response.status_code}")

    print(f"Error: {response.text}")

# Wait for user input before ending the script

input("Press Enter to exit the script.")

Running the script

If you paste this code into a text file, change the access to the codes you have saved from when you created the X app, then save it with the file extension PY (x-post.py), then double click the file it should post to your X account.

You can keep changing the tweet and running the ode to make new tweets, but you will likely want to make the tweet a variable and add code to select new tweets from a spreadsheet automatically. You will also likely want to use a schedule to run the script automatically so you can make posts throughout the day. But that’s for the next article.

Follow GeekSided for more productivity-boosting tools.

feed