This is an article of Tokyo National College of Technology Advent Calendar ① Day 16. Since I am a beginner in programming, I think there are many unsightly points, but I would appreciate it if you could forgive me.
By the way, I'm sorry for the personal matters from the beginning, but recently my followers' reaction to my tweets has slowed down. This is also due to my lack of effort, but as it is likely to cause a mental collapse in the near future, I decided to send a reply to my tweet myself as a symptomatic treatment for fire.
For the time being, for tweets containing negative words that I often use, such as "help me" and "I'm tired", they reply with words of comfort, effort, and encouragement with a thankful image. We aimed to use the hearty Twitter API.
--Language: Python3
--The development environment for Python3 is in place (see: [Python Tutorial in Visual Studio](https://docs.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-] visual-studio-step-01-create-project?view = vs-2019)) --All the above modules are installed and operate normally. --The application for using Twitter API has been accepted and the API key has already been obtained (Reference: [Summary of procedures from [Twitter API registration (account application method) to approval]](https://qiita.com/kngsym2018/ items / 2524d21455aac111cdee))) --What you are doing on Twitter
How To Make
First, as a standard, create a new .py
file separately from main.py
and describe the process of assigning the API key to the variable there (here, config.py
". It is the file name).
config.py
CONSUMER_KEY = 'Obtained Consumer API key'
CONSUMER_SECRET = 'Obtained Consumer API secret key'
ACCESS_TOKEN = 'Obtained Access token'
ACCESS_TOKEN_SECRET = 'Obtained Access token secret'
This completes the API key setting. All you have to do now is import this config.py
into main.py
and use the variables.
main.py
The whole of main.py
is as follows.
main.py
#File(config.py)And module import
import config
import json
import random, glob, time
from requests_oauthlib import OAuth1Session
#OAuth authentication
CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)
#Function to execute image attachment reply
def reply(replies, id):
url_media = 'https://upload.twitter.com/1.1/media/upload.json'
url_text = 'https://api.twitter.com/1.1/statuses/update.json'
images = glob.glob('images/*')
files = {'media': open(images[random.randrange(len(images))], 'rb')}
req_media = twitter.post(url_media, files = files)
media_id = json.loads(req_media.text)['media_id']
params = {'status': replies[random.randrange(len(replies))], 'media_ids': [media_id], 'in_reply_to_status_id': id}
req_text = twitter.post(url_text, params = params)
#Repeated processing with a 3-second cycle
while True:
#Get your latest tweets and list your keywords(words)Extract only those that contain the words that correspond to
url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
params ={'count': 1}
req = twitter.get(url, params = params)
words = ['help me', 'Spicy', 'Hard', 'No good', 'Impossible','I want to run away', 'Dislike', 'worst', 'I've got tired', 'I want to disappear', 'failed','I dropped the linear algebra', 'Proffesional', 'I was caught']
#List of words used for reply(replies)Randomly extract the words stored in and pass it to the reply function
replies = ['You are doing your best', 'I'm sure it's okay', 'I just happened to be sick today', 'It will definitely work tomorrow', 'Let's go well rather than squeeze!', 'Don't worry about anything', 'God will forgive you', 'As expected! I'm experiencing the hardships of life', 'Don't be spoiled', 'Pathetic', 'Human mess']
if req.status_code == 200:
timeline = json.loads(req.text)
for word in words:
if word in timeline[0]['text']:
reply(replies, timeline[0]['id_str'])
print('Posted!')
else:
print('ERROR: %d' % req.status_code)
time.sleep(3)
Next, I will give a brief explanation of main.py
.
main.py
#File(config.py)And module import
import config
import json
import random, glob, time
from requests_oauthlib import OAuth1Session
#OAuth authentication
CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)
This is almost the same as the general template. In addition to json
used to load the endpoint and config.py
, requests_oauthlib
used to pass OAuth authentication, import random
, glab
, time
and see below. I am using it for processing.
main.py
#Function to execute image attachment reply
def reply(replies, id):
url_media = 'https://upload.twitter.com/1.1/media/upload.json'
url_text = 'https://api.twitter.com/1.1/statuses/update.json'
images = glob.glob('images/*')
files = {'media': open(images[random.randrange(len(images))], 'rb')}
req_media = twitter.post(url_media, files = files)
media_id = json.loads(req_media.text)['media_id']
params = {'status': replies[random.randrange(len(replies))], 'media_ids': [media_id], 'in_reply_to_status_id': id}
req_text = twitter.post(url_text, params = params)
Here, as the comment out statement, "define the function that executes the image attachment reply". After posting an image, you can post a reply with the image attached by posting a reply with the image's ['media_id']
stored in the media_ids
parameter.
In ʻimages, the relative coordinates of the images obtained locally by
grab.grab () are assigned as a list type, and one of them is randomly assigned using
random.randrange () `. It has a structure to select and post.
To be honest, I implemented this function to acquire images from the local, so I'm thinking that it would be better to remove it so that it would be less complicated.
main.py
#Repeated processing with a 3-second cycle
while True:
#Get your latest tweets and list your keywords(words)Extract only those that contain the words that correspond to
url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
params ={'count': 1}
req = twitter.get(url, params = params)
words = ['help me', 'Spicy', 'Hard', 'No good', 'Impossible','I want to run away', 'Dislike', 'worst', 'I've got tired', 'I want to disappear', 'failed','I dropped the linear algebra', 'Proffesional', 'I was caught']
#List of words used for reply(replies)Randomly extract the words stored in and pass it to the reply function
replies = ['You are doing your best', 'I'm sure it's okay', 'I just happened to be sick today', 'It will definitely work tomorrow', 'Let's go well rather than squeeze!', 'Don't worry about anything', 'God will forgive you', 'As expected! I'm experiencing the hardships of life', 'Don't be spoiled', 'Pathetic', 'Human mess']
if req.status_code == 200:
timeline = json.loads(req.text)
for word in words:
if word in timeline[0]['text']:
reply(replies, timeline[0]['id_str'])
print('Posted!')
else:
print('ERROR: %d' % req.status_code)
time.sleep(3)
Here, by substituting the "get own tweet" endpoint for ʻurland setting the parameter to
{'count': 1}, only the latest one is obtained. After that, it is judged whether it corresponds to the list of keywords prepared in advance or not, and if it corresponds, the value is passed to the
reply ()` function mentioned above.
Also, by while True
andtime.sleep ()
, it is executed every 3 seconds [^ 1]. The maximum number of times https://api.twitter.com/1.1/statuses/user_timeline.json
can be acquired in the Twitter API is 900 times in 15 minutes = once per second, but I was worried, so I gave it some time.
Also, since it's boring to just say the words of ale, I mixed a light curse as a spice.
I was able to execute it safely. Will this heal the wound?
python.exe
Posted!
In the afterlife, I want a reply from a proper human being.
-Try tapping the Twitter API quickly and easily with Python -Tweet with image in Python
--API Reference --Twitter Developers
[^ 1]: To be exact, due to the specification of time.sleep ()
, it is not a strict 3 second cycle, but in this program it is regarded as a minor error and should be ignored. To. For more information, see How to run and validate in Python at regular intervals.
Recommended Posts