LINE Messaging API SDK for Python with comprehensive bot development capabilities including messaging, webhooks, and platform integrations.
npx @tessl/cli install tessl/pypi-line-bot-sdk@3.19.0A 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.
pip install line-bot-sdkModern 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, AsyncInsightLegacy API (deprecated):
# Legacy API - deprecated in v3.0
from linebot import LineBotApi, WebhookHandler
from linebot.models import MessageEvent, TextMessage, TextSendMessagefrom 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()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())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"
)
]
)
)
)The LINE Bot SDK is organized around several key architectural patterns:
v3 API is split into specialized modules:
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: ...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]: ...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]): ...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: ...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: ...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.
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: ...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: strclass 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): ...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: PostbackContentThe 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"""When migrating from the legacy API to v3:
linebot to linebot.v3.* modulesConfiguration and module-specific API clients