I am trying to set up a “bot” account (separate from my own) that can be automated. I have been successful at accessing and tweeting from this account, but I’m running into authorization/authentication errors once the access token has expired.
From what I understand, once you have initially granted access to another account, all I should have to do is manage the generation and handling of the refresh token. – For simplicity’s sake, here is my process:
-
Check for a “twitter_token.txt” file – this file stores the token dictionary in JSON format that is retrieved from the fetch_token() method.
-
If the file doesn’t exist: the token needs to be created for the first time (step N/A for this scenario)
-
If the file does exist: load the token from the JSON file, and convert back into a dict object
-
I create a new OAuth2Session using the client_id and token_data as input
-
I send a POST request to (https)://api.twitter.com/2/tweets to create a new tweet – if the token is expired, it attempts to call refresh_token.
# Extra credentials to be passed along when refreshing tokens, usually for authentication purposes.
extra = {
'client_id': client_id,
'client_secret': client_secret,
}
headers = {
"Authorization": "Bearer {}".format(token_data["access_token"]),
"Content-Type": "application/json"
}
try:
client = OAuth2Session(client_id, token=token_data)
r = client.post('https://api.twitter.com/2/tweets', json={'text': 'Testing 1, 2, 3, 4, 5'}, headers=headers)
except TokenExpiredError as e:
token_data = client.refresh_token(refresh_url, **extra)
token_saver(token_data)
client = OAuth2Session(client_id, token=token_data)
r = client.post('https://api.twitter.com/2/tweets', json={'text': 'Testing 1, 2, 3, 4, 5'}, headers=headers)
print(r.content)
print("")
The error happens once it gets to: token_data = client.refresh_token(refresh_url, **extra)
and I get the following error:
Can anyone explain to me why I’m getting this error? From what I’ve read, as long as I have the access token, as long as I refresh it when it expires, I should still be able to access the bot account.