Send a push message to the LINE Bot when the LTE-M Button is pressed [SORACOM]

Introduction

This article is the second chapter of a four-chapter article.

  1. We made a system that "not only" watches over elderly houses by making full use of IoT [SORACOM Summer Challenge 2020]
  2. Send a push message to the LINE Bot when the LTE-M Button is pressed [SORACOM]: arrow_backward: Now here
  3. [Raspberry Pi] When the motion sensor detects it, store the timestamp in the Firebase Realtime Database
  4. Link SORACOM with home appliances and LINE Bot [Python / Flask / Raspberry Pi] ** All sources released **

Trigger

It is assumed that the LTE-M Button is pressed when something happens to an elderly parent who lives away. There is a function to notify LINE Notify from SORACOM Lagoon, but I decided to make a LINE Bot because I can not select the action after the notification comes only by text message. It's nice to have a simple mechanism with only one button like this, because even elderly people who are not good at machines can see it visually. LTE-M Button

Operating environment

Raspberry Pi 3 Model B Python 3.7.3 Flask==1.1.2 line-bot-sdk==1.16.0

Until LTE-M Button and LINE Bot are linked

① Send an alert from SORACOM Lagoon

For specific usage, the official Create a dashboard using SORACOM Lagoon and [Alert using SORACOM Lagoon] Since it is described in detail in Setting, I will omit it.

LTE-M Button sends Int type data such as 1 for 1 click, 2 for double click, and 3 for long press. Since this is an emergency, I don't know what kind of button operation will be performed. Therefore, we decided to send an alert when the value is 0.5 or more (all button operations) (see image).

Also, select Webhook for the notification channel. The URL will be set later, so for now, just use https: //test.example.

② Register LINE Bot

Create a new Channel from LINE Developers. In "Choose a channel type to continue", use the Messaging API. Make a note of the Channel secret in the Basic settings and the Channel access token in the Messaging API for later use.

③ Use Raspberry Pi as a server

Run Flask on your Raspberry Pi to receive webhooks and return messages. For various settings, [Try making a LINE BOT with Python / Raspberry Pi! ](Try making a LINE BOT with Python / Raspberry Pi!).

important point

You can ignore the settings of the above site and pyenv-virtualenv, but be sure to rewrite other .bash_profile etc. Otherwise it won't work. Also, please set the Channel secret and Channel access token in the environment variables as described in the above site.

④ Send a Push message

You need to know ʻuserId to send a Push message. This ʻuserId is different from the ID used when adding a friend, which is set arbitrarily by the individual, so it is necessary to know it by another method. If you use the following code, sending a text message will return ʻuserId`.

line_bot.py


from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import os

app = Flask(__name__)

LINE_BOT_ACCESS_TOKEN = os.environ["LINE_BOT_ACCESS_TOKEN"]
LINE_BOT_CHANNEL_SECRET = os.environ["LINE_BOT_CHANNEL_SECRET"]

line_bot_api = LineBotApi(LINE_BOT_ACCESS_TOKEN)
handler = WebhookHandler(LINE_BOT_CHANNEL_SECRET)

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    
    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    profile = line_bot_api.get_profile(event.source.user_id)
    messages = str(profile.user_id)
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=messages))

if __name__ == "__main__":
    port = int(os.getenv("PORT", 6000))
    app.run(host="0.0.0.0", port=port)

If you can set it properly, you should get an ID starting with U like this.

If you can do so far, it is finally cooperation with SORACOM Lagoon. I'll add a little to the code above. Allows you to send a Push message to the user when there is a POST in the / webhook. Please note that ʻimport` is also added.

line_bot.py


from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import os
import json  #add to

app = Flask(__name__)

LINE_BOT_ACCESS_TOKEN = os.environ["LINE_BOT_ACCESS_TOKEN"]
LINE_BOT_CHANNEL_SECRET = os.environ["LINE_BOT_CHANNEL_SECRET"]

line_bot_api = LineBotApi(LINE_BOT_ACCESS_TOKEN)
handler = WebhookHandler(LINE_BOT_CHANNEL_SECRET)

#Added below
@app.route("/webhook", methods=['POST'])
def webhook():
    print(json.dumps(request.get_json(), indent=2))
    object = request.get_json()
    if object['title'] == "[Alerting] Emergency alert":
        user_id = "U03xxxxxx(The userId obtained earlier)"
        messages = TextSendMessage(text="I got an alert")
        line_bot_api.push_message(user_id, messages=messages)

    return request.get_data()
#So far

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    
    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    profile = line_bot_api.get_profile(event.source.user_id)
    messages = str(profile.user_id)
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=messages))

if __name__ == "__main__":
    port = int(os.getenv("PORT", 6000))
    app.run(host="0.0.0.0", port=port)

Finally, set the notification channel of SORACOM Lagoon. Enter the URL of the ngrok running on the Raspberry Pi and add / webhook to the end. This will allow you to receive webhooks from Lagoon.

Demo video

[YouTube] SORACOM LTE-M Button will notify LINE The reaction is faster than expected! With this, you can act as quickly as one second in an emergency.

Recommended Posts

Send a push message to the LINE Bot when the LTE-M Button is pressed [SORACOM]
I want to send a message from Python to LINE Bot
Send a message to LINE with Python (LINE Notify)
How to send a message to LINE with curl
[LINE Messaging API] I want to send a message from the program to everyone's LINE
How to install NPI + send a message to line with python
What to do when a warning message is displayed in pip list
Send a message from Python to Slack
Hanashi who became a read through BOT when trying to make a morphological analysis BOT using the popular LINE BOT API
Send a direct love email to a new user when a new user joins the Slack team
Send a message from Slack to a Python server
[Python] Throw a message to the slack channel
A command to check when something goes wrong when the server is not doing anything
The world's most easy-to-understand explanation of how to make a LINE BOT (1) [Account preparation]
The easiest line bot in the world to lose weight
Creating a list when the nomenclature is a fixed time
Send a message from the server to your Chrome extension using Google Cloud Messaging for Chrome
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to make an interactive LINE BOT 004 (answer the closing date of a listed company)