A memo to make a LINE Bot that returns parrots using SAM Local
on AWS Cloud9
I will make this.
-[LINE Developers] Create provider -[LINE Developers] Set a channel for the created provider -[LINE Developers] Get two pieces of information on the created channel --Channel access token --Channel secret -[AWS] Prepare Cloud9 environment (Tokyo region: ap-northeast-1) -[AWS-Cloud9] Create Lambda - Function name - Application name -[AWS] Lambda script update -[AWS] Set environment variables in Lambda --LINE_CHANNEL_SECRET (Channel Secret) --LINE_CHANNEL_ACCESS_TOKEN (Channel access token) --[AWS] Confirm API Gateway URL call -[LINE Developers] Updated channel settings --Webhook URL (← API Gateway URL call) --Use of Webhook disabled-> enabled --Response message valid-> invalid
-LINE Messaging API x AWS Lambda simple response system # 2-appx1: Signature verification ――I mainly referred to the Lambda script.
Create a provider in LINE Developers.
Set up a channel for the provider you just created.
Select the Messaging API.
Get channel secret and channel access token information.
Channel secret information
Click the Publish button for channel access token information.
In the AWS console, create Cloud9. Created in the Tokyo region (ap-northeast-1).
Create a Lambda using SAM Local. Click λ
->λ +
on the right side of Cloud9 to create a new one.
Set an arbitrary character string in the red frame field and click the Next
button
I chose Python.
Create API Gateway as a whole.
I made it the default setting.
Click the Finish
button to start creating.
When the creation is completed, you will see a screen like this.
You can see the AWS resources you've created so far in the CloudFormation stack. Two stacks are created, the first stack (aws-cluod9-xxx) is the stack when Cloud9 was created, and the next stack (cloud9-app1) is the stack when Lambda was created.
You can see the AWS resources created on the Resources tab of the stack when you created Lambda.
Delete all existing Lambda scripts and copy the following script.
Lambda script
#Environment variable
# LINE_CHANNEL_SECRET channel secret
# LINE_CHANNEL_ACCESS_TOKEN channel access token
import json
import os
import logging
import urllib.request
import base64
import hashlib
import hmac
#Preparing for log output
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
#Log output of request contents
logger.info(event)
###
#Get the LINE channel secret from an environment variable
channel_secret = os.environ['LINE_CHANNEL_SECRET']
#HMAC with LINE channel secret as key-Calculate the hash value of the request body using the SHA256 algorithm
hash = hmac.new(channel_secret.encode('utf-8'), event['body'].encode('utf-8'), hashlib.sha256).digest()
#Base64-encoded hash value
signature = base64.b64encode(hash)
# X-Line-Get Signature
xLineSignature = event['headers']['X-Line-Signature'].encode('utf-8')
#Verify signature match and log output if there is a mismatch
if xLineSignature != signature:
logger.info('Signature mismatch')
return {
'statusCode': 200,
'body': json.dumps('It looks like the signature is incorrect.')
}
###
# 1.Extract the contents of the webhook event
body = json.loads(event['body'])
for event in body['events']:
#Define a list of message objects for response
messages = []
# 2.Webhook event type is message
if event['type'] == 'message':
# 3.If the message type is text
if event['message']['type'] == 'text':
# 4.Use the content of the received text as a message object
messages.append({
'type': 'text',
'text': event['message']['text']
})
#Define request information for response messages
url = 'https://api.line.me/v2/bot/message/reply'
headers = {
'Content-Type': 'application/json',
#Get a LINE channel access token from an environment variable
'Authorization': 'Bearer ' + os.environ['LINE_CHANNEL_ACCESS_TOKEN']
}
data = {
#Set response token and message object
'replyToken': event['replyToken'],
'messages': messages
}
request = urllib.request.Request(url, data = json.dumps(data).encode('utf-8'), method = 'POST', headers = headers)
with urllib.request.urlopen(request) as response:
#Log output of response contents
logger.info(response.read().decode("utf-8"))
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
After updating the lambda script, deploy it with the deploy button (up arrow icon).
Open Lambda in the AWS console and set the channel secret
and channel access token
of the channel you created in LINE Developers as environment variables.
ʻCheck the API Gateway URL call`.
Set the ʻAPI Gateway URL call` you confirmed earlier as the Webhook URL of the channel created by LINE Developers and enable the use of Webhooks. In addition, it disables the response message.
This completes the settings for "LINE Bot for Echolalia".
Register the created channel as a friend from the QR code and check if you want to return the parrot.
In this way, if you return the parrot, you will succeed
It might be a good idea to check the CloudWatch log group for errors.
This time, this is the end
Recommended Posts