I made a LINE Bot with Serverless Framework!

What is Serverless Framework?

https___camo.githubusercontent.jpeg

Serverless Framework is a frame for configuring applications with FaaS (Function as a Service), cloud DB, and Storage. It is a work. In addition to AWS, it also supports GCP and Azure. Please refer to this article for the installation method.

Precautions

-Since the command is supposed to be Mac, I think that the setting method is different for Windows. ・ You cannot do this unless you have an AWS account. -Since it is too easy to set up Lambda and API Gateway, I think that those who are new to it will not understand much.

Create a LINE Bot

Create a LINE Bot with LINE Dvelopers . After logging in, click Create at the bottom of the screen. スクリーンショット 2020-11-04 12.49.01.png

Then, the screen for entering the provider name will be displayed, so enter the name you like. スクリーンショット 2020-11-04 12.53.55.png

You have now created a provider. Next, create a channel (LINE Bot). This time, we will create a LINE Bot that returns, so select the Messaging API. スクリーンショット 2020-11-04 12.55.23.png

A screen for entering the LINE Bot icon and name will appear, so enter it. スクリーンショット 2020-11-04 12.59.58.png

This completes the creation of LINE Bot.

System configuration

The system we create this time feels like the Lambda function is executed by the webhook when the user sends a message to the LINE Bot. The part enclosed in red is implemented by Serverless Framework. スクリーンショット 2020-11-04 13.08.13.png

Associate your AWS account with your PC

Use AWS-CLI to set AWS information on your PC. Refer to this article

Let's Serverless After installing Serverless Framework on your PC, change to your working directory in the terminal and execute the following command. The --template option specifies the programming language used by Lambda, and the --path option specifies the project name and project location. Please change accordingly.

$ serverless create --template aws-python3 --path line-bot

When you execute the command, a project will be created with the following directory structure.

line-bot
    ├ .gitignore
    ├ handler.py
    └ serverless.yml

Rewrite serverless.yml

Rewrite serverless.yml as follows.

serverless.yml


service: line-bot
frameworkVersion: '2'

provider:
  name: aws
  runtime: python3.8
  region: ap-northeast-1  #Specify the Tokyo region

#Lambda function settings
functions:
  callback:
    handler: handler.callback

    #API Gateway settings
    events:
      - http:
          path: callback
          method: post

This completes the API Gateway and Lambda settings. It's too easy ...

Implement Lambda function

Next, implement the function that Lambda executes.

Create a Python virtual environment

Since it is Python, first create a virtual environment. I create a virtual environment with venv, but I think there are people who create it with conda or virtualenv, so please change that as appropriate.

$ python3 -m venv line-bot

Doing this will create a directory called line-bot.

line-bot
    ├ line-bot/  <--Virtual environment directory
    ├ .gitignore
    ├ handler.py
    └ serverless.yml

Once generated, activate it with the following command.

$ source line-bot/bin/activate

Library used for LINE Bot

A library called line-bot-sdk is used to operate LINE Bot.

$ pip3 install line-bot-sdk

Implemented in handler.py

Now that you're ready, let's actually write the code.

handler.py


from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, ImageMessage
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot import (
    LineBotApi, WebhookHandler
)
import os

access_token = os.environ['LINE_CHANNEL_ACCESS_TOKEN']  //Get from Lambda environment variables
secret_key = os.environ['LINE_CHANNEL_SECRET']          //Get from Lambda environment variables

line_bot_api = LineBotApi(access_token)
handler = WebhookHandler(secret_key)

//Functions executed by LINE Bot webhooks
def callback(event, context):
    try:
        signature = event["headers"]["x-line-signature"]
        event_body = event["body"]
        handler.handle(event_body, signature)
    except InvalidSignatureError as e:
        logger.error(e)
        return {"statusCode": 403, "body": "Invalid signature. Please check your channel access token/channel secret."}
    except Exception as e:
        logger.error(e)
        return {"statusCode": 500, "body": "exception error"}
    return {"statusCode": 200, "body": "request OK"}

//Echolalia function
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text)
    )

This completes the implementation of the Lambda function.

Output requirements.txt

Prints a list of libraries used by Lambda's Python. Execute the following command in the activated state.

$ pip3 freeze > requirements.txt

