[PYTHON] Until implementing LINE chatbot in Chalice

Premise

I wanted to put it on AWS and run it because anything is fine. I've deployed LINE chatbot on Heroku, so I decided to put this on for the time being.

What is Chalice

Chalice is an AWS-made application framework that enables an API environment with Amazon API Gateway and AWS Lambda for Python. (From AWS official)

In addition to being able to build and deploy applications from the command line It automatically grants the IAM role policy to be granted to Lambda, It was quite convenient, such as automatically paying out the API.

Until the introduction of Chalice

Preparation ・ Acquisition of AWS account -Installing the AWS CLI If you are installing the AWS CLI for the first time, after installation

aws configure

Hit the command to enter the account access key or secret access key, Let's register the region and output format. Credentials are stored in the .aws folder under your home directory. Issuing the root user's access key is not recommended, so create an IAM user and register its credentials.

Chalice


pip install chalice

You can install it with.

From project creation to deployment

chalice new-project hello-world

The command will generate a project file. Click here for the directory structure.

│  .gitignore
│  app.py
│  requirements.txt
│
└─.chalice
        config.json

Edit app.py. This is the default.

app.py


from chalice import Chalice

app = Chalice(app_name='hello-world')


@app.route('/')
def index():
    return {'hello': 'world'}


# The view function above will return {"hello": "world"}
# whenever you make an HTTP GET request to '/'.
#
# Here are a few more examples:
#
# @app.route('/hello/{name}')
# def hello_name(name):
#    # '/hello/james' -> {"hello": "james"}
#    return {'hello': name}
#
# @app.route('/users', methods=['POST'])
# def create_user():
#     # This is the JSON body the user sent in their POST request.
#     user_as_json = app.current_request.json_body
#     # We'll echo the json body back to the user in a 'user' key.
#     return {'user': user_as_json}
#
# See the README documentation for more examples.
#

You can check the operation locally with the following command.

chalice local

WS000008.JPG

Click here to deploy.

chalice deploy

WS000009.JPG

Go to the API URL that was issued and check that {'hello':'world'} is returned. Here is the cleanup.

chalice delete

Implement LINE chatbot

Register with LINE developers

Set the application name etc. appropriately and create a channel for returning parrots. Turn on the use of webhooks from the Messaging API settings and Messaging API settings ** Channel access token (long term) **, Make a note of the ** channel secret ** in the channel preferences.

Install line-bot-sdk

Locally

pip install line-bot-sdk

OK. Drop the whl format file from PyPI for deployment to Lambda. When using an external library with Lambda, create a vendor folder in the folder of the project name and store it in whl format there. In addition, create requirements.txt and specify the version to use.

requirements.txt


line-bot-sdk==1.17.0

Register environment variables

Add environment variables to config.json in the .chalice directory. Let's register the channel secret and channel access token that we wrote down earlier as follows.

config.json


{
  "version": "2.0",
  "app_name": "line-bot",
  "stages": {
    "dev": {
      "api_gateway_stage": "api",
      "environment_variables": {
      "LINE_CHANNEL_SECRET": "Channel secret",
      "LINE_CHANNEL_ACCESS_TOKEN": "Channel access token"
      }
    }
  }
}

Editing app.py

Create a webhook for LINE Bot on AWS Lambda using Chalice I referred to here.

Deploy-Result

Deploy. If you check the console, Lambda and API gateway are created. WS000001.JPG WS000003.JPG

Register the issued API URL plus / callback in the LINE developers webhook. If you press verify and there is no problem, it is OK. WS000004.JPG

Then talk to the bot and see if the parrot return works. WS000007.JPG

Troubleshooting up to implementation

At first, I went to test Lambda because Aum didn't say yes or no. WS000000.JPG An empty json is sufficient for the test function here. I confirmed the failure, so I went to see CloudWatch. Error logs are stored in CloudWatch> CloudWatch Logs> Log groups. When I open the line-bot log stream ... WS000005.JPG It is said that there is no line-bot module. I checked and found that it was fine until I stored the library in vendor, but forgot to edit the requirements.txt file.

Precautions / unsolved matters

-I was in a hurry because the console did not work for a few minutes after deploying, but it seems that it took a long time to install line-bot-sdk. Let's wait patiently. -When I connect to api / callback with a browser, it becomes {"message": "Missing Authentication Token"}. The parrot return itself is working, but ... -Chalice automatically grants the IAM role policy given to Lambda nicely, but the policy of the IAM user who has the access key to access AWS must be given here. Even if I give such a policy, I don't have the authority. I was rejected by an error, and this time I ended up hitting the Administrator Access policy and pushing it (it doesn't make sense to create an IAM user ...).

Recommended Posts

Until implementing LINE chatbot in Chalice
Until I return something with a line bot in Django!
Try implementing Yubaba in Python 3
Implement Slack chatbot in Python