Let's make a LINE bot using various services [ngrok edition]

Overview

This is a series of trying to create a backend for LINEbot using various services. The first one uses ngrok. Also, for this article only, we will include procedures such as registration with LINE Developers as an introduction.

Please refer to the following for building using other services.

--First: ngrok * This article --Second: Heroku --Third: Google Cloud Functions * Updated soon --Fourth: Google Cloud Run --Fifth: Google Kubernetes Engine --Sixth: AWS Lambda (planned)

Premise

--I have a LINE account --Python is ready to be executed locally

Overall picture

linebot_1-webhook.png

LINE Developers preparation

It is a capture procedure as of 2020/10. Please note that changes may occur in the future.

Login

To use the Messaging API, first register for an account with LINE Developers. First, access here and press the login button on the upper right. On the next screen, press "Login with LINE account". Then, the following screen will be displayed. Log in by either entering the e-mail address and password registered in LINE or scanning the QR code. If successful, you will be taken to the console home screen. ログイン

Channel creation

There is a section called Providers on the home screen, so click the" Create "button next to it and enter an arbitrary name in the Provider name field.

The screen will change to the Provider home screen, so click the "Create a Messaging API Channel" block.

Provider

The screen will change to the information input screen, so enter the following (only the minimum required items are listed).

--Channel icon: The icon is not essential, but the white icon is lonely, so I want to set it because anything is fine. --Channel name: Channel name, any name is OK --Channel description: Channel description, "LINE Bot practice", etc. are OK --Category: Channel category, "Individual" if you have any problems --Subcategory: Channel subcategory, "Individual (Other)" if you have any problems --Check the agreement link at the bottom and check the check boxes (2 places)

Issuance of Channel Secret and Channel Access Token

Since it will be used in the back end, it will be issued at this stage. In addition, please keep these two values carefully so that they will not be known to others.

The string in the Channel secret part of the Basic settings tab. This is published when the channel is created.

Secret

The string for the Channel access token part at the bottom of the Messaging API tab. This is not published by default, so let's generate it by pressing the "Issue" button.

Token

Register as a friend

There is a QR code on the Messaging API tab, so scan it with the LINE app and register as a friend.

Build a backend server

Source code

Copy the code for line-bot-sdk-python and save it locally as ʻapp.py` .. Then, set the secret information as follows.

--Replace the part (L16) where YOUR_CHANNEL_SECRET is written with the character string obtained by Channel secret. --Replace the part (L15) where YOUR_CHANNEL_ACCESS_TOKEN is written with the character string obtained by Channel access token.

app.py


#Example
line_bot_api = LineBotApi('YXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXZGG==') #This is the longer string
handler = WebhookHandler('fxxxxxxxxxxxxxxxxxxxxx')

Library installation

Since the source code uses the library, it is necessary to install the library. Run the following command in the terminal:

Terminal


pip install Flask line-bot-sdk

ngrok installation

ngrok is a service that allows you to access locally started processes from the outside via the Internet. Above all, the point that a public endpoint on https is prepared is very big. (Webhook URL must be https)

For MacOS, we recommend installing with the first Homebrew. Other than that, install it with the second command.

For MacOS

Terminal


brew cask install ngrok

In other cases

Terminal


wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
unzip ngrok-stable-linux-amd64.zip
mv ngrok /usr/local/bin/ngrok

Installation confirmation

Make sure it is installed correctly. If you execute the ngrok command and the following message is displayed, there is no problem. Enter Ctrl + C to stop.

Terminal


ngrok http 80

Execution result

Terminal


ngrok by @inconshreveable                                                                                                                                                                          (Ctrl+C to quit)
                                                                                                                                                                                                                   
Session Status                online                                                                                                                                                                               
Session Expires               7 hours, 59 minutes                                                                                                                                                                  
Version                       2.3.35                                                                                                                                                                               
Region                        United States (us)                                                                                                                                                                   
Web Interface                 http://127.0.0.1:4040                                                                                                                                                                
Forwarding                    http://a9e65703bdfa.ngrok.io -> http://localhost:80                                                                                                                                  
Forwarding                    https://a9e65703bdfa.ngrok.io -> http://localhost:80                                                                                                                                 
                                                                                                                                                                                                                   
Connections                   ttl     opn     rt1     rt5     p50     p90                                                                                                                                          
                              0       0       0.00    0.00    0.00    0.00 

Echolalia

Now, let's start the server and see where the message is returned.

Start backend server

Execute the following command in the terminal. If the Python file name is not ʻapp.py, you need to set the environment variable FLASK_APP` to that file name.

Terminal


