[PYTHON] Make a parrot return LINE Bot on AWS Cloud9

Introduction

A memo to make a LINE Bot that returns parrots using SAM Local on AWS Cloud9

Diagram

I will make this.

image.png

Outline of procedure

-[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

reference

-LINE Messaging API x AWS Lambda simple response system # 2-appx1: Signature verification ――I mainly referred to the Lambda script.

1. [LINE Developers] Create provider

Create a provider in LINE Developers.

image.png

2. [LINE Developers] Set the channel for the created provider

Set up a channel for the provider you just created.

image.png

Select the Messaging API.

image.png

3. [LINE Developers] Get two pieces of information on the created channel

Get channel secret and channel access token information.

Channel secret information image.png

Click the Publish button for channel access token information. image.png

4. [AWS] Prepare Cloud9 environment

In the AWS console, create Cloud9. Created in the Tokyo region (ap-northeast-1).

image.png

5. [AWS-Cloud9] Create Lambda

Create a Lambda using SAM Local. Click λ->λ +on the right side of Cloud9 to create a new one.

image.png

Set an arbitrary character string in the red frame field and click the Next button

image.png

I chose Python.

image.png

Create API Gateway as a whole.

image.png

I made it the default setting.

image.png

Click the Finish button to start creating.

image.png

When the creation is completed, you will see a screen like this.

image.png

* Aside * [AWS] Confirmation of created AWS resources

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.

image.png

You can see the AWS resources created on the Resources tab of the stack when you created Lambda.

image.png

6. [AWS] Lambda script update

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).

image.png

7. [AWS] Set environment variables in Lambda

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.

image.png

8. Confirm the URL call of [AWS] API Gateway

ʻCheck the API Gateway URL call`.

image.png

9. Update [LINE Developers] channel settings

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.

image.png

This completes the settings for "LINE Bot for Echolalia".

[LINE Bot] Operation check

Register the created channel as a friend from the QR code and check if you want to return the parrot.

image.png

In this way, if you return the parrot, you will succeed

* Supplement * [AWS] When it does not work well

It might be a good idea to check the CloudWatch log group for errors.

image.png

line.png

This time, this is the end

Recommended Posts

Make a parrot return LINE Bot on AWS Cloud9
[Python] [LINE Bot] Create a parrot return LINE Bot
Make a LINE BOT (chat)
Parrot return LINE BOT creation
Procedure for creating a Line Bot on AWS Lambda
Checkpoint when you get hooked on LINE parrot return bot on Heroku
Make a bot for Skype on EC2 (CentOS)
Make a LINE WORKS bot with Amazon Lex
Make LINE BOT (Echolalia)
[AWS] I made a reminder BOT with LINE WORKS
Make a morphological analysis bot loosely with LINE + Flask
[For play] Let's make Yubaba a LINE Bot (Python)
[Super easy] Let's make a LINE BOT with Python.
[LINE Messaging API] Create parrot return BOT with Python
Let's make a Discord Bot.
Make a LINE bot with GoogleAppEngine / py. Simple naked version
Until I return something with a line bot in Django!
Let's make a LINE bot using various services [ngrok edition]
[AWS] I made a reminder BOT with LINE WORKS (implementation)
[Python] Make your own LINE bot
Make Perl segfault on one line
How to make a slack bot
Make Flask a Cloud Native application
[LINE bot] I'm a ranger! Part 2
[AWS / Tello] Build a system to operate the drone on the cloud
Create a LINE Bot in Django
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
Python calling Google Cloud Vision API from LINE BOT via 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
Run TensorFlow on a GPU instance on AWS
Creating a LINE bot ~ Creating, deploying, and launching ~
Make Jupyter Notebook a service on CentOS
Make Unity Accelerator a service on Linux
Build a Python + OpenCV environment on Cloud9
Let's make a Twitter Bot with Python!
I made a LINE Bot that sends recommended images every day on time
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
I made a stamp substitute bot with line
Consider a cloud-native WebSocket application running on AWS
Build a WardPress environment on AWS with pulumi
Make a Twitter trend bot with heroku + Python
Try Tensorflow with a GPU instance on AWS
Create a LINE BOT with Minette for Python
LINE BOT with Python + AWS Lambda + API Gateway
Simply display a line graph on Jupyter Notebook
Make a rock-paper-scissors game in one line (python)
I made a LINE Bot with Serverless Framework!
Serverless LINE bot made with IBM Cloud Functions
Anyway, I'm at home, so let's make a (site) screenshot function bot on Discord!
The world's most easy-to-understand explanation of how to make a LINE BOT (1) [Account preparation]