[PYTHON] Decision support system for elderly people made with LINE Messaging API + Serverless Framework

This article is the 8th day article of Senior Maru Advent Calendar.

Hello everyone. If you notice it, how are you doing nowadays when you become an elderly person and you are about to end this trouble? By the way, speaking of elderly people, they are in their 40s. Speaking of 40, Confucius-sama is said to be "forty years old" in the analects, and it is also called "unpleasant". But times have changed (maybe). Even though I'm in my 40s, I'm still at a loss. For that reason, the judgment speed is slowing down and I am in trouble.

Here, we will deliver a wonderful decision support system to you! (Long assumption)

1. Configuration

Consider the overall configuration. After all, let's make it with LINE Bot using the LINE Messaging API that was just released in October 2016 due to the trend. Even if you say elders, you have LINE on your smartphone, right? If you don't have it, download it now. I don't want to spend money on the backend, so let's get on the trend and use AWS Lambda (python). And since it's a big deal, let's make it with Severless Framework.

2. Register with LINE's Developer Trial to create a bot

Register your account from "Start Developer Trial" in LINE BUSINESS CENTER. After registering, go to "Account List" on the login screen and go to "Create Business Account". The service selection screen will appear, so select "Messaging API". Here, I created the account name with "Senior Maru". The type of business may be appropriate, but I chose "individual (fictitious person)" here. syorou-1.jpg

After registration is complete, proceed to "LINE @ MANAGER". We will set up a bot account here, but first let's enable the API. syorou-2.jpg

Then enable "Send Webhook". Also, set "Automatic response message" to "Do not use". syorou-5.jpg

When you're done, press "Set up with LINE Developers" from the "Bot Settings" screen to go to the "LINE Developers" page.

Press the "ISSUE" button next to the Channnel Access Token to pay out the token and make a note of the token and Channel Secret.

For the time being, the preparations are now complete.

3. Preparation of Serverless Framework

Install with the npm command. Install npm properly as yum.

#sudo npm install serverless -g

Let's check if it is installed normally.

#sls --help

Commands
* Serverless documentation: http://docs.serverless.com
* You can run commands with "serverless" or the shortcut "sls"
* Pass "--help" after any <command> for contextual help

config credentials ............ Configures a new provider profile for the Serverless Framework
create ........................ Create new Serverless service
install ....................... Install a Serverless service from GitHub
deploy ........................ Deploy a Serverless service
deploy function ............... Deploy a single function from the service
deploy list ................... List deployed version of your Serverless Service
invoke ........................ Invoke a deployed function
invoke local .................. Invoke function locally
info .......................... Display information about the service
logs .......................... Output the logs of a deployed function
metrics ....................... Show metrics for a specific function
remove ........................ Remove Serverless service and all resources
rollback ...................... Rollback the Serverless service to a specific deployment
slstats ....................... Enable or disable stats

Plugins
AwsConfigCredentials, Config, Create, Deploy, Info, Install, Invoke, Logs, Metrics, Package, Remove, Rollback, SlStats

If the help is displayed as above, it is successful. "Sls" is a short alias for the serverless command. This article has been confirmed to work with npm 3.9.2 and serverless 1.3.0 on FreeBSD 11.0.

4. Coding

4.1 Creating a project

First, create a serverless project.

#mkdir line-syorou
#cd line-syorou
#sls create -t aws-python

Specify the template with -t. Since AWS Lambda (python) is used here, "aws-python" is specified.

This will create two files in the current directory, "handler.py" and "serverless.yml". hapdler.py is the program itself and serverless.yml is the configuration file. It's very simple!

4.2 Settings

Set serverless.yml. There is almost no place to rewrite this time. When HTTP GET and HTTP POST come to https: // XXXXXXXX / syorou, let's call the function called syorou in handler.py. Please rewrite only the following places.

functions:
  syorou:
    handler: handler.hello
    events:
      - http:
           path: syorou
           method: get
      - http:
           path: syorou
           method: post

4.3 Installation of official SKD

There is an official LINE python SDK, so install it.

line-bot-sdk-python

#pip install line-bot-sdk -t ./

The installed SDK needs to be zipped together when deploying to Lambda, so use the "-t" option to install it in the current directory.

4.4 Write code

Write the code in handler.py. Save the file in UTF-8.

If you write according to Official document, there is nothing particularly difficult, but as a flow

--Verify and parse the request using the X-Line-Signature header information as well as the channel secret --In the request header, the events (Message / Join, etc.) that occurred in the array "Events" are included. This time, I want to reply to the writing from the user, so I will target the Message Event. --Retrieve reply_token. --Reply according to the content. Create a TextMessage object and specify the destination with reply_token obtained earlier.

It will be.

# coding: utf-8
import json
import random
from linebot import (
    LineBotApi, WebhookHandler, WebhookParser
)
from linebot.exceptions import (
    InvalidSignatureError,LineBotApiError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,TemplateSendMessage,ButtonsTemplate,URITemplateAction,LocationSendMessage
)

def syorou(oevent, context):

    #Request body and X-LINE-Extract Signature header
    body = oevent['body']
    signature = oevent['headers']['X-Line-Signature']

    #Use Channel Secret to check if the input is correct
    secret = 'The channel secret I noted earlier'
    parser = WebhookParser(secret)

    try:
        events = parser.parse(body,signature)
    except InvalidSignatureError:
        return {"stautsCode" : 400,"body" : ""};

    #Create a LineBot API object
    token = 'The token I noted earlier'
    line_bot_api = LineBotApi(token)
    
    try:
        events = parser.parse(body,signature)
    except InvalidSignatureError:
        return {"stautsCode" : 400,"body" : ""};

    for event in events:
        if event.type == 'message':
            reply_token = event.reply_token
            if random.randint(0,1) == 0:
                message = TextSendMessage(
                    text=u"Go GOGO!"
                )
            else:
                message = TextSendMessage(
                    text=u"Well, let's stop..."
                )
                
            try:
                line_bot_api.reply_message(reply_token,message)
            except LineBotApiError as e:
                print(e.status_code)
                print(e.error.message)
                print(e.error.details)

    return {"stautsCode" : 200,"body" : "OK"};
            

5. Let's move

5.1 Deploy

Deploy to Lambda. To deploy, the aws credential must be set, so set it appropriately. Write it in ~ / .aws / credentials or set an environment variable.

#sls deploy
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading service .zip file to S3 (2.26 MB)...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.................................
Serverless: Stack update finished...

Service Information
service: aws-python
stage: dev
region: us-east-1
api keys:
  None
endpoints:
  GET - https://*****us-east-1.amazonaws.com/dev/syorou
  POST - https://******us-east-1.amazonaws.com/dev/syorou
functions:
  aws-python-dev-syorou: arn:aws:lambda:us-east-1:********:function:aws-python-dev-syorou

If successful, the endpoint will be displayed like this, so set this to the Webhook URL from the LINE Developers page earlier.

5.2 Let's talk

There is a QR code for registering the bot you made this time in "Account Settings" on the LINE @ MANAGER page earlier, so read this from the LINE app and make friends.

And let's talk about what you are worried about now.

syorou-4.png

Your worries have been resolved safely! : v:

Summary

So, I tried to build a chatbot using LINE Messaging API on AWS Lambda using Serverless Framework. It's very easy to use both, so please give it a try. In addition, we are not responsible for any serious accidents that occur according to the instructions of this chatbot, so please take responsibility for that: stuck_out_tongue:

You can apply for friends to this bot from the QR code below, but it is unknown how long it will work as it can only register up to 64 people, so I'm sorry if you can not connect. After trying it all out, I would appreciate it if you could unfriend it for the next person.

QRコード

Recommended Posts

Decision support system for elderly people made with LINE Messaging API + Serverless Framework
I made a LINE Bot with Serverless Framework!
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
Serverless face recognition API made with Python
Serverless LINE bot made with IBM Cloud Functions
[LINE Messaging API] Create parrot return BOT with Python
Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)
I made a Chatbot using LINE Messaging API and Python