Skip to content

Instantly share code, notes, and snippets.

@73spica
Last active July 2, 2018 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 73spica/ee5a7e83f7822c28dc7f96898280dc32 to your computer and use it in GitHub Desktop.
Save 73spica/ee5a7e83f7822c28dc7f96898280dc32 to your computer and use it in GitHub Desktop.
Using twitter api without python library.
import requests
from base64 import b64decode, b64encode
# SECRET:)
import config
def main():
# ===== 手順 (プログラム外の手順も) =====
# 1. consumer_key, consumer_key_secretの取得
# ==== ここからプログラム ====
# 2. bearer tokenの取得 (consumer_key, consumer_key_secretを使用)
# 3. Userのtimelineを取得 (bearer token, user_timeline api を使用)
# =======================================
# 1. consumer_key, consumer_key_secretの取得
# Application Managementのページから発行できる
# ===== 2. bearer tokenの取得 =====
# ref: https://developer.twitter.com/en/docs/basics/authentication/api-reference/token
headers = { "Content-Type" : "application/x-www-form-urlencoded;charset=UTF-8" }
data = { "grant_type":"client_credentials" }
oauth2_url = "https://api.twitter.com/oauth2/token"
r = requests.post(oauth2_url, data=data, headers=headers, auth=(config.CONSUMER_KEY, config.CONSUMER_SECRET))
bearer_token = r.json()["access_token"]
print("[*] Bearer token:", bearer_token, "\n")
# ===== 3. Userのtimelineを取得 =====
# ref: http://benalexkeen.com/interacting-with-the-twitter-api-using-python/
# ref: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html
username = "CVEnew" #
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
headers = {
"Authorization": "Bearer {}".format(bearer_token)
}
params = {
"screen_name": username,
#"count": 1,
}
r = requests.get(url, headers=headers, params=params)
tweets = r.json()
print(tweets[0])
if __name__ == "__main__":
main()
@73spica
Copy link
Author

73spica commented Jul 2, 2018

configには

  • Consumer Key
  • Consumer Secret
    を記載.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment