蒼社川(片山)の水位と写真をTwitterに定時投稿

import datetime
import tempfile

import requests
import twitter
from apscheduler.schedulers.blocking import BlockingScheduler
from bs4 import BeautifulSoup


def scraping():

    url = 'http://183.176.244.72/cgi/050_HQ_100_03.cgi?GID=050_HQ_100&UI=U777&SI=00000&DT=000000000000&DBDT=0000000000&MNU=1&DTO=-1&DN=0972900400025&KTM=3&GHK=3&YSK=0&SRO=1&LO=88&TD=0000&BTY=IE6X&cSessionID=0000000000000000000000&UIS=000000000000&SIMU=0&ZM=0'

    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html5lib')

    result = []

    dt_now = datetime.datetime.now()

    for trs in soup.select('body > table > tbody > tr'):
        data = [i.get_text(strip=True) for i in trs.select('td.right-10')]

        # 日付補完
        if data[0]:
            cache = data[0]
        else:
            data[0] = cache

        # 日付
        m, d = map(int, data[0].split('/'))

        # 時間
        H, M = map(int, data[1].split(':'))

        # 日時
        dt_date = datetime.datetime(dt_now.year, m, d) + datetime.timedelta(
            hours=H, minutes=M)

        # 年をまたいだか
        if dt_date > dt_now:
            dt_date -= datetime.timedelta(years=1)

        # 小数点に変換、変換できない場合はスキップ
        try:
            water_level = float(data[2])
        except:
            pass
        else:
            result.append([dt_date, water_level])

    # 時間・現在の水位・直前の水位
    return (result[-1][0], result[-1][1], result[-2][1])


sched = BlockingScheduler()


@sched.scheduled_job('interval', minutes=10)
def river_job():

    wl_date, wl_now, wl_before = scraping()

    if wl_now > 2 or wl_before > 2:

        # 危険水位
        if wl_now >= 2.85:
            wl_alert = 'はん濫危険水位'
        elif wl_now >= 2.60:
            wl_alert = '避難判断水位'
        elif wl_now >= 2.40:
            wl_alert = 'はん濫注意水位'
        elif wl_now >= 2.10:
            wl_alert = '水防団待機水位'
        else:
            wl_alert = ''

        # 水位変化
        if wl_now > wl_before:
            wl_sign = '↗'
        elif wl_now < wl_before:
            wl_sign = '↘'
        else:
            wl_sign = '➡'

        twit = '{}現在\n蒼社川(片山)の水位は{}m{}{}です。'.format(
            wl_date.strftime('%Y/%m/%d %H:%M'), wl_now, wl_sign, wl_alert)

        res = requests.get(
            'http://www.pref.ehime.jp/kasen/Jpeg/Cam006/00_big.jpg')

        if res.status_code == requests.codes.ok:
            with tempfile.TemporaryFile() as fp:
                fp.write(res.content)
                fp.seek(0)
                fp.read()

                api = twitter.Api(
                    consumer_key='',
                    consumer_secret='',
                    access_token_key='',
                    access_token_secret='')

                print(twit)
                status = api.PostUpdate(twit, media=fp)


sched.start()