Support yourself with Twitter API

Introduction

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.

Elements used

--Language: Python3

Premise

--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

1. API key setting

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.

2. Description of 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.


2.1. Import and OAuth authentication

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.


2.2. Function to execute reply

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.


2.3. Get the latest tweets regularly

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.

Execution result

I was able to execute it safely. Will this heal the wound?

python.exe


Posted!

Conclusion

In the afterlife, I want a reply from a proper human being.

Reference site

Qiita article that I used as a reference

-Try tapping the Twitter API quickly and easily with Python -Tweet with image in Python

Official reference

--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

Support yourself with Twitter API
Use Twitter API with Python
Successful update_with_media with twitter API
[Life hack] Women's Anna support bot with Twitter API
Specifying the date with the Twitter API
Collecting information from Twitter with Python (Twitter API)
Post from another account with Twitter API
Extract sudden buzzwords with twitter streaming API
Extrude with Fusion360 API
Hit the Twitter API after Oauth authentication with Django
Crawling with Python and Twitter API 1-Simple search function
Pick up only crispy Japanese with Twitter streaming API
Image download with Flickr API
Try hitting the Twitter API quickly and easily with Python
Use Trello API with python
Create an API with Django
Twitter graphing memo with Python
Get Twitter timeline with python
Extract Twitter data with CSV
API with Flask + uWSGI + Nginx
Try using the Twitter API
I tried follow management with Twitter API and Python (easy)
Get information with zabbix api
Streamline information gathering with the Twitter API and Slack bots
Web API with Python + Falcon
Try using the Twitter API
Play RocketChat with API / Python
Call the API with python3.
Search twitter tweets with python
Use subsonic API with python3
Support multi session with SQLAlchemy
Presentation Support System with Python3
Qiita API Oauth with Django
Get ranking with Rakuten API
Crawling with Python and Twitter API 2-Implementation of user search function
I made a Twitter Bot with Go x Qiita API x Lambda
Operate Nutanix with REST API Part 2
Create Awaitable with Python / C API
Get reviews with python googlemap api
Run Rotrics DexArm with python API
Quine Post with Qiita API (Python)
Twitter posting application made with Django
Hit the Etherpad-lite API with Python
Post multiple Twitter images with python
[python] Read information with Redmine API
Multi-input / multi-output model with Functional API
Create API using hug with mod_wsgi
Easily post to twitter with Python 3
Continuous acquisition by Twitter API (Tips)
GraphQL API with graphene_django in Django
Twitter search client made with bottle
Access the Twitter API in Python
Introducing Google Map API with rails
[Memo] Tweet on twitter with python
Hit ISE's ERS API with PowerShell
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Try collecting sites all over Japan compatible with Brave browser with Twitter API
Be careful when retrieving tweets at regular intervals with the Twitter API