LoginSignup
6
3

More than 1 year has passed since last update.

推しからおはようメッセージを受け取るBOTを作ったよ

Last updated at Posted at 2021-11-27

注釈

こちらに移動しました。

はじめに

python初学者です。
楽しくpythonを学習できる方法はないかと模索していると、bot開発が楽しそうなので試してみました。
どうせなら推しから毎朝、自動メッセージが送信されるように作成してみました!

#実行環境
python : 3.8
github actions

今回の環境は、自前でサーバを用意することなくサーバレスに実行できる構成です。

#ファイル

  • info.json
  • main.py

この2つだけ!

#ソースコード

main.py
import json
from linebot import LineBotApi
from linebot.models import TextSendMessage

file = open('info.json', 'r')
info = json.load(file)

CHANNEL_ACCESS_TOKEN = info['CHANNEL_ACCESS_TOKEN']
line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)

def main():
    USER_ID = info['USER_ID']
    messages = TextSendMessage(text="おはよう〜 みなみだよ❤︎ \n今日も1日頑張ろうね!")
    line_bot_api.push_message(USER_ID,messages=messages)

if __name__ == "__main__":
    main()
info.json
{
    "CHANNEL_ACCESS_TOKEN": "~~~~~~~~~",
    "USER_ID": "~~~~~~~~"
}

info.jsonに記載されている変数をmain.pyから参照しています。

Line-Developperでチャンネルを作成する方法は、こちら

チャンネル作成後に、
"CHANNEL_ACCESS_TOKEN"は、「Messaging API settings」タブから
"USER_ID"は、「Basic settings」タブからそれぞれ取得できます。

#githubへpush

$ git init
$ git remote add origin https://~~~.git
$ git add .
$ git commit -am "first commit"
$ git push origin maseter

#github action の設定

#####Actionsから設定を行います
スクリーンショット 2021-11-27 16.50.07.png

後続の作業とyamlファイルの記述方法は、下記youtubeを参考にさせていただきました。

実際のyamlファイルはこんな感じ


name: hello_chatbot

on:
#   push:
  schedule:
    - cron: '55 20 * * *'

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - name: Set up Python 3.8
        uses: actions/setup-python@v1
        with:
          python-version: 3.8
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install line-bot-sdk
      - name: Run script
        run: |
          # main.pyの実行
          python main.py

github actionsのcronの時刻はUTCらしいので、起動させたい時刻からマイナス9した値を設定する必要があります。
私の場合は、毎朝6時にメッセージを受け取りたいので、AM6:00から-9してPM9:00に設定していたのですが、
ビルドに時間がかかるのでさらに5分早めに起動させています。

  schedule:
    - cron: '55 20 * * *'

#完成
スクリーンショット 2021-11-27 17.07.10.png
最高やないかい!!!(キモいとか言わないで。)

6
3
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
6
3