[PYTHON] Procedure for creating a Line Bot on AWS Lambda

Overview

We have summarized the procedure for creating a LineBot on AWS Lambda. I wrote from 1 without using line-bot-sdk-python. I use almost "reference" articles.

What is a webhook

-What is Webhook? -[What is a webhook? I tried to draw it so that even children can understand it](https://kintone-blog.cybozu.co.jp/developer/000283.html#:~:text=Webhook%E3%81%A8%E3%81%AF% EF% BC% 88% E7% 95% A5% EF% BC% 89% E3% 80% 81,% E3% 81% A7% E9% 80% 9A% E7% 9F% A5% E3% 81% 99% E3 % 82% 8B% E4% BB% 95% E7% B5% 84% E3% 81% BF% E3% 81% A7% E3% 81% 99% E3% 80% 82)

Development procedure introduction

Technology

flow

  1. Creating a Lambda function
  2. Line Developer registration
  3. Create Echolalia Bot
  4. Let's play with the bot a little

The entire

import json  
import logging  
import os  
import urllib.request  

#Preparing for log output
logger = logging.getLogger()  
logger.setLevel(logging.INFO)  

def lambda_handler(event, context):  
    #Log output of request contents
    logger.info(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
                if event['message']['text'] == 'honto':
                    messages.append({  
                            'type': 'image',  
                            'originalContentUrl': 'https://www.bizcourt.space/bizmarket/assets_c/2019/06/a_ocean_eyes_logo_bg_white_02-thumb-autox227-1304.png',
                            'previewImageUrl': 'https://www.bizcourt.space/bizmarket/assets_c/2019/06/a_ocean_eyes_logo_bg_white_02-thumb-autox227-1304.png'
                            })
                else:
                    messages.append({  
                          'type': 'text',  
                          'text': event['message']['text']+ 'is' 
                        })  

                #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!')  
    } 

Details

1. Creating a Lambda function

Python AWS Lambda Function Handler

2. Line Developer registration

Official documentation

3. Create Echolalia Bot

Throw a Post request

Use the urllib.request library. Official documentation Sample usage ... urllib.request is sufficient for Python HTTP client

Registration of environment variables From Using AWS Lambda Environment Variables

import os
region = os.environ['AWS_REGION']

You can use environment variables with.

4. Let's play with the bot a little

・ Return the image Image object of official document Refer to this document

messages.append({  
                            'type': 'image',  
                            'originalContentUrl': 'Image URL',
                            'previewImageUrl': 'Image URL'
                            })

Then you can return the image.

Reference: [How to send an image from a LINE bot] I made a LINE bot that returns an image of a Shiba Inu when asked

reference

LINE Messaging API x AWS Lambda simple response system # 1: Connect LINE to Lambda ← This service seems to be broken and the link is broken.

Impressions ・ Future ...

――Lambda is convenient. ――I want to improve my reading comprehension! ――LineBot seems to be applicable in more ways, so I'd like to do my best from now on.

Recommended Posts

Procedure for creating a Line Bot on AWS Lambda
Make a parrot return LINE Bot on AWS Cloud9
Creating a LINE bot ~ Creating, deploying, and launching ~
Procedure for building a kube environment on amazon linux2 (aws) ~ (with bonus)
Periodically run a python program on AWS Lambda
A tool for creating symbolic links on Windows
Make a bot for Skype on EC2 (CentOS)
Create a LINE BOT with Minette for Python
Procedure for creating a LineBot made with Python
LINE BOT with Python + AWS Lambda + API Gateway
Procedure for creating a Python quarantine environment (venv environment)
Creating a LINE BOT to notify you of additional AtCoder contests using AWS
[AWS] I made a reminder BOT with LINE WORKS
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
[For play] Let's make Yubaba a LINE Bot (Python)
Procedure for building a CDK environment on Windows (Python)
Make a LINE BOT (chat)
About "Lamvery", a deployment and management tool for AWS Lambda
Dockerfile for creating a data science environment based on pip3
A quick explanation from creating AWS Lambda Layers to linking
[AWS] I made a reminder BOT with LINE WORKS (implementation)
Step by Step for creating a Dockerfile
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Run Python on Schedule on AWS Lambda
Best practice for logging in JSON format on AWS Lambda / Python
[Go] Procedure for installing Go on WSL2
Serverless scraping on a regular basis with AWS lambda + scrapy Part 1
[LINE bot] I'm a ranger! Part 2
Create a LINE Bot in Django
The story of creating a store search BOT (AI LINE BOT) for Go To EAT in Chiba Prefecture (1)
I made a bot to post on twitter by web scraping a dynamic site with AWS Lambda (continued)
Use AWS lambda to scrape the news and notify LINE of updates on a regular basis [python]
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
I wrote a Slack bot that notifies delay information with AWS Lambda
Tips for making small tools in python
Tips for using Realsense SR300 on MacBook in 2020
Procedure for creating a Line Bot on AWS Lambda
Search for large files on Linux from the command line
Run TensorFlow on a GPU instance on AWS
Commands for creating a new django project
OpenCV aiming for a decent line art
[Python] [LINE Bot] Create a parrot return LINE Bot
Memo for creating a text formatting tool
Deployment procedure on AWS ① Network environment settings
Creating a cholera map for John Snow
Creating a development environment for machine learning
The story of creating a store search BOT (AI LINE BOT) for Go To EAT in Chiba Prefecture (2) [Overview]
Create a bot with AWS Lambda that automatically starts / stops Instances with specific tags
I made a LINE Bot that sends recommended images every day on time
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
A story about cross-compiling a python package for AWS Lambda and deploying it serverless
A procedure manual for quickly publishing a C ++ Python library using pybind11 on Github.
[Linux] Review of commands for deploying on AWS
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
Try Tensorflow with a GPU instance on AWS
[Piyopiyokai # 1] Let's play with Lambda: Creating a Lambda function
Simply display a line graph on Jupyter Notebook
I made a LINE Bot with Serverless Framework!
A memorandum for touching python Flask on heroku
Commands for creating a python3 environment with virtualenv