Use Twitter API with Python

I just wrapped tweepy, but it's a hassle to catch old code and remember how to use it every time, so my Twitter API library and notes on how to use it.

My Twitter API library

Set the following values in the environment variables. --TWITTER_CONSUMER_KEY: "Consumer Key (API Key)" in the "Keys and Access Tokens" tab of the Twitter App --TWITTER_CONSUMER_SECRET: "Consumer Secret (API Secret)" in the "Keys and Access Tokens" tab of the Twitter App --TWITTER_CALLBACK_URL: "Callback URL" set in the "Settings" tab of the Twitter App

twitter.py


# -*- coding: utf-8 -*-

import os
import urllib2
import os.path
import logging
import traceback

import oauthlib
import tweepy


CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET')
CALLBACK_URL = os.environ.get('TWITTER_CALLBACK_URL')


#

def api(access_token = None, access_token_secret = None, with_callback_url = False):
    if with_callback_url:
        auth = tweepy.OAuthHandler(
            consumer_key = CONSUMER_KEY,
            consumer_secret = CONSUMER_SECRET,
            callback_url = CALLBACK_URL)
    else:
        auth = tweepy.OAuthHandler(
            consumer_key = CONSUMER_KEY,
            consumer_secret = CONSUMER_SECRET)

    if access_token is not None and access_token_secret is not None:
        auth.set_access_token(access_token, access_token_secret)

    return tweepy.API(auth)


# API
 
def get_tweets(screen_name = None, hashtag = None, count = 200):
    if screen_name is not None:
        cursor = tweepy.Cursor(api().user_timeline, 
        screen_name = screen_name, count = 200, exclude_replies = True)
    elif hashtag is not None:
        cursor = tweepy.Cursor(api().search, q = u"#{0}".format(hashtag), count = 200)

    if count is not None:
        return cursor.items(count)
    else:
        return cursor.items()

def tweet_link(tweet):
    return "https://twitter.com/{screen_name}/status/{tweet_id}".format(
        screen_name = tweet.user.screen_name,
        tweet_id = tweet.id_str)

def get_friends(screen_name):
    return tweepy.Cursor(api().friends, screen_name = screen_name, count = 200).items()


# OAuth

def generate_auth_url():
    oauth_handler = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)
    redirect_url = oauth_handler.get_authorization_url(signin_with_twitter = True)
    request_token = oauth_handler.request_token

    return redirect_url, request_token['oauth_token'], request_token['oauth_token_secret'],

def get_access_token(request_token_key, request_token_secret, oauth_verifier):
    oauth_handler = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    oauth_handler.request_token = {
        'oauth_token': request_token_key,
        'oauth_token_secret': request_token_secret,
        'oauth_callback_confirmed': True,
    }
    oauth_handler.get_access_token(oauth_verifier)

    return oauth_handler.access_token, oauth_handler.access_token_secret

def verify_credentials(access_token, access_token_secret):
    api = api(access_token, access_token_secret)
    return api.verify_credentials()


# Utility

def get_big_profile_image_url(profile_image_url):
    return profile_image_url.replace('_normal', '')

Procedure for OAuth authentication on the Web

The code I'm writing is a sample code for Bottle.

1. Issue a URL for OAuth

@get('/twitter_login')
def twitter_login():
    auth_url, request_token_key, request_token_secret = twitter.generate_auth_url()

    # request_token_key and request_token_Save the secret in the session.

    redirect(auth_url)

Call twitter.generate_auth_url to issue the URL, request token, and secret to be sent to Twitter.

Then, the request token and secret are saved in the session. The value saved here is used when acquiring the access token in the callback process from Twitter.

I think that the implementation is different depending on the person here, but I store the request token and secret in the database and put only the request token in the cookie. Also, as a CSFR measure, * access source IP * or * User Agent * may also be included in the database.

Then redirect to Twitter.

2. Obtaining an access token

@get('/twitter_callback')
def twitter_callback():
    #Request token stored in session (request_token_key), secret (request)_token_get secret).

    oauth_verifier = request.query['oauth_verifier']

    access_token_key, access_token_secret = twitter.get_access_token(
        twitter_connect.request_token_key,
        twitter_connect.request_token_secret,
        oauth_verifier)

    twitter_user = twitter.verify_credentials(access_token_key, access_token_secret)

    #Processing such as user registration and login

The callback from Twitter contains ʻoauth_verifier`, so use this and the request token and secret that you put in the session to get the access token and secret.

Recommended Posts

Use Twitter API with Python
Use Trello API with python
Use subsonic API with python3
Collecting information from Twitter with Python (Twitter API)
[Python] Use JSON with Python
Use mecab with Python3
Use DynamoDB with Python
Use Python 3.8 with Anaconda
Use python with docker
Twitter graphing memo with Python
Use TUN / TAP with Python
Web API with Python + Falcon
Play RocketChat with API / Python
Support yourself with Twitter API
Call the API with python3.
Search twitter tweets with python
Successful update_with_media with twitter API
Use e-Stat API from Python
Crawling with Python and Twitter API 1-Simple search function
Python: How to use async with
Use PointGrey camera with Python (PyCapture2)
Use vl53l0x with Raspberry Pi (python)
Get reviews with python googlemap api
Run Rotrics DexArm with python API
Specifying the date with the Twitter API
[Python] Use Basic/Digest authentication with Flask
Quine Post with Qiita API (Python)
Use NAIF SPICE TOOLKIT with Python
Use rospy with virtualenv in Python3
Hit the Etherpad-lite API with Python
Post multiple Twitter images with python
[python] Read information with Redmine API
Use kabu Station® API from Python
Use Python in pyenv with NeoVim
How to use OpenPose's Python API
Use the Flickr API from Python
How to use FTP with Python
Use Windows 10 speech synthesis with Python
Use OpenCV with Python 3 in Window
Easily post to twitter with Python 3
Use PostgreSQL with Lambda (Python + psycopg2)
Access the Twitter API in Python
[Python] How to use Typetalk API
Use Google Analytics API from Python
[Memo] Tweet on twitter with python
Easy to use Nifty Cloud API with botocore and python
Try hitting the Twitter API quickly and easily with Python
I tried follow management with Twitter API and Python (easy)
FizzBuzz with Python3
Scraping with Python
Automatically create Python API documentation with Sphinx
Statistics with python
Use smbus with python3 under pyenv environment
Use DeepL with python (for dissertation translation)
Simple Slack API client made with Python
twitter on python3
Scraping with Python
Retrieving food data with Amazon API (Python)
Python with Go
[September 2020 version] Explains the procedure to use Gmail API with Python
Use Amazon Simple Notification Service with Python