X (Twitter) Automation with Python
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.
I. Get a X Developer Account
- Open a private window and login to x.com as the account you want to automate. (Not needed if you only have one account)
- Go to developer.x.com and click “Sign up for Free Account”
- Fill the form explaining your use case.
II. Get your keys
- Go to Projects & Apps > Default project-{long-id} > {long-id} and under “User authentication settings” click “Set up”.
- Grant Read and write Permissions
- Save your
Client ID
andClient Secret
but we will not need them unless we implement “Login with X” functionality. - Go to Projects & Apps > Default project-{long-id} > {long-id} > Keys and tokens
- Click “Regenerate” on API Key and Secret. (Because we need new keys now that we added write permissions). Save your new
API Key
andAPI Key Secret
. We will need them for Tweepy - From the same page, generate “Access Token and Secret”. Save the resulting
Access Token
andAccess Token Secret
That will also be needed by Tweepy.
III. 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.
Recent TILs
Dockerize your Gatsby Projects
JavaScript-based projects tend to rot quickly. Very often, when I come back to them a few months later, nothing works. Today simply running my Gatsby blog after…
Google Login with Django Allauth
I often find myself needing to implement Google OAuth in Django projects but keep forgetting the exact steps. So, I'm documenting the process here for future…
Login Required Modal with Django
The goal is to show a modal when the user clicks on a link, rather than redirecting him right away to the auth page. It just seems less confusing. In a file…