Skip to content

Instantly share code, notes, and snippets.

@motoy3d
Last active June 27, 2021 12:26
Show Gist options
  • Save motoy3d/1a7374278ed168c19306f4f2168a10d8 to your computer and use it in GitHub Desktop.
Save motoy3d/1a7374278ed168c19306f4f2168a10d8 to your computer and use it in GitHub Desktop.
Twitter API v2をPythonで使ってみる
# Twitter API v2のTweets countsで指定キーワードを含むツイートのリストを取得
# https://developer.twitter.com/en/docs/twitter-api/tweets/search/introduction
import json
import requests
import urllib.parse
import settings
# 検索条件
query = '一番搾り'
url = f'https://api.twitter.com/2/tweets/search/recent?query={urllib.parse.quote(query)}'
# 認証
headers = {'Authorization': f'Bearer {settings.bearer_token}'}
# API実行
response = requests.request('GET', url, headers=headers)
result = json.loads(response.content.decode('utf-8'))
print(json.dumps(result, indent=4, ensure_ascii=False))
# https://developer.twitter.com/ja/docs/basics/authentication/guides/bearer-tokens
bearer_token = 'your bearer_token'
# Twitter API v2のTweet lookupで指定IDのツイートのいいね数、RT数を取得
# https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/introduction
import json
import requests
import urllib.parse
import settings
tweet_id = 1409058922581794819
url = f'https://api.twitter.com/2/tweets/{tweet_id}?tweet.fields=public_metrics'
# 認証
headers = {'Authorization': f'Bearer {settings.bearer_token}'}
# API実行
response = requests.request('GET', url, headers=headers)
result = json.loads(response.content.decode('utf-8'))
print(json.dumps(result, indent=4, ensure_ascii=False))
# Twitter API v2のTweets countsで指定キーワードを含むツイート件数を取得
import json
import requests
import urllib.parse
import settings
# 検索条件
query = '一番搾り'
url = f'https://api.twitter.com/2/tweets/counts/recent?query={urllib.parse.quote(query)}&granularity=day'
# 認証
headers = {'Authorization': f'Bearer {settings.bearer_token}'}
# API実行
response = requests.request('GET', url, headers=headers)
result = json.loads(response.content.decode('utf-8'))
print(json.dumps(result, indent=4, ensure_ascii=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment