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 webhook events, 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 the 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 servers that can call APIs of 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 page

Confirming the webhook behavior

When a user interacts with your bot such as sending a message or adding your bot as a friend, the LINE Platform sends an HTTP POST request that contains a webhook event object to the bot server specified in the "Webhook URL" field in the console. The request header contains a signature.

This section explains how to check if your server can receive webhook events and how to validate the signature of webhook events.

Receiving webhook events

To confirm that your server can receive webhook events, block your bot on LINE and check your server logs to confirm that your server receives an unfollow event from the LINE Platform. The following is an example log.

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)

After you have confirmed that the webhook works normally, add your bot as a friend again.

Validating the signature

To ensure that the request is sent from the LINE Platform, your bot server 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 Signature validation in the Messaging API reference.

Webhook event types

When a user interacts with your bot such as sending a message or adding your bot as a friend, the LINE Platform sends an HTTP POST request that contains a webhook event object to the bot server specified in the "Webhook URL" field in the console. You can control your bot's behavior and respond to the user on the basis of the data in the webhook event object.

The following webhook events are available for the one-on-one chat. For more information, see Webhook event objects in the Messaging API reference.

Event type Description
Message event Indicates that the user sent a message. You can reply to this events.
Follow event Indicates that your account was added as a friend (or unblocked). You can reply to this events.
Unfollow event Indicates that your account was blocked.
Postback event Indicates that the user performed a postback action. You can reply to this events.
Beacon event Indicates that the user entered or left the range of a LINE Beacon. You can reply to this events. For more information, see Using beacons.
Account link event Indicates that the user has linked their LINE account with a provider's (your) service account. You can reply to this events. For more information, see Linking user accounts.
Device link event Indicates that a LINE Things-compatible device has been linked with LINE by a user operation. For more information, see Receiving device link events via webhook.
Device unlink event Indicates that a LINE Things-compatible device has been unlinked from LINE by a user operation. For more information, see Receiving device unlink events via webhook.

See Group chats for webhook events that are specific to group chats.

Sending a request to an endpoint

You can perform the following operations via your bot.

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 that include a reply token.

To send a reply message, send an HTTP POST request to the /bot/message/reply endpoint. Include the channel access token in the authorization header and the reply token 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 Messages.

Example

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

For more information, see Send reply message in the Messaging API reference.

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.

When sending push messages, specify the user ID in the to property. The recipient ID is found in webhook event objects. Send a POST request to the following endpoints depending on the number of recipients.

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 Messages.

Example

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

For more information, see Send push message and Send multicast messages in the Messaging API reference.

Getting content sent by users

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

Example

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

For more information, see Get content in the Messaging API reference.

Getting user profile information

To get the LINE profile information of a user that added your bot as a friend or sent a message to your bot, send an HTTP GET request to the /bot/profile/{userId} endpoint. This request returns the user's display name, user ID, profile image URL, and status message if available.

Example

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

If successful, a JSON object is returned.

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

For more information, see Get profile in the Messaging API reference.

Other Messaging API features

The following are other major 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.

Rich menus

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. Rich menus can be created using the Messaging API or LINE@ Manager.

For more information, see Using rich menus.

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.

By using the account link feature, providers (businesses and developers) can securely link the existing user accounts from their service with accounts belonging to LINE users that have friended providers' bot. For more information, see Linking user accounts.

LINE@ Manager settings

LINE@ Manager is a tool for managing your LINE@ account (LINE bot). In addition to using features provided by the Messaging API, you can improve the user experience by customizing the account page, creating Timeline posts, and using other features of LINE@ Manager.

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

Customize the account page

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

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

LINE@ Manager 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 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 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.

Next steps

For more information about features available LINE bots, see each page of the Messaging API document.