botで天気予報をtweet その2


はい。

過去記事 http://qiita.com/clarinet758/items/0142e88cd19a4246f308

http://weather.service.msn.com/data.aspx?src=vista&weadegreetype=C&culture=ja-JP&wealocations=wc:

残念ながら更新が2016年11月中頃から更新がデータが更新されていないようです。

なんかその3を起こすのもなんなので更新でお茶を濁します。新たな取得先はOpenWeatherMapにしました。使用したのは未だにPython2系です。辛いですね。

参考先様

http://qiita.com/b-wind/items/06e19043a0cd70b10b03

http://qiita.com/nownabe/items/aeac1ce0977be963a740

http://qiita.com/sudnonk12/items/744fb48e378c05979952

上記を閲覧されたらこの先は特に読む必要ないのではと思います。

Twitterのためにちょっと情報が欲しいと言うなら使うのは2種類のどちらかかな?と、

1. Current weather data

エンドポイントは、 api.openweathermap.org/data/2.5/weather?以下オプション です。

取得できるのは最新の更新時点での状態の1ケース?のみ。現在のお天気を〜とかならばこちらを使用するのではないかと思います。今回欲しかったのはコレではなかったので、コチラについてはここまで。

2. 5 day / 3 hour forecast

エンドポイントは、 api.openweathermap.org/data/2.5/forecast??以下オプション です。

取得できるのは3時間区切りで5日分のようです。何月何日何時の予報なのかはdt_txtの値で確認が出来ます。 なお、3時間区切りの情報のために「明日の天気」をどの時間のものを参照するかがまた悩む箇所かと思います。

サンプルコード

weather
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import oat
import time
import urllib2
import json


class Weather3:
    def __init__(self, api_key, hour, name, code, tag):
        self.api_key = api_key
        self.day = [u'今日', u'明日'][hour == **].encode('utf-8')
        self.name = name.encode('utf-8')
        self.code = code
        self.indx = [-1]*25
        self.indx[*] = *
        self.f = self.indx[hour]
        self.tag = tag

    def get_json(self):
        url = 'http://api.openweathermap.org/data/2.5/forecast?id={0:}&APPID={1:}'.format(self.code, self.api_key)
        o = urllib2.urlopen(url)
        r = o.read()
        j = json.loads(r)
        return j

    def get_info(self):
        ind = self.f
        data = self.get_json()
        base = data['list'][ind]
        tenki = base['weather'][0]['main']
        t_max = str('{0:.2f}'.format(base['main']['temp_max']-273.15))
        t_min = str('{0:.2f}'.format(base['main']['temp_min']-273.15))
        return (tenki, t_max, t_min)

    def make_txt(self):
        d = self.get_info()
        temp = "{0:}の{1:}ら辺の天候は{2:}です。最高気温は{3:}度くらいで、最低気温は{4:}度くらい。 #{5:}"
        text = temp.format(self.day, self.name, d[0], d[1], d[2], self.tag)
        return text

    def tweet(self):
        message = self.make_txt()
#        print message
        oat.tweet(message)

    def run(self):
        self.tweet()
        time.sleep(5)

if __name__ == '__main__':
    target = [[u'品川', 1852140], [u'船橋', '1863905'], [u'熊本', '1858421'], [u'宇治', '1849372']]
    jikan = datetime.datetime.now()
    flag = jikan.hour
    tag = jikan.microsecond

    for i in target:
        w = Weather3(oat.api_key, flag, i[0], i[1], tag)
        w.run()
token
#!/usr/bin/python
# -*- coding:UTF-8 -*-

from urllib import urlencode
from oauth2 import Client, Consumer, Token
import tweepy

#Twitter
consumer_key = "xxxxxx"
consumer_secret = "xxxxxxxxxxx"
user_key = "*****-xxxxxxxxxx"
user_secret = "xxxxxxxxx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(user_key, user_secret)
client = Client(Consumer(consumer_key, consumer_secret), Token(user_key, user_secret))
api = tweepy.API(auth)
ep = "https://api.twitter.com/1.1/statuses/update.json"

#OpenWeatherMap
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

def tweet(message):
    client.request(ep, 'POST', urlencode({'status': message}))


def reply(message, ids):
    client.request(ep, 'POST', urlencode({'status': message, 'in_reply_to_status_id': ids}))

動かした時間によって、今日の明日の天気とか取得した情報内の何番目の情報を使うかとかは使用方法によって様々になるかなと思います。なお、気温をケルビンから摂氏に変換するのに-273.15をべた書きしていますが、エンドポイント叩く時点でオプションを点けておけば摂氏で返ってくるらしいです。

twitter投稿サンプル画像
http://www.nowshika.com/joso/img11110131.png