LINE Messaging API SDK for Python

3.23.0 · active · verified Thu Apr 09

The `line-bot-sdk` is the official Python SDK for interacting with the LINE Messaging API. It simplifies the development of LINE bots by providing classes for sending messages, handling events, and managing user interactions. The current version is 3.23.0, and it maintains a frequent release cadence, often with monthly or bi-monthly updates to support new API features.

Warnings

Install

Imports

Quickstart

This Flask example sets up a basic LINE webhook. It receives messages, verifies the signature, and replies with the user's message. Ensure `LINE_CHANNEL_SECRET` and `LINE_CHANNEL_ACCESS_TOKEN` environment variables are set. This snippet requires Flask to be installed (`pip install Flask`).

import os
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage
)

app = Flask(__name__)

# Get channel_secret and channel_access_token from environment variable
channel_secret = os.environ.get('LINE_CHANNEL_SECRET', '')
channel_access_token = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN', '')

if not channel_secret:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    exit(1)
if not channel_access_token:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    exit(1)

line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)

@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=f"You said: {event.message.text}")
    )


if __name__ == "__main__":
    app.run(port=8000)

view raw JSON →