When you deploy the library listed in requirements.txt, add the plugin to the Serverless Framework to have Lambda install it.

$ npm install --save serverless-python-requirements

The library you are using locally is now available on Lambda.

Deploy for the time being

At this point, let's deploy once You can deploy with the following command. sls is an abbreviation for serverless.

$ sls deploy

After doing this, let's go to the AWS console screen and see Lambda in the Tokyo region. Then you can see that it is actually deployed.

Go see the LINE Bot access token and secret key

In order to execute the implemented Lambda function, you will need the access token and secret key of the LINE Bot, so look at it on the console screen of LINE Developers.

The access token is at the bottom of the Messaging API settings. スクリーンショット 2020-11-04 14.40.37.png

The secret key is at the bottom of the channel preferences. スクリーンショット 2020-11-04 14.38.04.png

Set environment variables in Lambda

Set the value you saw above in your Lambda environment variable. There is a place where you can set environment variables at the bottom of this screen, so save it like this.

Key value
LINE_CHANNEL_ACCESS_TOKEN ✖️✖️✖️✖️✖️✖️
LINE_CHANNEL_SECRET ✖️✖️✖️✖️✖️✖️

スクリーンショット 2020-11-04 14.30.44.png

View API Gateway URL

You can check the URL issued by API Gateway by clicking the following, so let's take a look. スクリーンショット 2020-11-04 14.30.44.png

Set the URL of the Lambda function in the LINE Bot webhook

Enter the API Gateway URL in the webhook on the LINE Bot Messaging API settings screen. スクリーンショット 2020-11-04 14.48.12.png After inputting, click the verification button, and when the success screen is displayed, it is finished. I think that the QR code of LINE Bot is displayed at the top, so if you add a friend from there, you can play with Echolalia Bot.

If it gets stuck

If you click the above verification and a response error is displayed, I think that there is an error in the Lambda function, so from the following monitoring スクリーンショット 2020-11-04 14.28.54.png

If you click "View CloudWatch Log", you can see the log of the Lambda function, so please see it and debug it. スクリーンショット 2020-11-04 15.03.52.png

Recommended Posts

I made a LINE Bot with Serverless Framework!
I made a stamp substitute bot with line
[AWS] I made a reminder BOT with LINE WORKS
I made a household account book bot with LINE Bot
I made a LINE BOT with Python and Heroku
I made a LINE BOT that returns parrots with Go
[AWS] I made a reminder BOT with LINE WORKS (implementation)
Serverless LINE bot made with IBM Cloud Functions
I made a Mattermost bot with Python (+ Flask)
I made a discord bot
I made a Twitter BOT with GAE (python) (with a reference)
I made a wikipedia gacha bot
I made a fortune with Python.
I made a daemon with Python
Until I return something with a line bot in Django!
I made a character counter with Python
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a WEB application with Django
I made a neuron simulator with Python
[Python] I made a Line bot that randomly asks English words.
I made a Twitter Bot with Go x Qiita API x Lambda
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
〇✕ I made a game
Create a LINE BOT with Minette for Python
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I made a simple Bitcoin wallet with pycoin
Make a LINE WORKS bot with Amazon Lex
I made a random number graph with Numpy
I made a bin picking game with Python
I made a QR code image with CuteR
I made a LINE BOT that returns a terrorist image using the Flickr API
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I made a LINE Bot that sends recommended images every day on time
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
Decision support system for elderly people made with LINE Messaging API + Serverless Framework
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
In Python, I made a LINE Bot that sends pollen information from location information.
Make a morphological analysis bot loosely with LINE + Flask
I made a ready-to-use syslog server with Play with Docker
I made a Christmas tree lighting game with Python
I made a window for Log output with Tkinter
I made a Python3 environment on Ubuntu with direnv.
[Valentine special project] I made a LINE compatibility diagnosis!
[Super easy] Let's make a LINE BOT with Python.
I made a falling block game with Sense HAT
I made blackjack with python!
I made a python text
I made COVID19_simulator with JupyterLab
I made Word2Vec with Pytorch
I made blackjack with Python.
I made wordcloud with Python.
A story that stumbled when I made a chatbot with Transformer
I made a simple typing game with tkinter in Python
Make a LINE bot with GoogleAppEngine / py. Simple naked version
Create a machine learning app with ABEJA Platform + LINE Bot