How to make a Line chatbot with AWS Lambda


Posted by ar851060 on 2024-05-25

Since I participated Hackathon held by AWS just one week ago, I want to practice how to use AWS services. This side project is just a practice to make a very simple Line chatbot (echo chatbot) using AWS Lambda. I will write another article to explain how to create an AI Line chatbot using AWS bedrock and AWS dynamoDB. Let's get started.

The struture of Line chatbot

The steps is following:

  1. Create a Business Line account and create a Line official account
  2. Open webhook feature in Line
  3. Copy Channel access token and Channel secert from Line official account, we will use it later.
  4. Create AWS account
  5. Create a Lambda function
  6. Upload required package as layers in AWS lambda
  7. Create API in Lambda (without entering API gateway)
  8. Put API into Line webhook, and test it.

Since I am lazy, I will start write from step 5. If you want to know about how to create Line business account, you can see in this link.

Also, don't worry about price. AWS Lambda is free if the number of request event is lower than 1 million per month. It is very difficult for a side project.

image

Create a Lambda Function

When you get into AWS console, please click Lambda function to enter it, and then click Create Function.

image

After clicking, you can name your function whatever you want, and please change your runtime as Python 3.12. Everything else can stay as default, and press Create Function.

image

Put the following code into Code Source and press Deploy

from linebot.v3 import (
    WebhookHandler
)
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    TextMessage,
    ReplyMessageRequest
)
from linebot.v3.exceptions import (
    InvalidSignatureError
)
from linebot.v3.webhooks import (
    MessageEvent,
    TextMessageContent
)

import os
import json

configuration = Configuration(access_token=os.environ['Channel_access_token'])
handler = WebhookHandler(os.environ['Channel_secret'])

def lambda_handler(event, context):
    @handler.add(MessageEvent, message=TextMessageContent)
    def handle_message(event):
        with ApiClient(configuration) as api_client:
            line_bot_api = MessagingApi(api_client)
            line_bot_api.reply_message(
                ReplyMessageRequest(
                    reply_token=event.reply_token,
                    messages=[TextMessage(text=event.message.text)]
                )
            )

    signature = event['headers']['x-line-signature']
    body = event['body']

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        return {
            'statusCode': 502,
            'body': json.dumps("Invalid signature. Please check your channel access token/channel secret.")
            }
    return {
        'statusCode': 200,
        'body': json.dumps("OK")
        }

Upload Requirement Package as Layer and Set Environment Variables

First, please find Configuration section and find Environment variables in side bar. Press Add variable and set your Channel access token and Channel secret from your Line business account.

Next, please use pip install line-bot-sdk -t target_dir to download line sdk into your target directory, and zip it as zip file.

Then, click Layers on the side bar of AWS Lambda page, and press Create Layers. You can name this layer whatever you want, select Upload a .zip file, and Upload your zip file mentioned above. Press Create at the bottom of this page, and copy the ARN code.

image

Finally, go to Functions at the side bar of Lambda page, and press the name of your function. You can see there is a bar under the logo of Lambda saying that Layers (0). Press it, and press Add a Layer. Press Specify an ARN and paste ARN code into the bar under the page. Press Add, and the layer is done.

If you want to know more about Layers, please check this link

Create API in Lambda

Go to the Configuration, press Trigger at the side bar, and press Add Trigger.

  • select API Gateway
  • select Create a new API
  • select REST API
  • select Open in Security section.
  • Press Add

image

Put API into Line webhook, and test it.

First, check whether you need to deploy the newest function.

Then, copy API endpoint under the API Gateway we just created.

Finally, paste API endpoint in Webhook URL in Line Business account (Please make sure you open Use webhook first).

And you can play with your chatbot in Line.


Line icons created by Ruslan Babkin - Flaticon


#line #Chatbot #aws #lambda









Related Posts

我知道你懂 hoisting,可是你了解到多深?

我知道你懂 hoisting,可是你了解到多深?

[Day 01] 強化學習?

[Day 01] 強化學習?

如何打包 CRA 專案並建立不透過第三方服務即可供別人使用的專案

如何打包 CRA 專案並建立不透過第三方服務即可供別人使用的專案


Comments