ゆるいプログラミングネタです.
PythonでTwitterに天気を自動投稿させてみました.
今更感もありますが……
使ったもの
下ごしらえ
pip install python-twitterでpython-twitterを導入します.
つくる
TwitWeather.pyという名前で作成しました.
アタマ
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import twitter
from system import conf # ./system/conf.pyにAPIキーなどを記述しています.
import urllib # 天気取得時に使用
import urllib2
import json
# const
api = twitter.Api(
consumer_key = conf.consumer_key,
consumer_secret = conf.consumer_secret,
access_token_key = conf.access_token_key,
access_token_secret = conf.access_token_secret,
)
# system/conf.pyからAPIキーなどを読んできます.
天気取得
def get_weather():
city = 'Ikoma,jp'
url = 'http://api.openweathermap.org/data/2.5/forecast/daily?'
query = {
'q': 'Ikoma,jp',
'mode': 'json',
'units': 'metric',
'cnt': '1',
}
req = urllib.urlencode(query)
res = urllib2.urlopen(url + req)
line = res.readline()
#print line
desc = []
desc.append(city)
weather = json.loads(line)['list'][0]['weather'][0]['description']
desc.append(str(weather))
desc.append('min:')
temp_min = json.loads(line)['list'][0]['temp']['min']
desc.append(str(temp_min))
desc.append('max:')
temp_max = json.loads(line)['list'][0]['temp']['max']
desc.append(str(temp_max))
return desc
天気の取得にはOpenWeatherMap current weather and forecastを使いました.
クエリ http://api.openweathermap.org/data/2.5/forecast/daily?q=Ikoma,jp&mode=json&units=metric&cnt=1を投げると
{"cod":"200","message":0.0585,"city":{"id":1861749,"name":"Ikoma","coord":{"lon":135.699997,"lat":34.683331},"country":"JP","population":0,"sys":{"population":0}},"cnt":1,"list":[{"dt":1431914400,"temp":{"day":16.89,"min":16.45,"max":16.89,"night":16.45,"eve":16.89,"morn":16.89},"pressure":995.29,"humidity":96,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.59,"deg":120,"clouds":92,"rain":6.9}]}
が返ってきます.
ちなみに,jsonをパッと確認する際にはJSON整形サービスをよく利用させてもらっています.
今回は 天気,最低気温,最高気温 を表示したかったので上記のようにしています.
それらの情報をdescとして返しています.
ツイート
def tweet(desc):
content = '.@mhr380'
for item in desc:
content += ' '
content += item
content += ' """Tweeted by Bot"""'
print content
status = api.PostUpdate(content)
先ほど返したdescをツイートしますが,コードはこれだけです.
APIにツイートしたい内容を渡してあげるだけです.
APIキーなど
https://apps.twitter.com/app/newに必要事項を入力するとAPIキーがもらえます.
それを,system/conf.pyに記述します.
#!/usr/bin/env python # -*- coding: utf-8 -*- consumer_key = 'xxxxxxxx' consumer_secret ='xxxxxxxx' access_token_key = 'xxxxxxxx' access_token_secret = 'xxxxxxxx'
herokuの準備
今回はheroku上で動かします.設定ファイルとしてProcfile(拡張子なし) とrequirements.txtが必要になります.
まずProcfileは
bot: python TwitWeather.py
のように記述します.
次に,requirements.txtには,用いた外部ライブラリおよびそのバージョンを記述します.
今回使用したライブラリはpython-twitterのみで,そのバージョンはpip listで調べることができます.
で,requirements.txtには
python-twitter==2.2
と記述します.
デプロイ
heroku上にデプロイします.ご存知の通り,デプロイにはgitを用いるので,コミットしておきましょう. なお,手順などはこちらのブログ記事を参考に行いました.
firstspring1845.hatenablog.com
完成?
こんな感じで,勝手に天気をツイートしてくれます.
今後
(もうちょいテクノロジー感のあることをしたい)