When I heard that I wanted to tweet on Twitter automatically, I tried to make it a little, but I was addicted to it
If you look at various sites and search, there are 4 items required to tweet from python.
CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET
I need it, but no matter how I look at it, there is no CONSUMER_KEY and CONSUMER_SECRET!
However, I can't find it anyway, so when I search
CONSUMER_KEY is API KEY CONSUMER_SECRET seems to be good with API_key_secret.
It is a code that you often see if you search, but I changed the variable to the following code. I think this is easier to understand.
twitter.py
import json
from requests_oauthlib import OAuth1Session
#Key and Token here
API_KEY = 'XXXXXXX'
API_KEY_SECRET = 'XXXXXXX'
ACCESS_TOKEN = 'XXXXXXX'
ACCESS_TOKEN_SECRET = 'XXXXXXX'
twitter = OAuth1Session(API_KEY, API_KEY_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
url = "https://api.twitter.com/1.1/statuses/update.json"
print(twitter)
tweet = "This is a test tweet from Python\r line break\r\n line break\n line break" #Tweet content
params = {"status" : tweet}
req = twitter.post(url, params = params) #Tweet here
if req.status_code == 200: #success
print("Succeed!")
else: #error
print("ERROR : %d"% req.status_code)
Even if you execute with the above code after taking API_KEY
ERROR : 401
I can't tweet at all. This case was a setting omission. As per 401, there was no authority.
First of all, since the first setting is read only, I changed the setting so that it can also be written.
However, the 401 error continues.
Why couldn't you?
Maybe after changing to read & write settings Regenerate ACCESS_KEY again.
It seems that you cannot write while using ACCESS_KEY, which can only be read unless you acquire it again.
If the 401 error still doesn't work, try getting it several times and assigning it to a variable.
https://prog-masaki.com/tweet-python/
Recommended Posts