LINE Messaging API SDK for Python

repository·master·Indexed 24 days ago

https://github.com/line/line-bot-sdk-python

A client library designed to simplify the development of LINE bots. It provides high-level abstractions for handling webhooks, managing event handlers, and interacting with the LINE Messaging API through modules such as linebot.api, linebot.webhook, and linebot.models. The SDK includes support for various frameworks like FastAPI, Flask, and aiohttp, and provides specialized classes like ManageAudience for managing audience groups.

Tokens
50.2K
Snippets
122
Records
136
Agent score
84%

What's inside line-bot-sdk-python

  1. Overview of the linebot package modules

    master

    The linebot package is organized into several core modules that provide the functionality needed to interact with the LINE Messaging API:

    • linebot.api: Contains the primary API client for sending messages and interacting with LINE services.
    • linebot.webhook: Provides tools for handling incoming webhook events, including signature verification and event parsing.
    • linebot.models: Contains the data models (schemas) for messages, events, and other API objects.
    • linebot.exceptions: Defines the exception hierarchy for error handling within the SDK.
    • linebot.http_client: Manages the underlying HTTP communication layer.
  2. ManageAudience API Overview

    master

    The linebot.v3.audience.ManageAudience class provides methods to manage audience groups for the LINE Messaging API. This includes creating audiences for uploading user IDs, creating click-based or impression-based audiences, managing existing groups, and handling shared audience data.

    Available Methods

    MethodHTTP RequestDescription
    add_audience_to_audience_groupPUT /v2/bot/audienceGroup/uploadAdd user IDs or Identifiers for Advertisers (IFAs) to an audience
    create_audience_groupPOST /v2/bot/audienceGroup/uploadCreate audience for uploading user IDs (by JSON)
    create_click_based_audience_groupPOST /v2/bot/audienceGroup/clickCreate audience for click-based retargeting
    create_imp_based_audience_groupPOST /v2/bot/audienceGroup/impCreate audience for impression-based retargeting
    delete_audience_groupDELETE /v2/bot/audienceGroup/{audienceGroupId}Delete an audience group
    get_audience_dataGET /v2/bot/audienceGroup/{audienceGroupId}Get data for a specific audience group
    get_audience_groupsGET /v2/bot/audienceGroup/listList audience groups
    get_shared_audience_dataGET /v2/bot/audienceGroup/shared/{audienceGroupId}Get data for a shared audience group
    get_shared_audience_groupsGET /v2/bot/audienceGroup/shared/listList shared audience groups
    update_audience_group_descriptionPUT /v2/bot/audienceGroup/{audienceGroupId}/updateDescriptionUpdate the description of an audience group
  3. Quickstart: Create a Flask Echo Bot

    master

    This example demonstrates how to set up a Flask server to handle LINE webhooks, verify signatures, and reply to text messages using the v3 API.

    from flask import Flask, request, abort
    
    from linebot.v3 import (
        WebhookHandler
    )
    from linebot.v3.exceptions import (
        InvalidSignatureError
    )
    from linebot.v3.messaging import (
        Configuration,
        ApiClient,
        MessagingApi,
        ReplyMessageRequest,
        TextMessage
    )
    from linebot.v3.webhooks import (
        MessageEvent,
        TextMessageContent
    )
    
    app = Flask(__name__)
    
    configuration = Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')
    handler = WebhookHandler('YOUR_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:
            app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
            abort(400)
    
        return 'OK'
    
    
    @handler.add(MessageEvent, message=TextMessageContent)
    def handle_message(event):
        with ApiClient(configuration) as api_client:
            line_bot_api = MessagingApi(api_client)
            line_bot_api.reply_message_with_http_info(
                ReplyMessageRequest(
                    reply_token=event.reply_token,
                    messages=[TextMessage(text=event.message.text)]
                )
            )
    
    if __name__ == "____main__":
        app.run()
  4. Set up the Flask Echo sample bot

    master

    To run the Flask Echo sample bot, you must first configure your LINE Messaging API credentials as environment variables.

    1. Set your LINE_CHANNEL_SECRET and LINE_CHANNEL_ACCESS_TOKEN.
    2. Install the required dependencies using pip.
    3. Run the desired sample script.
    $ export LINE_CHANNEL_SECRET=YOUR_LINE_CHANNEL_SECRET
    $ export LINE_CHANNEL_ACCESS_TOKEN=YOUR_LINE_CHANNEL_ACCESS_TOKEN
    
    $ pip install -r requirements.txt
  5. Configure MessagingApi authentication

    master

    To use the MessagingApi, you must configure the linebot.v3.messaging.Configuration object with appropriate authentication parameters according to the API server security policy.

    For most bot implementations, you will use Bearer authorization by providing an access_token.

    Note: The host parameter is optional and defaults to https://api.line.me.

    import linebot.v3.messaging
    import os
    
    # Basic configuration with Bearer token
    configuration = linebot.v3.messaging.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
    
    # Optional: Defining a custom host
    configuration = linebot.v3.messaging.Configuration(
        host = "https://api.line.me",
        access_token = os.environ["BEARER_TOKEN"]
    )
  6. Configure LineModuleAttach with Basic Authentication

    master

    To use the LineModuleAttach client, you must configure the Configuration object with the appropriate authentication parameters. For Basic Authentication (basicAuth), provide the username and password (typically retrieved from environment variables) to the Configuration instance. The default host is https://manager.line.biz.

    import os
    import linebot.v3.moduleattach
    
    # Configure HTTP basic authorization: basicAuth
    configuration = linebot.v3.moduleattach.Configuration(
        username = os.environ["USERNAME"],
        password = os.environ["PASSWORD"]
    )
    
    # Enter a context with an instance of the API client
    with linebot.v3.moduleattach.ApiClient(configuration) as api_client:
        # Create an instance of the API class
        api_instance = linebot.v3.moduleattach.LineModuleAttach(api_client)
        # ... call api_instance methods ...
  7. Configure MessagingApiBlob with Bearer Authentication

    master

    To use MessagingApiBlob, you must first create a Configuration object and pass it to an ApiClient. For standard LINE Messaging API access, use Bearer authentication by providing an access_token.

    Note: The host parameter is optional and defaults to https://api.line.me.

    import os
    import linebot.v3.messaging
    
    # Optional: Explicitly defining the host
    configuration = linebot.v3.messaging.Configuration(
        host = "https://api.line.me"
    )
    
    # Required: Configure Bearer authorization
    configuration = linebot.v3.messaging.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
    
    # Initialize the client
    with linebot.v3.messaging.ApiClient(configuration) as api_client:
        api_instance = linebot.v3.messaging.MessagingApiBlob(api_client)
  8. Configure Bearer authorization for the Shop API

    master

    To use the linebot.v3.shop client, you must configure the Configuration object with a Bearer token. This token is typically retrieved from your environment variables.

    import os
    import linebot.v3.shop
    
    configuration = linebot.v3.shop.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
    import os
    import linebot.v3.shop
    
    configuration = linebot.v3.shop.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
  9. Initialize MessagingApi with Bearer Authentication

    master

    To use the MessagingApi, you must first configure an ApiClient with your authentication credentials. The most common method is using Bearer token authentication. You create a Configuration object, pass it to an ApiClient, and then instantiate MessagingApi using that client. It is recommended to use the ApiClient as a context manager to ensure proper resource handling.

    import os
    import linebot.v3.messaging
    
    # Configure Bearer authorization
    configuration = linebot.v3.messaging.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
    
    # Enter a context with an instance of the API client
    with linebot.v3.messaging.ApiClient(configuration) as api_client:
        # Create an instance of the API class
        api_instance = linebot.v3.messaging.MessagingApi(api_client)
        # Now you can call api_instance methods
  10. Configure the LIFF API client with Bearer authentication

    master

    To use the linebot.v3.liff module, you must first create a Configuration object specifying the host and your authentication credentials. For most use cases, you will use Bearer authentication by providing an access_token.

    All URIs are relative to https://api.line.me by default. You can then initialize an ApiClient using this configuration and pass it to the Liff class to perform operations.

    import os
    import linebot.v3.liff
    
    # Configure the host (optional, defaults to https://api.line.me)
    configuration = linebot.v3.liff.Configuration(
        host = "https://api.line.me"
    )
    
    # Configure Bearer authorization
    configuration = linebot.v3.liff.Configuration(
        access_token = os.environ["BEARER_TOKEN"]
    )
    
    # Initialize the API client and the Liff instance
    with linebot.v3.liff.ApiClient(configuration) as api_client:
        api_instance = linebot.v3.liff.Liff(api_client)
        # api_instance is now ready to use