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 app 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 server where webhook payloads are sent.

  1. Log in to the LINE Developers console, and click the provider in which the channel for the Messaging API is present.

  2. Click the channel for the Messaging API.

  3. Click Edit under Use webhooks, and then select Enabled and click Update.

  4. Click Edit under Webhook URL, enter the Webhook URL (the destination URL for events sent from the LINE platform to the bot), and then click Update.

  5. Click Verify.

    If Webhook events are received by the set webhook URL, "Success" is displayed.

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

Console Channel settings page: Webhook URL

Add your LINE official account as a friend

Add the LINE official account associated with the channel for your bot as a friend on LINE. To do so, 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 LINE official account such as adding the LINE official account as a friend or sending the LINE official account a message, 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 LINE official account on LINE and check your server logs to confirm that your bot 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 LINE official account 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 LINE official account such as adding the LINE official account as a friend or sending the LINE official account a message, 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 LINE official account was added as a friend (or unblocked). You can reply to this events.
Unfollow event Indicates that your LINE official 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 device. 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 (LINE Things) Indicates that the user linked a device with LINE.
Device unlink event (LINE Things) Indicates that the user unlinked a device from LINE.

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

Sending a request to an endpoint

You can perform the following operations:

Sending reply messages

Reply messages are messages that are sent in response to a user-generated event such as when a user adds your LINE official account as a friend or sends your LINE official account a message. 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 Message types.

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

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

Send a POST request to one of the following endpoints depending on the number of recipients.

Endpoint Recipients
/message/push A single user
/message/multicast Multiple users
/message/broadcast All users who are friends of your LINE official account

When sending messages to specific users, specify the user ID in the to property. The recipient ID is found in webhook event objects.

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 -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 the following sections 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 LINE official account as a friend or sent your LINE official account a message, 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.

Setting with LINE Official Account Manager

LINE Official Account Manager is a tool for managing your LINE official account. 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 Official Account Manager.

For a complete list of features available to LINE official accounts, see the LINE for Business website.

Customize the account page

The account page provides users with basic information about your LINE official account.

Go to LINE Official Account Manager to add basic information about your LINE official account. You can customize the cover image, logo, buttons, and information provided.

LINE Official Account 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 Official Account Manager to set a greeting message to send users when they first add your LINE official account 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 Official Account 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 with the Messaging API, see each page of the Messaging API document.

{{ $t("form.question.helpful") }}

{{ $t("form.question.detail") }}

{{ $t("form.question.improve") }}

{{ $t("form.info.start") }}{{ $t("form.info.link") }}{{ $t("form.info.end") }}


{{ $t("form.result.success") }}
{{ $t("form.result.error") }}
{{ $t("form.result.errorLink") }}