or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdindex.mdmessaging.mdrich-menus.mdrich-messages.mduser-management.mdwebhooks.md
tile.json

tessl/pypi-line-bot-sdk

LINE Messaging API SDK for Python with comprehensive bot development capabilities including messaging, webhooks, and platform integrations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/line-bot-sdk@3.19.x

To install, run

npx @tessl/cli install tessl/pypi-line-bot-sdk@3.19.0

index.mddocs/

LINE Bot SDK for Python

A comprehensive Python SDK for building LINE bots and messaging applications using the LINE Messaging API. The SDK provides both synchronous and asynchronous APIs, webhook handling, rich message support, and integration with LINE's platform features including LIFF apps, rich menus, audience management, and analytics.

Package Information

  • Package Name: line-bot-sdk
  • Package Type: pypi
  • Language: Python
  • Installation: pip install line-bot-sdk
  • Python Requirements: >= 3.9.0

Core Imports

Modern v3 API (recommended):

# Messaging API
from linebot.v3.messaging import MessagingApi, AsyncMessagingApi, Configuration, ApiClient, AsyncApiClient

# Webhook handling
from linebot.v3 import SignatureValidator, WebhookParser, WebhookHandler

# Message types and models
from linebot.v3.messaging.models import TextMessage, ImageMessage, FlexMessage, TemplateMessage

# Event types
from linebot.v3.webhooks.models import MessageEvent, FollowEvent, PostbackEvent

# Additional imports for specific functionality
from linebot.v3.oauth import ChannelAccessToken, AsyncChannelAccessToken
from linebot.v3.audience import ManageAudience, AsyncManageAudience
from linebot.v3.insight import Insight, AsyncInsight

Legacy API (deprecated):

# Legacy API - deprecated in v3.0
from linebot import LineBotApi, WebhookHandler
from linebot.models import MessageEvent, TextMessage, TextSendMessage

Basic Usage

Simple Echo Bot

from flask import Flask, request, abort
from linebot.v3 import WebhookHandler
from linebot.v3.messaging import MessagingApi, Configuration, TextMessage, ReplyMessageRequest
from linebot.v3.webhooks import MessageEvent
from linebot.v3.webhooks.models import TextMessageContent

app = Flask(__name__)

# Configure API client
configuration = Configuration(
    access_token='YOUR_CHANNEL_ACCESS_TOKEN'
)
messaging_api = MessagingApi(configuration)

# Initialize webhook handler
handler = WebhookHandler('YOUR_CHANNEL_SECRET')

@app.route("/callback", methods=['POST'])
def callback():
    # Verify signature and parse events
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    
    try:
        handler.handle(body, signature)
    except Exception as e:
        abort(400)
    
    return 'OK'

@handler.add(MessageEvent, message=TextMessageContent)
def handle_text_message(event):
    # Echo user's message
    reply_message = TextMessage(text=event.message.text)
    messaging_api.reply_message(
        ReplyMessageRequest(
            reply_token=event.reply_token,
            messages=[reply_message]
        )
    )

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

Async API Example

import asyncio
from linebot.v3.messaging import AsyncMessagingApi, Configuration, AsyncApiClient
from linebot.v3.messaging.models import TextMessage, PushMessageRequest

async def send_async_message():
    # Configure async API client
    configuration = Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')
    
    async with AsyncApiClient(configuration) as api_client:
        messaging_api = AsyncMessagingApi(api_client)
        
        # Send message asynchronously
        await messaging_api.push_message(
            PushMessageRequest(
                to="USER_ID",
                messages=[TextMessage(text="Hello from async API!")]
            )
        )

# Run async function
asyncio.run(send_async_message())

Rich Message Example

from linebot.v3.messaging.models import (
    FlexMessage, FlexBubble, FlexBox, FlexText, FlexButton, 
    FlexImage, PostbackAction
)

# Create a rich flex message
flex_message = FlexMessage(
    alt_text="Product Card",
    contents=FlexBubble(
        hero=FlexImage(
            url="https://example.com/product.jpg",
            size="full",
            aspect_ratio="20:13"
        ),
        body=FlexBox(
            layout="vertical",
            contents=[
                FlexText(text="Product Name", weight="bold", size="xl"),
                FlexText(text="$29.99", size="md", color="#666666"),
                FlexText(text="High quality product description here", wrap=True)
            ]
        ),
        footer=FlexBox(
            layout="vertical",
            contents=[
                FlexButton(
                    action=PostbackAction(
                        label="Buy Now",
                        data="action=buy&item_id=123"
                    ),
                    style="primary"
                )
            ]
        )
    )
)

Architecture

The LINE Bot SDK is organized around several key architectural patterns:

Dual API Architecture

  • Legacy API (v1/v2): Deprecated synchronous API with manual model definitions
  • v3 API: OpenAPI-generated clients with full type safety and async support

Module-Based Organization

v3 API is split into specialized modules:

  • Messaging: Core message sending and bot interactions
  • Webhooks: Event handling and callback processing
  • Audience: User targeting and audience management
  • Insight: Analytics and performance metrics
  • LIFF: LINE Front-end Framework integration
  • OAuth: Authentication and token management
  • Shop: Commerce and reward features

Client Patterns

  • Synchronous and asynchronous API clients for all modules
  • Consistent configuration and error handling across modules
  • Standardized request/response models with full type definitions

Capabilities

Core Messaging

