X (Twitter) Automation with Python

Published on August 8th, 2024

Automating social media accounts can be annoying, especially because of the shenanigans Big Social put us through to obtain our API keys.

Here is an updated guide on how to post to X from python code.

#1 Get a X Developer Account

  1. Open a private window and login to x.com as the account you want to automate. (Not needed if you only have one account)
  2. Go to developer.x.com and click “Sign up for Free Account”
  3. Fill the form explaining your use case.

#2 Get your keys

  1. Go to Projects & Apps > Default project-{long-id} > {long-id} and under “User authentication settings” click “Set up”.
  2. Grant Read and write Permissions
  3. Save your Client ID and Client Secret but we will not need them unless we implement “Login with X” functionality.
  4. Go to Projects & Apps > Default project-{long-id} > {long-id} > Keys and tokens
  5. Click “Regenerate” on API Key and Secret. (Because we need new keys now that we added write permissions). Save your new API Key and API Key Secret . We will need them for Tweepy
  6. From the same page, generate “Access Token and Secret”. Save the resulting Access Token and Access Token Secret That will also be needed by Tweepy.

#3 Post from Python

Now we have all we need to post to our X account from our python code.

pip install tweepy
import requests
import tweepy

def post_to_x(message):
    client = tweepy.Client(
        consumer_key=settings.X_API_KEY,
        consumer_secret=settings.X_API_SECRET_KEY,
        access_token=settings.X_ACCESS_TOKEN,
        access_token_secret=settings.X_ACCESS_TOKEN_SECRET,
    )

    post_content = f"{message}"

    try:
        response = client.create_tweet(text=post_content)
        if response.data:
            print("Successfully posted to Twitter.")
            return response.data
    except Exception as e:
        print(f"Failed to post to Twitter: {e}")

And we can check that it works.

post_to_x("Hello, world!")
# Successfully posted to Twitter.