flask run --reload --port 8080

#If the following is displayed, the startup status
* Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)

The figure below shows the current state.

linebot_1-local.png

External disclosure of server

Start another terminal and execute the following command. Then copy the URL that starts with https on the line that says Forwarding.

Terminal


ngrok http 8080

Forwarding    http://e5e58099a87e.ngrok.io -> http://localhost:8080                     
Forwarding    https://e5e58099a87e.ngrok.io -> http://localhost:8080 #here

The figure below shows the current state.

linebot_1-ngrok.png

Webhook URL settings

At this point, you will return to the LINE Developers screen. On the Messaging API tab, in the Webhook URL part, enter "** URL ** + / callback you copied earlier.

Webhook

Also, move to the response setting screen from the Edit button in the above image, and set as follows.

--Response message: OFF

Now when you send a message to LINE, the request will fly to the locally running server via the ngrok endpoint.

linebot_1-webhook.png

send a message

Let's actually send a message with the bot registered as a friend. If you get the same message, you're successful! !!

important point

ngrok issues a different endpoint each time you start it, so if you quit it and then start it again, you'll need to modify the LINE Developers webhook URL as well.

Step up

I have omitted the explanation of the source code, but the sdk source code only returns a text message parrot. The following two examples of changing the behavior as a step-up are described as issues, so please try it if you like.

1. Always reply "Thank you for your message!"

Answer

The value specified by text of the handle_message function will be the content of the reply. In the original source, ʻevent.message.text was set, and since this ʻevent.message.text is the content of the message sent by us, it was a parrot return. In other words, just set text to" Thank you for your message! ".

app.py


def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
-        TextSendMessage(text=event.message.text))
+        TextSendMessage(text='thank you for the message!'))

2. When you send a stamp, make sure to reply "It's a cute stamp"

Answer

The reason why only text messages are handled is that the decorator of @ handler.add (MessageEvent, message = TextMessage) tells the WebhookHandler that" When a TextMessage type message event comes, the handle_message function is processed. This is because we are doing it. You can add a function to handle the event of stamp type (StickerMessage) in the same way.

app.py


+ @handler.add(MessageEvent, message=StickerMessage)
+ def handle_sticker_message(event):
+     line_bot_api.reply_message(
+         event.reply_token,
+         TextSendMessage(text='It's a cute stamp'))

See API Specifications to see what other event types and message types are available.

in conclusion

I think it is very good that you can easily check the operation locally. However, it is a mess to have to start it locally all the time, or to reset the Webhook URL every time it starts. This kind of mentality can be solved by starting the server using a cloud service, so I would like to touch on it from the next time onwards.

Recommended Posts

Let's make a LINE bot using various services [ngrok edition]
Let's make a Discord Bot.
[For play] Let's make Yubaba a LINE Bot (Python)
[Super easy] Let's make a LINE BOT with Python.
Let's make a multilingual site using flask-babel
Let's make a Twitter Bot with Python!
Make a LINE WORKS bot with Amazon Lex
Let's make a module for Python using SWIG
Make LINE BOT (Echolalia)
Let's make a spot sale service 9 (Task Queue edition)
Make a morphological analysis bot loosely with LINE + Flask
Let's make a spot sale service 8 (image uploader edition)
Let's easily make a math gif using Google Colaboratory
Make a LINE bot with GoogleAppEngine / py. Simple naked version
Let's make a rock-paper-scissors game
Let's make a web chat using WebSocket with AWS serverless (Python)!
Let's make a remote rumba [Hardware]
[Python] Make your own LINE bot
Let's make a remote rumba [Software]
Let's make a GUI with python.
Let's make a spot sale service 2
Make a face recognizer using TensorFlow
How to make a slack bot
Let's make a breakout with wxPython
Let's make a spot sale service 1
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Let's make a spot sale service 3
Create a LINE Bot in Django
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
Hanashi who became a read through BOT when trying to make a morphological analysis BOT using the popular LINE BOT API
Knowledge when making a bot using discord.py
Creating a LINE bot ~ Creating, deploying, and launching ~
I tried drawing a line using turtle
Let's make a voice slowly with Python
[Python] [LINE Bot] Create a parrot return LINE Bot
Let's make a web framework with Python! (1)
Let's make a combination calculation in Python
Let's make a web framework with Python! (2)
Let's make a Backend plugin for Errbot
I made a LINE BOT that returns a terrorist image using the Flickr API
Creating a LINE BOT to notify you of additional AtCoder contests using AWS
I tried to make a translation BOT that works on Discord using googletrans
If you want to make a discord bot with python, let's use a framework