Essential messaging functionality including sending text, rich media, and template messages. Supports push messaging, reply messaging, multicast, and broadcast with comprehensive message types and formatting options.

class MessagingApi:
    def reply_message(self, reply_message_request: ReplyMessageRequest) -> ReplyMessageResponse: ...
    def push_message(self, push_message_request: PushMessageRequest) -> PushMessageResponse: ...
    def multicast(self, multicast_request: MulticastRequest) -> dict: ...
    def broadcast(self, broadcast_request: BroadcastRequest) -> dict: ...
    def get_profile(self, user_id: str) -> UserProfileResponse: ...

Core Messaging

Webhook Event Handling

Comprehensive webhook processing for receiving and handling LINE platform events. Includes signature validation, event parsing, and handlers for all event types including messages, follows, postbacks, and group interactions.

class WebhookHandler:
    def handle(self, body: str, signature: str) -> None: ...
    def add(self, event_type, message=None): ...

class SignatureValidator:
    def validate(self, body: bytes, signature: str) -> bool: ...

class WebhookParser:
    def parse(self, body: str, signature: str) -> List[Event]: ...

Webhook Handling

Rich Messages and Templates

Advanced message formatting including Flex Messages, templates, quick replies, and interactive components. Supports complex layouts, carousels, image maps, and rich interactive experiences.

class FlexMessage:
    def __init__(self, alt_text: str, contents: FlexContainer): ...

class TemplateMessage:  
    def __init__(self, alt_text: str, template: Template): ...

class QuickReply:
    def __init__(self, items: List[QuickReplyItem]): ...

Rich Messages

Rich Menus

Interactive menu system for LINE bot interfaces. Supports menu creation, linking, batch operations, and alias management for enhanced user experience and navigation.

class MessagingApi:
    def create_rich_menu(self, rich_menu_request: RichMenuRequest) -> RichMenuIdResponse: ...
    def get_rich_menu_list(self) -> RichMenuListResponse: ...
    def set_rich_menu_image(self, rich_menu_id: str, body: bytes) -> dict: ...
    def link_rich_menu_id_to_user(self, user_id: str, rich_menu_id: str) -> dict: ...

Rich Menus

User and Profile Management

User profile access, group and room management, follower insights, and membership features. Includes demographic data access and user interaction analytics.

class MessagingApi:
    def get_profile(self, user_id: str) -> UserProfileResponse: ...
    def get_group_summary(self, group_id: str) -> GroupSummaryResponse: ...
    def get_room_member_count(self, room_id: str) -> RoomMemberCountResponse: ...
    def get_followers(self, start: str = None) -> GetFollowersResponse: ...

User Management

Advanced Features

The SDK includes additional capabilities for advanced use cases:

Audience Management: User targeting and segmentation for marketing campaigns through the linebot.v3.audience module.

Analytics and Insights: Bot performance metrics and user demographics via the linebot.v3.insight module.

LIFF Integration: LINE Front-end Framework support for web applications through the linebot.v3.liff module.

These advanced features follow the same patterns as the core modules with both synchronous and asynchronous clients available.

Authentication and OAuth

Channel access token management, OAuth flows, and authentication handling. Supports token issuance, verification, and lifecycle management for secure bot operations.

class ChannelAccessToken:
    def issue_channel_token(self, grant_type: str = "client_credentials") -> IssueChannelAccessTokenResponse: ...
    def verify_channel_token(self, access_token: str) -> VerifyChannelAccessTokenResponse: ...
    def revoke_channel_token(self, access_token: str) -> dict: ...

Authentication

Types and Models

Core Message Types

class Message:
    """Base message class"""
    type: str

class TextMessage(Message):
    text: str
    emojis: Optional[List[Emoji]] = None

class ImageMessage(Message):
    original_content_url: str
    preview_image_url: str

class VideoMessage(Message):  
    original_content_url: str
    preview_image_url: str

class AudioMessage(Message):
    original_content_url: str 
    duration: int

class LocationMessage(Message):
    title: str
    address: str
    latitude: float
    longitude: float

class StickerMessage(Message):
    package_id: str
    sticker_id: str

Configuration and Clients

class Configuration:
    def __init__(self, access_token: str, host: str = "https://api.line.me"): ...

class ApiClient:
    def __init__(self, configuration: Configuration): ...

class AsyncApiClient:
    def __init__(self, configuration: Configuration): ...

Event Types

class Event:
    """Base event class"""
    type: str
    timestamp: int 
    source: Source
    mode: str

class MessageEvent(Event):
    reply_token: str
    message: MessageContent

class FollowEvent(Event):
    reply_token: str

class PostbackEvent(Event):
    reply_token: str
    postback: PostbackContent

Error Handling

The SDK provides comprehensive error handling through OpenAPI-generated exceptions:

class ApiException(Exception):
    """Base API exception"""
    status: int
    reason: str
    body: str

class ApiTypeError(ApiException):
    """Type validation error"""

class ApiValueError(ApiException):  
    """Value validation error"""

Migration from Legacy API

When migrating from the legacy API to v3:

  1. Import Changes: Update imports from linebot to linebot.v3.* modules
  2. Client Initialization: Use Configuration and module-specific API clients
  3. Model Updates: Use OpenAPI-generated models with full type definitions
  4. Async Support: Consider async clients for better performance
  5. Error Handling: Update exception handling for OpenAPI exceptions