1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめまして。MeeのS子です。
この記事では「twitter API v2 oauth2.0と連携し、コードを使ってツイートする」方法について書いています。
必要なコードのみ書いています。
今後は、このコードを読み解くのに必要な知識を私自身勉強しながら、別に記事にまとめていければと思います。

1.1 Oauth2.0の認証・アクセストークンの取得

まず、Oauth2.0の認証とアクセストークンの取得を次のコードで行います。手順はコードの後に説明します。
(※ちなみに下記コードはこちらを参考に…というかほぼ写経させてもらいました。
私の環境ではうまく動かなかったところを一部アレンジしています。)

example1.py
import base64
import hashlib
import os
import re
import json
import requests
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session

# 認証準備
client_id = "【自分のClient id】"
client_secret = "【自分のClient secret】"
redirect_uri = "http://localhost:3000/twitter/redirect"
scopes = ["tweet.read", "tweet.write", "users.read", "offline.access"] 

# 任意の文字列とその変換形を作成
code_verifier = base64.urlsafe_b64encode(os.urandom(30)).decode("utf-8")
code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier)
code_challenge = hashlib.sha256(code_verifier.encode("utf-8")).digest()
code_challenge = base64.urlsafe_b64encode(code_challenge).decode("utf-8")
code_challenge = code_challenge.replace("=", "")

oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes)

#認証リクエストURLの生成
auth_url = "https://twitter.com/i/oauth2/authorize"
authorization_url, state = oauth.authorization_url(
    auth_url, code_challenge=code_challenge, code_challenge_method="S256"
)
print(authorization_url)
authorization_response = input(
    "Paste in the full URL after you've authorized your App:\n"
)

# サーバーでSSLを設定していないので下記コードが必要
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

token_url = "https://api.twitter.com/2/oauth2/token"
auth = HTTPBasicAuth(client_id, client_secret)
token = oauth.fetch_token(
    token_url=token_url,
    authorization_response=authorization_response,
    auth=auth,
    client_id=client_id,
    include_client_id=True,
    code_verifier=code_verifier,
)
print(token)

# 認証と操作対象設定(事前準備ゴール)
access = token["access_token"]

# リクエスト作成/疎通確認
headers = {
    "Authorization": "Bearer {}".format(access),
    "User-Agent": "auth_test",
}
url = "https://api.twitter.com/2/users/me"
response = requests.request("GET", url, headers=headers)
if response.status_code != 200:
    raise Exception(
        "Request returned an error: {} {}".format(response.status_code, response.text)
    )
print("finish!")

手順
1.1.1 コード内の【】に対応する内容を書く
1.1.2 コードを実行する
1.1.3 プロンプト上にURLがでてくるので、そのURLへアクセス
1.1.4 Xの認証画面がでてくるので認証する
1.1.5 リダイレクトURIにとぶ
1.1.6 URLをコピペしてプロンプトに貼り付け+Enterキーを押す
1.1.7 プロンプトにaccess tokenが表示される
1.1.8 access tokenをコピペする

1.2 ツイートする

次に先ほど取得したaccess tokenを下記コードに貼り付けましょう。
そして【ツイートしたいこと】につぶやきたいことを記載して下さい。

example2.py
import requests

access_token = "【1.1で取得したaccess_token】"
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-type": "application/json"
}
data = {
    "text": "【ツイートしたいこと】"
}
response = requests.post("https://api.twitter.com/2/tweets", headers=headers, json=data)
print(response.json())

これでツイートできるはずです。
URLエンコードやハッシュ化などの知識はおいおい記事にまとめていこうと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?