LINE Messaging API SDK for Python with comprehensive bot development capabilities including messaging, webhooks, and platform integrations.
—
Comprehensive webhook processing for receiving and handling LINE platform events. Includes signature validation, event parsing, and handlers for all event types including messages, user interactions, and bot lifecycle events.
Primary interface for processing LINE webhook callbacks with automatic signature validation and event dispatching.
class WebhookHandler:
def __init__(self, channel_secret: str):
"""
Initialize webhook handler with channel secret for signature validation.
Args:
channel_secret: LINE channel secret for webhook signature validation
"""
def handle(self, body: str, signature: str) -> None:
"""
Process webhook callback by validating signature and dispatching events.
Args:
body: Raw webhook request body as string
signature: X-Line-Signature header value
Raises:
LineBotApiError: If signature validation fails
"""
def add(self, event_type, message=None):
"""
Decorator for registering event handlers.
Args:
event_type: Event class to handle (MessageEvent, FollowEvent, etc.)
message: Optional message type filter for MessageEvent
Returns:
Decorator function for handler registration
"""Cryptographic validation of webhook signatures to ensure message authenticity and security.
class SignatureValidator:
def __init__(self, channel_secret: str):
"""Initialize validator with channel secret."""
def validate(self, body: bytes, signature: str) -> bool:
"""
Validate webhook signature against request body.
Args:
body: Raw request body as bytes
signature: X-Line-Signature header value without 'base64=' prefix
Returns:
bool: True if signature is valid, False otherwise
"""Direct webhook payload parsing for custom event processing workflows.
class WebhookParser:
def __init__(self, channel_secret: str):
"""Initialize parser with channel secret for validation."""
def parse(self, body: str, signature: str) -> List[Event]:
"""
Parse webhook payload into event objects after signature validation.
Args:
body: Raw webhook request body as string
signature: X-Line-Signature header value
Returns:
List[Event]: Parsed event objects
Raises:
LineBotApiError: If signature validation fails
"""Container for raw webhook data and metadata.
class WebhookPayload:
def __init__(self, events: List[Event]):
"""
Initialize payload with parsed events.
Args:
events: List of parsed event objects
"""
@property
def events(self) -> List[Event]:
"""Get list of events in the payload."""class Event:
"""Base event class for all LINE webhook events"""
type: str
timestamp: int
source: Source
mode: str
webhook_event_id: str
delivery_context: DeliveryContext
class CallbackRequest:
"""Root webhook callback request"""
destination: str
events: List[Event]Events triggered when users send messages to the bot.
class MessageEvent(Event):
"""User sent a message to the bot"""
reply_token: str
message: MessageContent
class MessageContent:
"""Base message content"""
id: str
type: str
class TextMessageContent(MessageContent):
"""Text message content"""
text: str
emojis: Optional[List[Emoji]] = None
mention: Optional[Mention] = None
class ImageMessageContent(MessageContent):
"""Image message content"""
content_provider: ContentProvider
image_set: Optional[ImageSet] = None
class VideoMessageContent(MessageContent):
"""Video message content"""
duration: int
content_provider: ContentProvider
class AudioMessageContent(MessageContent):
"""Audio message content"""
duration: int
content_provider: ContentProvider
class LocationMessageContent(MessageContent):
"""Location message content"""
title: str
address: str
latitude: float
longitude: float
class StickerMessageContent(MessageContent):
"""Sticker message content"""
package_id: str
sticker_id: str
sticker_resource_type: str
keywords: Optional[List[str]] = None
text: Optional[str] = None
class FileMessageContent(MessageContent):
"""File message content"""
file_name: str
file_size: intEvents triggered by user interactions with the bot and platform features.
class FollowEvent(Event):
"""User followed the bot"""
reply_token: str
follow_detail: FollowDetail
class UnfollowEvent(Event):
"""User unfollowed the bot"""
pass
class JoinEvent(Event):
"""Bot was added to a group or room"""
reply_token: str
joined_members: JoinedMembers
class LeaveEvent(Event):
"""Bot was removed from a group or room"""
pass
class PostbackEvent(Event):
"""User triggered a postback action"""
reply_token: str
postback: PostbackContent
class BeaconEvent(Event):
"""User interacted with a LINE Beacon"""
reply_token: str
beacon: BeaconContent
class AccountLinkEvent(Event):
"""Account linking event occurred"""
reply_token: str
link: LinkContent
class UnsendEvent(Event):
"""User unsent a message"""
unsend: UnsendDetail
class VideoPlayCompleteEvent(Event):
"""User finished watching a video message"""
reply_token: str
video_play_complete: VideoPlayCompleteEvents related to group and room member management.
class MemberJoinedEvent(Event):
"""Members joined a group or room"""
reply_token: str
joined_members: JoinedMembers
class MemberLeftEvent(Event):
"""Members left a group or room"""
left_members: LeftMembersEvents related to bot activation, suspension, and lifecycle management.
class ActivatedEvent(Event):
"""Bot was activated"""
pass
class DeactivatedEvent(Event):
"""Bot was deactivated"""
pass
class BotSuspendedEvent(Event):
"""Bot account was suspended"""
pass
class BotResumedEvent(Event):
"""Bot account suspension was lifted"""
passEvents related to LINE membership features and subscriptions.
class MembershipEvent(Event):
"""Membership-related event occurred"""
reply_token: str
membership: MembershipContent
class JoinedMembershipContent(MembershipContent):
"""User joined a membership"""
pass
class LeftMembershipContent(MembershipContent):
"""User left a membership"""
pass
class RenewedMembershipContent(MembershipContent):
"""User renewed a membership"""
passEvents related to LINE module functionality and attachments.
class ModuleEvent(Event):
"""Module-related event occurred"""
reply_token: str
module: ModuleContent
class AttachedModuleContent(ModuleContent):
"""Module was attached"""
pass
class DetachedModuleContent(ModuleContent):
"""Module was detached"""
passEvents related to message delivery and push notification completion.
class PnpDeliveryCompletionEvent(Event):
"""Push notification delivery completed"""
delivery: PnpDeliverySource information identifying where events originated.
class Source:
"""Base event source"""
type: str
class UserSource(Source):
"""Event from individual user"""
user_id: str
class GroupSource(Source):
"""Event from group chat"""
group_id: str
user_id: Optional[str] = None
class RoomSource(Source):
"""Event from room chat"""
room_id: str
user_id: Optional[str] = Noneclass PostbackContent:
data: str
params: Optional[dict] = Noneclass BeaconContent:
hwid: str
type: str
device_message: Optional[bytes] = Noneclass Mention:
mentionees: List[Mentionee]
class Mentionee:
"""Base mentionee class"""
type: str
class UserMentionee(Mentionee):
"""Specific user mentioned"""
user_id: str
class AllMentionee(Mentionee):
"""All users mentioned"""
passclass ContentProvider:
type: str # "line" or "external"
original_content_url: Optional[str] = None
preview_image_url: Optional[str] = Nonefrom flask import Flask, request, abort
from linebot.v3 import WebhookHandler
from linebot.v3.webhooks.models import MessageEvent, TextMessageContent
app = Flask(__name__)
handler = WebhookHandler('YOUR_CHANNEL_SECRET')
@app.route("/callback", methods=['POST'])
def callback():
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):
print(f"Received text: {event.message.text}")
print(f"From user: {event.source.user_id}")from linebot.v3.webhooks.models import (
FollowEvent, PostbackEvent, BeaconEvent,
ImageMessageContent, LocationMessageContent
)
@handler.add(FollowEvent)
def handle_follow(event):
print(f"New follower: {event.source.user_id}")
# Send welcome message using messaging API
@handler.add(PostbackEvent)
def handle_postback(event):
postback_data = event.postback.data
print(f"Postback received: {postback_data}")
# Process postback action
@handler.add(MessageEvent, message=ImageMessageContent)
def handle_image(event):
message_id = event.message.id
print(f"Image received: {message_id}")
# Download and process image using MessagingApiBlob
@handler.add(MessageEvent, message=LocationMessageContent)
def handle_location(event):
location = event.message
print(f"Location: {location.title} at {location.latitude}, {location.longitude}")
@handler.add(BeaconEvent)
def handle_beacon(event):
beacon = event.beacon
print(f"Beacon interaction: {beacon.hwid} - {beacon.type}")from linebot.v3 import WebhookParser, SignatureValidator
# Initialize components
validator = SignatureValidator('YOUR_CHANNEL_SECRET')
parser = WebhookParser('YOUR_CHANNEL_SECRET')
def process_webhook(body_bytes, signature):
# Manual signature validation
if not validator.validate(body_bytes, signature):
raise ValueError("Invalid signature")
# Parse events directly
body_str = body_bytes.decode('utf-8')
events = parser.parse(body_str, signature)
for event in events:
if isinstance(event, MessageEvent):
print(f"Message from {event.source.user_id}: {event.message.text}")
elif isinstance(event, FollowEvent):
print(f"New follower: {event.source.user_id}")from linebot.v3.webhooks.models import (
JoinEvent, LeaveEvent, MemberJoinedEvent, MemberLeftEvent,
GroupSource, RoomSource
)
@handler.add(JoinEvent)
def handle_join(event):
if isinstance(event.source, GroupSource):
print(f"Bot joined group: {event.source.group_id}")
elif isinstance(event.source, RoomSource):
print(f"Bot joined room: {event.source.room_id}")
@handler.add(MemberJoinedEvent)
def handle_member_joined(event):
joined_users = event.joined_members.members
for member in joined_users:
print(f"New member: {member.user_id}")
@handler.add(LeaveEvent)
def handle_leave(event):
print("Bot was removed from chat")Install with Tessl CLI
npx tessl i tessl/pypi-line-bot-sdk