[PYTHON] Serverless LINE bot made with IBM Cloud Functions

IBM Cloud x LINE bot again this year

Last year's Advent calendar introduced How to make a LINE bot using Node-RED from IBM Cloud. Maybe it's because of the Advent calendar. Recently, when I searched for "Node-RED LINE bot" on Google, this article came to the top. It is good to easily create a LINE bot with Node-RED, but in the case of IBM Cloud Node-RED, if you do not edit the flow for a while with the light plan, the application will stop and the LINE bot will not work. There were often. So, when I thought about a LINE bot that could be made with a light plan by other methods, I came up with a method to make a bot using IBM Cloud Functions that I recently learned. Since I am making LINE bots with serverless from other cloud vendors, I thought that there is no reason why I can not do it with IBM Cloud, so this time I will make serverless LINE bots using IBM Cloud Functions.

IBM Cloud CLI installation

This time we will use the LINE bot SDK, so we will create actions on the command line. Install the command line tools from here (https://cloud.ibm.com/docs/cli?topic=cloud-cli-install-ibmcloud-cli&locale=ja). After the installation is complete, launch a terminal (command prompt for Windows) and log in to IBM Cloud with the following command.

$ ibmcloud login

If you can log in, the installation is complete.

Preparation of action

Preparation of execution environment

The LINE bot SDK is not in the default environment of IBM Cloud Functions, so you need to build the environment using Docker. Here introduces the environment construction method. This time, the repository of Docker hub is published at the link below, so I will use it. This environment is just the SDK of LINE bot in the Python library that is included by default in IBM Cloud Functions. kmiura/linebot_function

Preparation of code

Open an editor and save the following code. Here, we created the familiar "echolalia" for bots that reply to the message sent to the bot as it is. The file name and action name when saving must match. Here, it is "first-linebot.py".

first-linebot.py


# coding: utf-8
from linebot import LineBotApi
from linebot.exceptions import LineBotApiError
from linebot.models import TextSendMessage


def main(args):
    print(args)
    # account setting
    line_bot_api = LineBotApi(args['CHANNEL_ACCESS_TOKEN'])

    # make responce
    body = args["events"][0]
    try:
        if body["source"]["userId"] == "Udeadbeefdeadbeefdeadbeefdeadbeef":
            return {"status": 200}
        else:
            line_bot_api.reply_message(
                body["replyToken"],
                TextSendMessage(text=body["message"]["text"]))
    except LineBotApiError as e:
        print("Got exception from LINE Messaging API: %s\n" % e.message)
        for m in e.error.details:
            print("  %s: %s" % (m.property, m.message))
        return {"status": 403}

    return {"status": 200}

Creating an action

Now let's create an action. First, install the IBM Cloud Functions plug-in.

$ ibmcloud plugin install cloud-functions

Target the resource group with the following command. For the group name, log in from here to check.

$ ibmcloud target -o <org> -s <space> 

Create an action with the following command.

$ ibmcloud fn action create first-linebot --docker kmiura/linebot_function first-linebot.py 

If the result is returned without any error, it is successful.

Webhook URL generation

Now that we've created the action, it's time to generate the webhook URL to set on the LINE bot. Log in to IBM Cloud from your browser and open the action setting screen you created earlier from the IBM Cloud Functions screen (open by selecting Functions or function in the menu on the dashboard screen). Click the Endpoints` `` tab and check Enable as Web Action `` `to save. This will generate a URL where you can call the web action, so copy it.

コメント 2019-10-26 194305.png

LINE bot settings

Settings in LINE Developers

Now, let's create a LINE bot. Log in to LINE Developers, go to ** New Brobider → Create Channel → Messaging API **, go to the new channel setting screen below, and enter the required items. please.

** * All items except optional items are required. ** ** ** * Character strings including LINE cannot be registered in the app name, so enter any other name. ** **

When the creation is completed, you will be taken to the channel setting screen. Select the "Mesaging API Settings" tab from this and add friends from the QR code displayed above. Scroll down and paste the Functions URL you just copied into the Webhook URL. At this time, at the end of the URL, .json If you add, the value received by Webhook will be fetched by json, so it will be easier to process on the Functions side. After completing the entry, click the "Update" button to complete the registration. To see if the Function works, click the Validate button. The Function code used this time also implements a response for checking the operation, so if it works correctly, it will be displayed as "success". After updating, let's enable the use of the Webhook that appears below.

コメント 2019-12-02 233240.png

This alone will not move the bot. If you go further down, the following LINE official account function will appear, but the response message in this will be disabled. Click Edit to the left of the response message item.

コメント 2019-12-02 233723.png

Please set the response message to "disabled" from the following screen linked to.

コメント 2019-12-02 234022.png

If you scroll further, the issue column for the channel access token will appear. Click "Issue" to issue the access token and make a note of it.

スクリーンショット 2019-12-03 00.48.32.png

IBM Cloud CLI settings

Then, launch the terminal (command prompt or Power Shell for window) again and register the access token you copied earlier from the CLI as an action parameter. Register with the following command.

$ ibmcloud fn action update YOUR_ACTION --param CHANNEL_ACCESS_TOKEN YOUR_ACCESS_TOKEN

Operation check

Then, open the LINE app, open the account of the bot you created earlier, and when the sent message is returned from the bot, it is working normally. IMG_7192.png

What did you think? You can easily create a LINE bot even in the serverless environment of IBM Cloud. And with IBM Cloud Functions, the Watson SDK is built in, so it's easy to create bots that work with Watson. Also, if you have knowledge of Docker, you can customize the environment, so I think that it is a serverless architecture with a high degree of freedom.

Recommended Posts

Serverless LINE bot made with IBM Cloud Functions
I made a LINE Bot with Serverless Framework!
I made a stamp substitute bot with line
[AWS] I made a reminder BOT with LINE WORKS
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
I made a household account book bot with LINE Bot
I made a LINE BOT with Python and Heroku
I made a LINE BOT that returns parrots with Go
[AWS] I made a reminder BOT with LINE WORKS (implementation)
I want to use an external library with IBM Cloud Functions
Try using Python with Google Cloud Functions
Deploy functions with Cloud Pak for Data
Monitor web page updates with LINE BOT
Serverless face recognition API made with Python
Decision support system for elderly people made with LINE Messaging API + Serverless Framework
I made my dog "Monaka Bot" with LineBot
Create a LINE BOT with Minette for Python
LINE BOT with Python + AWS Lambda + API Gateway
Make a LINE WORKS bot with Amazon Lex
I made a Mattermost bot with Python (+ Flask)
I made a Twitter BOT with GAE (python) (with a reference)
Make a morphological analysis bot loosely with LINE + Flask
Make a parrot return LINE Bot on AWS Cloud9
Run Google Cloud Functions locally with Cloud Native Build packs
[Super easy] Let's make a LINE BOT with Python.
[LINE Messaging API] Create parrot return BOT with Python
Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)