3
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 5 years have passed since last update.

PythonでTwitter APIを使ってTerminalからツイートする

Last updated at Posted at 2019-10-23

Twitter APIを使ってみようという事で、ターミナルからツイートするアプリを作りました。
この記事を見る方は、Twitter APIを初めて使う方が多いと思うので入門にオススメの記事の紹介もしておきます。
紹介した記事を見れば、私が書いたコードは理解できると思うので説明は省きます。
まずは、コピペして動かしてみてTwitter APIを楽しんでください!

はじめに

予め読んでおいて欲しい記事を紹介します。

  1. Twitter APIの申請手順 -> kngsym2018様の記事
  2. APIって何?ドキュメントってどうやって読むの? -> [masahiro_isonoさんの記事]
    (https://qiita.com/masahiro_isono/items/a6cfdd073686100f0ef1)
  3. 公式ドキュメント -> [Twitter Developers]
    (https://developer.twitter.com/en/docs)
  4. 環境変数確認とパスの追加 -> [FJHoshi様の記事]
    (https://qiita.com/FJHoshi/items/c847ad51af388d2dbb4a)

コード

コマンドライン引数にツイートしたい文を打ち込み、プログラムを実行する事でツイートするプログラムです。

tweet.py
import sys, config
from requests_oauthlib import OAuth1Session

CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)

url = 'https://api.twitter.com/1.1/statuses/update.json'

tweet = ' '.join(sys.argv[1:])
params = {'status': tweet}
res = twitter.post(url, params=params)

print('status: {}'.format(res.status_code))

同階層にconfig.pyを作り、そこにAPI Keyとアクセストークン情報が書いてあります。

環境変数

以上のコードの実行は以下です。

terminal
$ python tweet.py hogehoge 

ツイートする度にこれをいちいち打つのはめんどくさいですね。
そこで[python tweet.py]の部分を.bash_profileに環境変数として書いちゃいましょう。
[tweet.pyのフルパス]に括弧を消してプログラムファイルのフルパスを入れてください。
詳しくは、紹介した記事の4をみてください。

terminal
$ echo export tweet=python\ [tweet.pyのフルパス] >>~/.bash_profile

毎回打たなければいけない部分を環境変数にしたことで以下のように簡単にツイートすることができるようになります。
*環境変数を使用する際は、変数名の前に$をつける必要があります。

terminal
$ $tweet hogehoge

以上でTwitter APIを使ってTerminalからツイートすることができました。
なお、ツイートすると何を使ってツイートされたかが表示されるようになりましたが、APIを通してツイートした場合はアプリ名がそこに表示されるのでくれぐれも変な名前にしてしまわないように気をつけてください。

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