LoginSignup
97

More than 5 years have passed since last update.

簡単!Herokuで動くTwitter botをPythonで実装する

Last updated at Posted at 2016-07-18

Herokuで動くTwitter botをPythonで実装する方法を紹介します。
やり尽くされたネタだとは思いますが、2016年版ということで。

実現方法としては、Heroku上にPythonスクリプトをデプロイして、Heroku Schedulerを使ってスクリプトを定期実行します。

完成版のソースコードは以下にあります。
https://github.com/k-enomoto/minimum_twitter_bot

この記事で説明すること

  • Twitter Botの最低限のソースコード
  • Herokuへのデプロイ
  • Heroku Schedulerの設定

この記事で説明しないこと

  • Herokuの使い方
  • pipの使い方
  • Twitter APIのアカウント作成方法

それぞれ他に詳しい記事がありますので、参考にしてください。

ライブラリの準備

使用するライブラリをインストールします。

$ pip install python-twitter
$ pip install bottle

Herokuにどのライブラリを使うか教えてあげる必要があるので、 requirements.txt を作成します。

$ pip freeze -l > requirements.txt

多分こんな内容になります。

bottle==0.12.9
future==0.15.2
oauthlib==1.1.2
python-twitter==3.1
requests==2.10.0
requests-oauthlib==0.6.2

Twitter APIにアクセスするコード

事前にTwitter APIの consumer_key, consumer_secret, access_token_key, access_token_secret を取得しておきます。
取得方法は以下の記事を参考にしてください。
RubyでTwitter APIを使ってツイートする
また各キーはセキュリティの観点から、環境変数に設定します。Herokuでの環境変数の設定方法は後述します。

つぶやきの内容はWeb APIから取るなり、ご自由にアレンジしてください。

tweet.py
# -*- coding: utf-8 -*-

import os
from datetime import datetime

import twitter


api = twitter.Api(consumer_key=os.environ["CONSUMER_KEY"],
                  consumer_secret=os.environ["CONSUMER_SECRET"],
                  access_token_key=os.environ["ACCESS_TOKEN_KEY"],
                  access_token_secret=os.environ["ACCESS_TOKEN_SECRET"]
                  )
api.PostUpdate("system time is %s" % datetime.now())

Webアプリのコード(ダミー)

今回のポイントになる箇所です。
Herokuでプロセスを動かしておくために、ダミーのWebアプリを用意します。本記事では軽量Webフレームワークbottleを使いました。
bottleのドキュメントにあるサンプルコードをそのまま流用しています。

index.py
# -*- coding: utf-8 -*-

import os
from bottle import route, run


@route("/")
def hello_world():
    return "" # ここで返す内容は何でもよい

run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))

Procfile

ProcfileにはHerokuのコンテナで実行するコマンドを記載します。
前述のダミーWebアプリを起動するコマンドを記載します。

Procfile
web: python index.py

runtime.txt

ポイントその2です。
runtime.txt を作成し、使用するランタイムを記述します。

runtime.txt
python-3.5.2

デプロイ

以上で必要なファイルが揃いました。

index.py
tweet.py
requirements.txt
runtime.txt
Procfile

Herokuにデプロイするために、ファイルはGitで管理する必要があります。Gitにコミットします。

git add .
git commit -m "Initial commit"

Herokuにデプロイします。
また前述した環境変数の設定はここで行います。 your_cosumer_key, your_consumer_secret, your_access_token_key, your_access_token_secretはご自身の値に読み替えてください。

$ heroku create --stack cedar
$ git push heroku master
$ heroku config:set CONSUMER_KEY=your_cosumer_key CONSUMER_SECRET=your_consumer_secret ACCESS_TOKEN_KEY=your_access_token_key ACCESS_TOKEN_SECRET=your_access_token_secret

ちゃんとデプロイできているか、確認しておきます。

$ heroku logs

スケジューラタスクの登録

最後に、Heroku Schedulerにタスクを登録します。
以下のコマンドを入力すると、スケジューラの登録ページが立ち上がります。

$ heroku addons:create scheduler:standard
$ heroku addons:open scheduler

スケジューラで実行するコマンドと、頻度を設定します。
つぶやくためのPythonスクリプトを設定しておきましょう。

$ python tweet.py

scsho.png

これでTwitter botが完成しました。

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
97