YU2TA7KA's BLOG ~take one step at a time~

派生開発、組み込み開発周りのこと。

RaspberryPi(Python)で『定期的に』Tweetを投稿するために必要なこと

はじめに

RaspberryPiから投稿する場合のメリットとして、それを常時稼働させておけば定期的な投稿も容易であることが挙げられます。PaizaCloudやHerokuなどのクラウドサーバを利用することでも実現可能ですが、自分で環境を持っているというのは所有欲も満たされてなんか良い感じだと思います。

定期実行

デフォルトでは入っていないため、ライブラリをインストールします。

$pip install schedule
import schedule
import time

def job():
    #定期実行処理
    twitter.update_status(status=message)

#1時間ごとに実行
schedule.every().hour.do(job)

#ループ処理
while True:
    schedule.run_pending()
    time.sleep(1)

実装コード

www.yu2ta7ka-emdded.com
上記で作成したソースコードのbot.pyに組み込みます。これをnohupコマンドで実行します。起動時にプログラムを実行する方法もありますが、nohupコマンドが楽だったのでひとまずはこれでやっています。

bot.py

#!/usr/bin/env python
# coding: utf-8
import schedule
import time
import random
import twython

# twitter configuration
from twython import Twython
from auth import (
    consumer_key,
    consumer_secret,
    access_token,
    access_token_secret
)

twitter = Twython(
    consumer_key,
    consumer_secret,
    access_token,
    access_token_secret
)


def job():
    prefecture_list = []
    municipality_list = []
    title_list = []

    # Read Data Base
    for line in open('db.txt', 'r'):
        title, prefecture, municipality = line[:-1].split('\t')
        title_list.append(title)
        prefecture_list.append(prefecture)
        municipality_list.append(municipality)

    # message create
    list_max_num = len(prefecture_list)
    list_num = random.randrange(0,list_max_num)
    message = title_list[list_num] + 'の聖地は' + prefecture_list[list_num] + 'の' + municipality_list[list_num] + 'ですっ!'

    try:
        # tweet
        print(message)
        twitter.update_status(status=message)
    except twython.TwythonError as err_message:
        print err_message

#1時間毎に実行
schedule.every().hour.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

おわりに

ここまで出来るとひとまずbotっぽくなったような気がします。