0
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?

More than 1 year has passed since last update.

twitterに自動でTweepyを使用せず、Twitter API "v2"でツイートする方法

Last updated at Posted at 2022-12-14

■やりたいこと

・自動でツイートする
・Tweepyモジュールを使用しない
・v2で行いたい
・APIキーは別ファイルで持っておきたい

■完成コード(とりあえず動かしたい人はここまで。メモ書きは後半。)

同一階層にinit.json, tweet.pyを格納
init.json には各種キーを格納。

init.json
{
    "api_key":"キーを入れる",
    "api_key_secret":"キーを入れる",
    "access_token":"トークンを入れる",
    "access_token_secret":"トークンを入れる",
}
tweet.py
from requests_oauthlib import OAuth1Session
import json

# Get request token
json_open = open('init.json', 'r')
json_load = json.load(json_open)

# Set request token
# [Hints] consumer_key = api_key, consumer_secret = api_key_secret
AK = json_load["api_key"]
AKS = json_load["api_key_secret"]
AT = json_load["access_token"]
ATS = json_load["access_token_secret"]

# Be sure to add replace the text of the with the text you wish to Tweet.
payload = {"text": "Hello!"}

# Make the request
oauth = OAuth1Session(
    AK, AKS, AT, ATS,
)

# Making the request
response = oauth.post(
    "https://api.twitter.com/2/tweets",
    json=payload,
)

if response.status_code != 201:
    raise Exception(
        "Request returned an error: {} {}".format(response.status_code, response.text)
    )

print("Response code: {}".format(response.status_code))

# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))

■めもとか

(そもそも)公式のコードだと長くてわざわざアクセスしてPINを取ってこなければならず、
必要最小限でツイートしたかった。
↓参照
https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.py

このinputで止まるのダルかった
image.png


init.jsonに格納してあるキー情報を取得しそれぞれ格納する。

tweet.py
# Get request token
json_open = open('init.json', 'r')
json_load = json.load(json_open)

# Set request token
# [Hints] consumer_key = api_key, consumer_secret = api_key_secret
AK = json_load["api_key"]
AKS = json_load["api_key_secret"]
AT = json_load["access_token"]
ATS = json_load["access_token_secret"]

ツイートしたい内容"Hello!"を入れる

tweet.py
# Be sure to add replace the text of the with the text you wish to Tweet.
payload = {"text": "Hello!"}

キーをがっちゃんこして、エンドポイント(api.twitter.com/2/tweets)へ

tweet.py
# Make the request
oauth = OAuth1Session(
    AK, AKS, AT, ATS,
)

# Making the request
response = oauth.post(
    "https://api.twitter.com/2/tweets",
    json=payload,
)

正常ならレスポンスコードは201が返ってくるはず。それ以外ならコードとエラー文を表示。

tweet.py
if response.status_code != 201:
    raise Exception(
        "Request returned an error: {} {}".format(response.status_code, response.text)
    )

コード表示して、レスポンス表示(エラー時も出るんよね。ここいらんか?)

tweet.py
print("Response code: {}".format(response.status_code))

# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
0
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
0
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?