Building a bot

This guide describes how to use the Messaging API to build a LINE bot. If you'd like to start by deploying a sample bot, go to Building a sample bot with Heroku.

Before you begin

Make sure you have completed the following:

  • Created a channel for your bot
  • Prepared a server to host your bot. You can use a cloud platform service such as Heroku.

Setting up your bot on the console

Your bot application requires a channel access token to make API calls and a webhook URL to receive webhook payloads from the LINE Platform.

Issue a channel access token

The channel access token is a long-lived token that must be set in the authorization header when making API calls. You can reissue the channel access token at any time through the console.

To issue a channel access token, click Issue on the "Channel settings" page on the console.

Set a webhook URL

The webhook URL is the endpoint of your bot application's server where webhook payloads are sent.

  1. Enter a webhook URL for your bot in the "Channel settings" page on the console.
  2. To enable webhooks, select Use webhooks. (Note: This is set to "Off" by default.)
  3. To confirm that your webhook URL can receive webhooks, click the Verify button and make sure "Success" is returned.

Note: The webhook URL must use HTTPS and have an SSL certificate issued by an authorized certificate authority (CA). See authorized CA list.

Console Channel settings page: Webhook URL

Add your bot as a friend

To add your bot as a friend on LINE, scan the QR code on the "Channel settings" page in the console.

Configure security settings (optional)

To improve security, you can specify the servers that can send and receive data from the LINE Platform on the "Security settings" page of the console. You can register IP addresses individually or if you have multiple servers you can use classless inter-domain routing (CIDR) notation to register your network address.

Security settings

Receiving webhooks

A webhook event is triggered when a user interacts with your bot such as sending a message or adding your bot as a friend. The LINE Platform then sends an HTTP POST request to your webhook URL with a webhook event object and a signature in the header.

Validate signature

To ensure that the request is sent from the LINE Platform, your bot application must validate the X-Line-Signature in the request header.

  1. Using the channel secret as a secret key, generate a Base64-encoded digest from the request body using the HMAC-SHA256 algorithm.
  2. Confirm that the X-Line-Signature signature in the request header matches the digest.

The following is an example of how to implement signature validation in Python.

import base64
import hashlib
import hmac

channel_secret = ... # Channel secret string
body = ... # Request body string
hash = hmac.new(channel_secret.encode('utf-8'),
    body.encode('utf-8'), hashlib.sha256).digest()
signature = base64.b64encode(hash)
# Compare X-Line-Signature request header and the signature

For more information and code samples, see validating signatures.

Receive webhook events

To confirm that your server can receive webhooks, block your bot on your LINE app and check your logs to confirm that your server receives an unfollow webhook event from the LINE Platform. After you have confirmed that your bot can receive webhooks, add your bot as a friend again.

2017-07-21T09:18:46.755256+00:00 app[web.1]: 2017-07-21 09:18:46.737  INFO 4 --- [io-13386-exec-2] c.e.bot.spring.KitchenSinkController     : unfollowed this bot: UnfollowEvent(source=UserSource(userId=Uxxxxxxxxxx...), timestamp=2017-07-21T09:18:46.031Z)

Receive and handle the data found in the JSON object sent in the request body. Webhook events that your bot can reply to contain a reply token. For more information on webhook events, see webhook-reference.

Sending reply messages

Reply messages are messages that are sent in response to a user-generated event such as when a user sends your bot a message or adds your bot as a friend. You can only reply to webhook events which include a reply token in the webhook event object.

To send a reply message, send an HTTP POST request to the /message/reply endpoint. Include the Channel access token in the authorization header and replyToken in the body. You can send up to 5 message objects in a single request.

For more information on the type of messages that you can send using the Messaging API, see message types.

Example

curl -X POST \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-d '{
    "replyToken":"nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
    "messages":[
        {
            "type":"text",
            "text":"Hello, user"
        },
        {
            "type":"text",
            "text":"May I help you?"
        }
    ]
}' https://api.line.me/v2/bot/message/reply

For more information, see send reply messages.

Sending push messages

Note: Only certain plans allow bots to send push messages. For more information, see LINE@ plans.

Push messages are messages that your bot can send to users at any time. Unlike reply messages, push messages do not require a reply token.

To send push messages to an individual user, send an HTTP POST request to the /message/push endpoint. For multiple users, send a POST request to the /message/multicast endpoint. You can send up to 5 message objects in a single request.

For more information on the type of messages that you can send using the Messaging API, see message types.

Example

curl -X POST \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-d '{
    "to": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"],
    "messages":[
        {
            "type":"text",
            "text":"Hello, world1"
        },
        {
            "type":"text",
            "text":"Hello, world2"
        }
    ]
}' https://api.line.me/v2/bot/message/multicast

For more information, see Send push messages.

Getting content sent by users

To retrieve image, video, or audio data sent by users, send an HTTP GET request to the /message/{messageId}/content endpoint. Note that content sent by users is automatically deleted after a certain period of time.

Example

curl -X GET \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
https://api.line.me/v2/bot/message/{messageId}/content

For more information, see get content.

Getting user profile information

To get the LINE profile information of a user that adds your bot as a friend or sends a message to your bot, send an HTTP GET request to the profile endpoint. Include the user ID as a parameter in the URL. This request returns the user's display name, user ID, profile image URL, and status message if available.

Example

curl -X GET \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
https://api.line.me/v2/bot/profile/{userId}

If successful, a JSON object is returned.

{
    "displayName":"LINE Botto",
    "userId":"Uxxxxxxxxxxxxxx...",
    "pictureUrl":"http://obs.line-apps.com/...",
    "statusMessage":"Hello world!"
}

For more information, see get profiles.

LINE@ Manager settings

The LINE@ Manager is a tool for managing your LINE@ account (LINE bot). When creating a bot with the Messaging API, you can improve the user experience by creating a rich menu and an account page on the LINE@ Manager.

For a complete list of features available to LINE@ accounts, see LINE@ features.

Create a rich menu

The rich menu is a customizable menu which helps users discover how they can interact with your bot. Users can access this menu from the chat at any time.

To configure the rich menu for your bot, go to the "Create Rich Content" menu in the LINE@ Manager. Select the design of the menu and configure the details of the buttons.

rich menu

Customize the account page

The account page provides users with basic information about your bot (LINE@ account).

Go to the LINE@ Manager to add basic information about your bot. You can customize the cover image, logo, buttons, and information provided.

account page

Set a greeting message (optional)

If you enable the "Greeting message" option on the "Channel settings" page of the console, you can go to the LINE@ Manager to set a greeting message to send users when they first add your bot as a friend. Alternatively, you can do this programmatically by responding to users after receiving a follow webhook event.

Set auto reply messages (optional)

If you enable the "Auto reply message" option on the "Channel settings" page of the console, you can go to the LINE@ Manager to set automated reply messages to respond to messages sent by users. However, you can do more with the Messaging API as you can program your bot to reply in different ways to various webhook events.

Other Messaging API features

The following are other features available with the Messaging API.

Group chats

Your bot can join group chats as well as one-on-one chats. For more information on using your bot in group chats, see Group chats.

Using beacons

Using LINE Beacon, you can configure your bot to interact with users whenever they enter the range of a beacon. For more information on using beacons, see Using beacons.

Resources

For more information on developing a LINE bot, see the following pages.