LoginSignup
0
1

LINE Notifyでごみの日を通知するプログラムを作ってみた

Posted at

通知プログラムを作成する

以下のプログラムを実装します。

  • ごみの日を判定する処理
  • LINE Notifyに命令を投げる処理
notify_trash_day.py
import datetime
import requests
from calendar import Calendar

def numOfWeek(target_day: datetime.date) ->int :
  """第何回目の曜日なのかを取得する

  Args:
      today (datetime.date): 対象の日付

  Returns:
      int: 第何回目
  """
  return (target_day.day-1)//7 + 1

def send(message: str):
  """LINE Notifyでメッセージを通知する

  Args:
      message (str): メッセージ
  """
  url = "https://notify-api.line.me/api/notify"
  #公開用のトークルーム: 
  access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # <----ここにAPIキーを入力
  headers = {'Authorization': 'Bearer ' + access_token}
  payload = {'message': message}
  requests.post(url, headers = headers, params = payload)

def garbage_day(target_day: datetime.datetime) -> str:
  """対象の日時のごみの種類を取得する

  Args:
      target_day (datetime.datetime): 対象の日時

  Returns:
      str: ごみの種類
  """
  # 曜日を取得
  weekday = target_day.weekday()
  # 第何回目の曜日なのかを取得
  week_num = numOfWeek(target_day)

  if weekday == 1 or weekday == 4:#1:火曜、4:金曜
    return '生活ごみ'
  elif (weekday == 0) and ((week_num == 2) or (week_num == 4)):#0:月曜、2・4回目
    return '缶・ビン'
  elif (weekday == 0) and (week_num == 1):#0:月曜、1回目
    return '紙・ペットボトル'
  elif (weekday == 0) and (week_num == 3):#0:月曜、3回目
    return 'ペットボトル'
  elif weekday == 3:#3:木曜
    return 'プラ容器包装'
  elif (weekday == 5) and (week_num == 3):#5:土曜、3回目
    return '小型金属・スプレー缶'
  else:
    return 'なし'

if __name__ == "__main__":
  notify_message_list = []

  # 本日のごみの種類を取得
  today_garbage_type = garbage_day(datetime.datetime.today())
  if today_garbage_type == 'なし':
    notify_message_list.append("今日はごみの日、なし")
  else:
    notify_message_list.append("今日は" + today_garbage_type + "の日")

  # 明日のごみの種類を取得
  tomorrow_garbage_type = garbage_day(datetime.datetime.today() + datetime.timedelta(days=1))    
  if tomorrow_garbage_type == 'なし':
    notify_message_list.append("明日はごみの日、なし")
  else:
    notify_message_list.append("明日は" + tomorrow_garbage_type + "の日")

  # ごみの種類のメッセージをLINE Notifyで通知
  notify_message_list[0] = "\n" + notify_message_list[0]
  notify_message = "\n".join(notify_message_list)
  send(notify_message)

プログラムを実行するサーバを用意する

おすすめはラズベリーパイです。
小さいプログラムを定期実行させるためだけなら、ラズパイで事足ります。
標準でPythonがインストールされていますし、amazonで探せば約2万円くらいでセット購入できます。

プログラムをを定期実行するように設定する

crontabコマンド(Windowsでいうタイムスケジューラみたいな機能)を使います。

エディタを起動

# Linux初心者におすすめのエディタはnano
crontab -e

時間を設定する

毎日6時と18時に実行したい場合は以下のように行を追加します。
空白は半角スペースで入力しないと実行されません。
通知プログラムは/home/test/notify_trash_day.pyにある想定です。

0 6 * * * python /home/test/notify_trash_day.py
0 18 * * * python ./home/test/notify_trash_day.py

実行イメージ

実行されたらこんな感じに表示されます。
トークルームにLINE Notifyユーザを追加するのをお忘れなく
image.png

0
1
0

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
0
1