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
- 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.
#2 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.
#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.