Like as soon as a reply comes on Twitter

Motivation

--I wanted to touch the Twitter API

Main subject

  1. Please access https://apps.twitter.com/ and create TwitterApps appropriately, and then give permission for Read this time on the permission tab.
  2. Make a note of the Consumer Key and Consumer secret from the key and access token
  3. And it is assumed that python is included (I made it with ver2.7)
  4. Install the library that handles Twitter with pip install tweepy
  5. Then paste the program below into a suitable python file and execute it. At this time, store Consumer Key and Consumer secret in variables respectively.
!/usr/bin/python
-*- coding: utf-8 -*-
import tweepy

consumer_key = ""#access https://apps.twitter.com/ and get consumer key
consumer_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
print("Access this URL:" + auth.get_authorization_url())
verifier = raw_input('Verifier:')
auth.get_access_token(verifier)
print "Access Token:", auth.access_token
print "Access Token Secret:", auth.access_token_secret
  1. Then the URL will be displayed, so please access it and enter the displayed code into the execution screen.
  2. Once authenticated, you will see ʻAccess Token and ʻAccess Token Secret, so make a note of each again.
  3. Paste the following program into a suitable python file and store the keys you wrote down in each variable. Also, store your Twitter ID without @.
!/usr/bin/env python
 -*- coding:utf-8 -*-

import tweepy
import datetime

class Listener(tweepy.StreamListener):
    def on_status(self, status):
        status.created_at += datetime.timedelta(hours=9)
        
        #favo when reply
        if str(status.in_reply_to_screen_name)==Twitter_ID and str(status.user.screen_name)!=Twitter_ID:
            print(str(datetime.datetime.today()))
            api.create_favorite(status.id)
        return True
    
    def on_error(self, status_code):
        print('Error code:' + str(status_code))
        return True
    
    def on_timeout(self):
        print('Timeout error')
        return True



consumer_key = ""#access s and get consumer key
consumer_secret = ""
access_token = ""
access_secret = ""
Twitter_ID = ""#Your TwitterID(Don't need @)

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

listener = Listener()
stream = tweepy.Stream(auth, listener)
stream.userstream()

  1. Then run it and you're done. By the way, the above program does not fabo even if I send a reply to myself

the end

――As mentioned above, the API is easy to use and anyone can easily create a bot.

Recommended Posts

Like as soon as a reply comes on Twitter
Register as a package on PyPI
Suspicious attacks that came as soon as I launched a blog on EC2
Would you like to make a Twitter resume?
twitter on python3
Summary when it comes out as a self-taught programmer