It's easy to tweet automatically from your account using the Twitter API, but a memo when I didn't know how to tweet from another account [^ 1]. [^ 1]: Since the purpose of use should be stated when applying for the API, it is naturally NG to use it beyond that range. At your own risk.
--Python is available (I'm version 3.7.0) --Twitter API application has been completed
I will use here (I am version 1.18.0).
pip install twitter
The method to make a note from now on is probably using PIN-based authorization. Callback_url doesn't seem to be used. However, since the official document says as follows, I will also fill in the Callback URLs like the image [^ 2]. [^ 2]: It shouldn't be used, so anything is fine, but for the time being, I used the URL of my github page.
The callback_url within the Twitter app settings is still required, even when using PIN-based auth.
Prepare the following two files in the same directory.
config.py
app_name = "XXXXXXXXXX" #Application name created above
consumer_key = "XXXXXXXXXX" #Consumer API Keys on the application management screen> API key
consumer_secret = "XXXXXXXXXX" #Consumer API Keys on the application management screen> API secret key
main.py
from twitter import *
from config import *
oauth_dance(app_name, consumer_key, consumer_secret, token_filename="./config.txt", open_browser=False)
When you run main.py
, the URL will be displayed as shown below and you will be prompted to enter your PIN.
Hi there! We're gonna get you all set up to use sample.
Opening: https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxx
Please go to the following URL, authorize the app, and copy the PIN:
https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxx
Please enter the PIN:
Open the URL in your browser, and then log in with the account you want to tweet and get a PIN [^ 3]. When you enter the PIN, the following message will be displayed and the token and token_secret will be saved in config.txt
.
[^ 3]: Normally, I would ask the user of my application to log in, but I checked the operation with my sub-account.
That's it! Your authorization keys have been written to ./config.txt.
The actual Python script to tweet is as follows. The same package as used for preparation is used.
from twitter import *
from config import *
t = Twitter(
auth=OAuth(
'XXXXXXXXXX', # token(config.1st line of txt)
'XXXXXXXXXX', # token_secret(config.2nd line of txt)
consumer_key,
consumer_secret,
)
)
t.statuses.update(status="message")
If you change the " message "
on the last line to any string, you should be able to tweet as you like.
Recommended Posts