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.00
# LINE Bot SDK for Python
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: line-bot-sdk
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install line-bot-sdk`
10
- **Python Requirements**: >= 3.9.0
11
12
## Core Imports
13
14
Modern v3 API (recommended):
15
16
```python
17
# Messaging API
18
from linebot.v3.messaging import MessagingApi, AsyncMessagingApi, Configuration, ApiClient, AsyncApiClient
19
20
# Webhook handling
21
from linebot.v3 import SignatureValidator, WebhookParser, WebhookHandler
22
23
# Message types and models
24
from linebot.v3.messaging.models import TextMessage, ImageMessage, FlexMessage, TemplateMessage
25
26
# Event types
27
from linebot.v3.webhooks.models import MessageEvent, FollowEvent, PostbackEvent
28
29
# Additional imports for specific functionality
30
from linebot.v3.oauth import ChannelAccessToken, AsyncChannelAccessToken
31
from linebot.v3.audience import ManageAudience, AsyncManageAudience
32
from linebot.v3.insight import Insight, AsyncInsight
33
```
34
35
Legacy API (deprecated):
36
37
```python
38
# Legacy API - deprecated in v3.0
39
from linebot import LineBotApi, WebhookHandler
40
from linebot.models import MessageEvent, TextMessage, TextSendMessage
41
```
42
43
## Basic Usage
44
45
### Simple Echo Bot
46
47
```python
48
from flask import Flask, request, abort
49
from linebot.v3 import WebhookHandler
50
from linebot.v3.messaging import MessagingApi, Configuration, TextMessage, ReplyMessageRequest
51
from linebot.v3.webhooks import MessageEvent
52
from linebot.v3.webhooks.models import TextMessageContent
53
54
app = Flask(__name__)
55
56
# Configure API client
57
configuration = Configuration(
58
access_token='YOUR_CHANNEL_ACCESS_TOKEN'
59
)
60
messaging_api = MessagingApi(configuration)
61
62
# Initialize webhook handler
63
handler = WebhookHandler('YOUR_CHANNEL_SECRET')
64
65
@app.route("/callback", methods=['POST'])
66
def callback():
67
# Verify signature and parse events
68
signature = request.headers['X-Line-Signature']
69
body = request.get_data(as_text=True)
70
71
try:
72
handler.handle(body, signature)
73
except Exception as e:
74
abort(400)
75
76
return 'OK'
77
78
@handler.add(MessageEvent, message=TextMessageContent)
79
def handle_text_message(event):
80
# Echo user's message
81
reply_message = TextMessage(text=event.message.text)
82
messaging_api.reply_message(
83
ReplyMessageRequest(
84
reply_token=event.reply_token,
85
messages=[reply_message]
86
)
87
)
88
89
if __name__ == "__main__":
90
app.run()
91
```
92
93
### Async API Example
94
95
```python
96
import asyncio
97
from linebot.v3.messaging import AsyncMessagingApi, Configuration, AsyncApiClient
98
from linebot.v3.messaging.models import TextMessage, PushMessageRequest
99
100
async def send_async_message():
101
# Configure async API client
102
configuration = Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')
103
104
async with AsyncApiClient(configuration) as api_client:
105
messaging_api = AsyncMessagingApi(api_client)
106
107
# Send message asynchronously
108
await messaging_api.push_message(
109
PushMessageRequest(
110
to="USER_ID",
111
messages=[TextMessage(text="Hello from async API!")]
112
)
113
)
114
115
# Run async function
116
asyncio.run(send_async_message())
117
```
118
119
### Rich Message Example
120
121
```python
122
from linebot.v3.messaging.models import (
123
FlexMessage, FlexBubble, FlexBox, FlexText, FlexButton,
124
FlexImage, PostbackAction
125
)
126
127
# Create a rich flex message
128
flex_message = FlexMessage(
129
alt_text="Product Card",
130
contents=FlexBubble(
131
hero=FlexImage(
132
url="https://example.com/product.jpg",
133
size="full",
134
aspect_ratio="20:13"
135
),
136
body=FlexBox(
137
layout="vertical",
138
contents=[
139
FlexText(text="Product Name", weight="bold", size="xl"),
140
FlexText(text="$29.99", size="md", color="#666666"),
141
FlexText(text="High quality product description here", wrap=True)
142
]
143
),
144
footer=FlexBox(
145
layout="vertical",
146
contents=[
147
FlexButton(
148
action=PostbackAction(
149
label="Buy Now",
150
data="action=buy&item_id=123"
151
),
152
style="primary"
153
)
154
]
155
)
156
)
157
)
158
```
159
160
## Architecture
161
162
The LINE Bot SDK is organized around several key architectural patterns:
163
164
### Dual API Architecture
165
- **Legacy API (v1/v2)**: Deprecated synchronous API with manual model definitions
166
- **v3 API**: OpenAPI-generated clients with full type safety and async support
167
168
### Module-Based Organization
169
v3 API is split into specialized modules:
170
- **Messaging**: Core message sending and bot interactions
171
- **Webhooks**: Event handling and callback processing
172
- **Audience**: User targeting and audience management
173
- **Insight**: Analytics and performance metrics
174
- **LIFF**: LINE Front-end Framework integration
175
- **OAuth**: Authentication and token management
176
- **Shop**: Commerce and reward features
177
178
### Client Patterns
179
- Synchronous and asynchronous API clients for all modules
180
- Consistent configuration and error handling across modules
181
- Standardized request/response models with full type definitions
182
183
## Capabilities
184
185
### Core Messaging
186
187
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.
188
189
```python { .api }
190
class MessagingApi:
191
def reply_message(self, reply_message_request: ReplyMessageRequest) -> ReplyMessageResponse: ...
192
def push_message(self, push_message_request: PushMessageRequest) -> PushMessageResponse: ...
193
def multicast(self, multicast_request: MulticastRequest) -> dict: ...
194
def broadcast(self, broadcast_request: BroadcastRequest) -> dict: ...
195
def get_profile(self, user_id: str) -> UserProfileResponse: ...
196
```
197
198
[Core Messaging](./messaging.md)
199
200
### Webhook Event Handling
201
202
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.
203
204
```python { .api }
205
class WebhookHandler:
206
def handle(self, body: str, signature: str) -> None: ...
207
def add(self, event_type, message=None): ...
208
209
class SignatureValidator:
210
def validate(self, body: bytes, signature: str) -> bool: ...
211
212
class WebhookParser:
213
def parse(self, body: str, signature: str) -> List[Event]: ...
214
```
215
216
[Webhook Handling](./webhooks.md)
217
218
### Rich Messages and Templates
219
220
Advanced message formatting including Flex Messages, templates, quick replies, and interactive components. Supports complex layouts, carousels, image maps, and rich interactive experiences.
221
222
```python { .api }
223
class FlexMessage:
224
def __init__(self, alt_text: str, contents: FlexContainer): ...
225
226
class TemplateMessage:
227
def __init__(self, alt_text: str, template: Template): ...
228
229
class QuickReply:
230
def __init__(self, items: List[QuickReplyItem]): ...
231
```
232
233
[Rich Messages](./rich-messages.md)
234
235
### Rich Menus
236
237
Interactive menu system for LINE bot interfaces. Supports menu creation, linking, batch operations, and alias management for enhanced user experience and navigation.
238
239
```python { .api }
240
class MessagingApi:
241
def create_rich_menu(self, rich_menu_request: RichMenuRequest) -> RichMenuIdResponse: ...
242
def get_rich_menu_list(self) -> RichMenuListResponse: ...
243
def set_rich_menu_image(self, rich_menu_id: str, body: bytes) -> dict: ...
244
def link_rich_menu_id_to_user(self, user_id: str, rich_menu_id: str) -> dict: ...
245
```
246
247
[Rich Menus](./rich-menus.md)
248
249
### User and Profile Management
250
251
User profile access, group and room management, follower insights, and membership features. Includes demographic data access and user interaction analytics.
252
253
```python { .api }
254
class MessagingApi:
255
def get_profile(self, user_id: str) -> UserProfileResponse: ...
256
def get_group_summary(self, group_id: str) -> GroupSummaryResponse: ...
257
def get_room_member_count(self, room_id: str) -> RoomMemberCountResponse: ...
258
def get_followers(self, start: str = None) -> GetFollowersResponse: ...
259
```
260
261
[User Management](./user-management.md)
262
263
### Advanced Features
264
265
The SDK includes additional capabilities for advanced use cases:
266
267
**Audience Management**: User targeting and segmentation for marketing campaigns through the `linebot.v3.audience` module.
268
269
**Analytics and Insights**: Bot performance metrics and user demographics via the `linebot.v3.insight` module.
270
271
**LIFF Integration**: LINE Front-end Framework support for web applications through the `linebot.v3.liff` module.
272
273
These advanced features follow the same patterns as the core modules with both synchronous and asynchronous clients available.
274
275
### Authentication and OAuth
276
277
Channel access token management, OAuth flows, and authentication handling. Supports token issuance, verification, and lifecycle management for secure bot operations.
278
279
```python { .api }
280
class ChannelAccessToken:
281
def issue_channel_token(self, grant_type: str = "client_credentials") -> IssueChannelAccessTokenResponse: ...
282
def verify_channel_token(self, access_token: str) -> VerifyChannelAccessTokenResponse: ...
283
def revoke_channel_token(self, access_token: str) -> dict: ...
284
```
285
286
[Authentication](./authentication.md)
287
288
## Types and Models
289
290
### Core Message Types
291
292
```python { .api }
293
class Message:
294
"""Base message class"""
295
type: str
296
297
class TextMessage(Message):
298
text: str
299
emojis: Optional[List[Emoji]] = None
300
301
class ImageMessage(Message):
302
original_content_url: str
303
preview_image_url: str
304
305
class VideoMessage(Message):
306
original_content_url: str
307
preview_image_url: str
308
309
class AudioMessage(Message):
310
original_content_url: str
311
duration: int
312
313
class LocationMessage(Message):
314
title: str
315
address: str
316
latitude: float
317
longitude: float
318
319
class StickerMessage(Message):
320
package_id: str
321
sticker_id: str
322
```
323
324
### Configuration and Clients
325
326
```python { .api }
327
class Configuration:
328
def __init__(self, access_token: str, host: str = "https://api.line.me"): ...
329
330
class ApiClient:
331
def __init__(self, configuration: Configuration): ...
332
333
class AsyncApiClient:
334
def __init__(self, configuration: Configuration): ...
335
```
336
337
### Event Types
338
339
```python { .api }
340
class Event:
341
"""Base event class"""
342
type: str
343
timestamp: int
344
source: Source
345
mode: str
346
347
class MessageEvent(Event):
348
reply_token: str
349
message: MessageContent
350
351
class FollowEvent(Event):
352
reply_token: str
353
354
class PostbackEvent(Event):
355
reply_token: str
356
postback: PostbackContent
357
```
358
359
## Error Handling
360
361
The SDK provides comprehensive error handling through OpenAPI-generated exceptions:
362
363
```python { .api }
364
class ApiException(Exception):
365
"""Base API exception"""
366
status: int
367
reason: str
368
body: str
369
370
class ApiTypeError(ApiException):
371
"""Type validation error"""
372
373
class ApiValueError(ApiException):
374
"""Value validation error"""
375
```
376
377
## Migration from Legacy API
378
379
When migrating from the legacy API to v3:
380
381
1. **Import Changes**: Update imports from `linebot` to `linebot.v3.*` modules
382
2. **Client Initialization**: Use `Configuration` and module-specific API clients
383
3. **Model Updates**: Use OpenAPI-generated models with full type definitions
384
4. **Async Support**: Consider async clients for better performance
385
5. **Error Handling**: Update exception handling for OpenAPI exceptions