LoginSignup
18
15

More than 3 years have passed since last update.

TwitterAPIで別アカウントから投稿する

Last updated at Posted at 2020-07-18

概要

TwitterAPIを使い、自分のアカウントから自動でつぶやくのは簡単だけど、別アカウントからつぶやく方法が分からず調べた際のメモ1

前提

  • Pythonが利用可能な状況である(私はバージョン3.7.0)
  • TwitterのAPI申請が済んでいる

準備

パッケージのインストール

こちらを利用させてもらう(私はバージョン1.18.0)。

pip install twitter

アプリケーションの作成

これからメモする方法はおそらくPIN-based authorizationを利用しているので、callback_urlは使わなそう。ただ公式ドキュメントに以下のようにあるので、一応画像のようにCallback URLsも埋めておく2

The callback_url within the Twitter app settings is still required, even when using PIN-based auth.

image.png

Pythonスクリプトの準備

以下2つのファイルを同じディレクトリに準備。

config.py
app_name = "XXXXXXXXXX" # 上で作成したアプリケーション名
consumer_key = "XXXXXXXXXX" # アプリケーション管理画面のConsumer API Keys > API key
consumer_secret = "XXXXXXXXXX"  # アプリケーション管理画面のConsumer API Keys > API secret key
main.py
from twitter import *
from config import *
oauth_dance(app_name, consumer_key, consumer_secret, token_filename="./config.txt", open_browser=False)

Pythonスクリプトの実行

main.pyを実行すると、以下のようにURLが表示され、PINの入力を要求される。

Hi there! We're gonna get you all set up to use sample.
Opening: https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxx


Please go to the following URL, authorize the app, and copy the PIN:

https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxx
Please enter the PIN:

ブラウザでURLを開き、つぶやきたいアカウントでログインのうえPINを取得する3。PINを入力すると以下のメッセージが表示され、config.txtにtokenとtoken_secretが保存される。

That's it! Your authorization keys have been written to ./config.txt.

投稿

実際につぶやくPythonスクリプトは以下の通り。なお、準備の際と同じパッケージを利用している。

from twitter import *
from config import *
t = Twitter(
    auth=OAuth(
        'XXXXXXXXXX', # token(config.txtの1行目)
        'XXXXXXXXXX', # token_secret(config.txtの2行目)
        consumer_key,
        consumer_secret,
    )
)
t.statuses.update(status="message")

最終行の"message"を任意の文字列に変えれば、好きなようにつぶやけるはず。


  1. APIの申請時に利用目的など記載しているはずなので、その範囲を超える使い方は当然NG。自己責任で。 

  2. 使われないはずなので何でもいいが、私はとりあえず自分のgithubのページのURLにした。 

  3. 通常は自分のアプリケーションのユーザーにログインしてもらうのだろうが、動作確認は自分のサブアカで行った。 

18
15
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
18
15