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.
-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 with LINE Dvelopers . After logging in, click Create at the bottom of the screen.
Then, the screen for entering the provider name will be displayed, so enter the name you like.
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.
A screen for entering the LINE Bot icon and name will appear, so enter it.
This completes the creation of LINE Bot.
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.
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 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 ...
Next, implement the function that Lambda executes.
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
A library called line-bot-sdk is used to operate LINE Bot.
$ pip3 install line-bot-sdk
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.
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.
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.
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.
The secret key is at the bottom of the channel preferences.
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 | ✖️✖️✖️✖️✖️✖️ |
You can check the URL issued by API Gateway by clicking the following, so let's take a look.
Enter the API Gateway URL in the webhook on the LINE Bot Messaging API settings screen. 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 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
If you click "View CloudWatch Log", you can see the log of the Lambda function, so please see it and debug it.
Recommended Posts