In our platform overview, you can learn more about getting started with the Twitter API.
How do bots work with OAuth 2.0?
With OAuth 2.0, your access token, the credential you use to request v2 endpoints, stays valid for two hours. Since bots run automatically, it’s important to figure out how to handle refreshing tokens and save them to a database. While refresh tokens remain valid for six months to allow flexibility to change the timing, it might be best to generate a new one each time the bot posts a Tweet.
Since Redis is a key-value store, it seemed to be an excellent place to store my refresh tokens. Since this bot only Tweets on behalf of @Factual__Dog, there is only one entry in the Redis database that gets saved over each time. You could use this same database to save tokens for other bots if needed.
In this tutorial, your bot account will need to log into Twitter to authenticate your App on behalf of your new bot. When the bot account logs in for the first time, it can post its first Tweet and add a token to the database. To do this, you will create a Flask application that you can run locally.
After that, you can create a script that will run regularly using a cron job. This script will obtain your most recent OAuth 2.0 tokens from your Redis queue and refresh your tokens. This is because your access token, your primary access credential for using OAuth 2.0, will only stay valid for two hours. Finally, it will post a new Tweet and save your latest set of tokens to a Redis instance.