Comprehensive LINE API integration library with enhanced FlexMessage components (FlexSpan, FlexVideo), full type safety, multicast messaging, Flex Messages, Rich Menus, LINE Login, LIFF, and Mini Apps
Project description
LineKit - LINE API Integration Library
A comprehensive, type-safe Python library for integrating with LINE's APIs. Built with modern async/await patterns, full Pydantic type safety, and designed for production use.
๐ LATEST UPDATE (July 2025): Successfully completed comprehensive FlexMessage model updates with full LINE API specification compliance, added new FlexSpan and FlexVideo components, achieved 100% mypy strict mode compliance, and created production-ready pull request #3.
๐ Features
- ๐ Push Messages: Send messages directly to users
- ๐ข Multicast Messages: Efficiently send messages to multiple users (up to 500)
- ๐ฑ Multiple Message Types: Text, images, locations, stickers, and Flex messages
- ๐จ Flex Messages: Type-safe Flex Message creation with Pydantic models
- NEW: FlexSpan component for styled text within text components
- NEW: FlexVideo component for video content in hero blocks
- ENHANCED: Complete enum support and modern properties
- ๐ก Webhook Handling: Complete webhook integration with signature verification
- ๐ฏ Event Handlers: Decorator-based event handling for messages, postbacks, follows
- ๐ก๏ธ Security: LINE signature verification for webhook authenticity
- ๐ JSON Export: Export Flex Messages for LINE simulator testing
- ๐ Clipboard Integration: Automatic clipboard copy for testing
- ๐ Type Safety: Full Pydantic integration with comprehensive type hints
- โก Async-First: Built for high-performance async/await operations
- ๐ก๏ธ Error Handling: Comprehensive error handling with typed exceptions
- ๐ Retry Logic: Built-in retry mechanisms with exponential backoff
- ๐ Rate Limiting: Automatic rate limit handling
- ๐ Silent Notifications: Option to send messages without push notifications
- ๐ Analytics Integration: Custom aggregation units for message tracking
- ๐ Idempotent Requests: Retry keys to prevent duplicate message sending
๐ Installation
# Using pip
pip install linekit
# Using uv
uv pip install linekit
โก Quick Start
1. Configuration
Set up your LINE channel credentials:
# Environment variables
export LINE_CHANNEL_ACCESS_TOKEN="your_channel_access_token"
export LINE_CHANNEL_SECRET="your_channel_secret"
Or create a .env file:
LINE_CHANNEL_ACCESS_TOKEN=your_channel_access_token
LINE_CHANNEL_SECRET=your_channel_secret
2. Send a Push Message
import asyncio
from line_api import LineAPIConfig, LineMessagingClient, TextMessage
async def send_message():
# Load configuration
config = LineAPIConfig.from_env_file()
# Create message
message = TextMessage.create("Hello from LINE API! ๐")
# Send push message
async with LineMessagingClient(config) as client:
success = await client.push_message("USER_ID_HERE", [message])
if success:
print("Message sent successfully!")
# Run the example
asyncio.run(send_message())
3. Send Multicast Messages
import asyncio
import uuid
from line_api import LineAPIConfig, LineMessagingClient, TextMessage
async def send_multicast():
# Load configuration
config = LineAPIConfig.from_env_file()
# User IDs to send to (get these from webhook events)
user_ids = [
"U1234567890abcdef1234567890abcdef", # User ID 1
"U0987654321fedcba0987654321fedcba", # User ID 2
"Uabcdef1234567890abcdef1234567890", # User ID 3
]
# Create messages (up to 5 messages)
messages = [
TextMessage.create("๐ Hello everyone!"),
TextMessage.create("This message was sent to multiple users simultaneously."),
]
async with LineMessagingClient(config) as client:
# Basic multicast
success = await client.multicast_message(
user_ids=user_ids,
messages=messages,
)
if success:
print(f"โ
Multicast sent to {len(user_ids)} users!")
# Advanced multicast with options
success = await client.multicast_message(
user_ids=user_ids,
messages=[TextMessage.create("๐ Campaign message")],
notification_disabled=False, # Users get push notifications
custom_aggregation_units=["summer_campaign_2024"], # For analytics
retry_key=str(uuid.uuid4()), # For request idempotency
)
# Silent multicast (no push notifications)
success = await client.multicast_message(
user_ids=user_ids,
messages=[TextMessage.create("๐ Silent update")],
notification_disabled=True, # No push notifications
)
# Run the example
asyncio.run(send_multicast())
4. Create Flex Messages
from line_api import (
FlexBox,
FlexBubble,
FlexLayout,
FlexMessage,
FlexText,
FlexSpan,
FlexTextWeight,
print_flex_json,
)
# Create a simple flex message
def create_welcome_message():
# Create text with styled spans
title = FlexText.create(
text="Rich text with spans",
contents=[
FlexSpan.create("Welcome", weight=FlexTextWeight.BOLD, color="#1E3A8A"),
FlexSpan.create(" to our ", color="#666666"),
FlexSpan.create("LINE API Library!", weight=FlexTextWeight.BOLD, color="#00C300")
]
)
subtitle = FlexText.create(
text="Thank you for using our comprehensive LINE integration library!",
wrap=True,
color="#555555",
margin="md"
)
# Create a vertical box layout
body = FlexBox.create(
layout=FlexLayout.VERTICAL,
contents=[title, subtitle],
spacing="md",
padding_all="20px",
)
# Create bubble
bubble = FlexBubble.create(body=body)
# Create flex message
return FlexMessage.create(
alt_text="Welcome Message",
contents=bubble,
)
# Create and export to JSON for testing
message = create_welcome_message()
print_flex_json(message, "Welcome Message")
# JSON is automatically copied to clipboard!
# Paste it into https://developers.line.biz/flex-simulator/
5. Handle LINE Webhooks
from fastapi import FastAPI, Request
from line_api import (
LineAPIConfig,
LineWebhookHandler,
LineMessagingClient,
LineMessageEvent,
TextMessage,
)
app = FastAPI()
# Initialize components
config = LineAPIConfig()
webhook_handler = LineWebhookHandler(config)
messaging_client = LineMessagingClient(config)
# Register event handlers using decorators
@webhook_handler.message_handler
async def handle_message(event: LineMessageEvent) -> None:
"""Handle incoming text messages."""
if event.message.type == "text":
user_text = event.message.text
# Create smart responses
if user_text.lower() in ["hello", "hi", "hey"]:
response = "Hello! How can I help you today?"
elif user_text.lower() == "help":
response = "Available commands: hello, help, status"
else:
response = f"You said: {user_text}"
# Reply to user
if event.replyToken:
await messaging_client.reply_message(
reply_token=event.replyToken,
messages=[TextMessage(text=response)]
)
@webhook_handler.follow_handler
async def handle_follow(event) -> None:
"""Welcome new followers."""
welcome_msg = "๐ Welcome! Thanks for adding me as a friend!"
reply_token = getattr(event, "replyToken", None)
if reply_token:
await messaging_client.reply_message(
reply_token=reply_token,
messages=[TextMessage(text=welcome_msg)]
)
# FastAPI webhook endpoint
@app.post("/webhook")
async def webhook_endpoint(request: Request):
"""Receive webhooks from LINE Platform."""
body = await request.body()
signature = request.headers.get("X-Line-Signature")
payload_dict = await request.json()
# Process webhook with automatic signature verification
response = await webhook_handler.handle_webhook(
request_body=body,
signature=signature,
payload_dict=payload_dict
)
return response.model_dump()
# Run with: uvicorn your_app:app --host 0.0.0.0 --port 8000
๐ค Contributing
Contributions are welcome! Please read our contributing guidelines to get started.
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
โ What's Working
- โ Core configuration management with Pydantic
- โ LINE Messaging API integration
- โ Text message support with type safety
- โ
Multicast Messages: Complete multicast messaging with advanced options
- โ Send to up to 500 users simultaneously
- โ Silent notifications support
- โ Custom aggregation units for analytics
- โ Retry keys for idempotent requests
- โ Flex Messages: Complete type-safe Flex Message creation
- โ JSON Export: Export to LINE Flex Message Simulator
- โ Clipboard Integration: Automatic copy-to-clipboard functionality
- โ Webhook Handling: Complete webhook integration with FastAPI
- โ Event Processing: Message, postback, follow/unfollow event handling
- โ Signature Verification: LINE webhook signature verification for security
- โ Type-Safe Events: Pydantic models for all LINE webhook event types
- โ
Modern Python packaging with
pyproject.toml - โ Development tools (ruff, mypy, pytest)
- โ Comprehensive test framework
- โ Async-first architecture
๐ง To Be Implemented
The following modules will be implemented:
- rich_menu/: Rich Menu management
- login/: LINE Login OAuth2 authentication
- liff/: LIFF (LINE Front-end Framework) integration
- advanced_messaging/: Image, video, audio message types
๐ฆ Installation
Development Setup
git clone <your-repository>
cd line-api
uv sync --dev
Basic Installation
pip install -e .
๐ Quick Start
Here's how to get started with the basic LineAPI class:
from line_api import LineAPI
# Initialize with your credentials
line_api = LineAPI(
channel_access_token="YOUR_CHANNEL_ACCESS_TOKEN",
channel_secret="YOUR_CHANNEL_SECRET"
)
# Use the client in an async context
async with line_api as client:
# Your API calls will go here
print(f"Client ready: {client}")
๐งช Testing
Run the current test suite:
# Using the test runner
python test_runner.py
# Using pytest directly
pytest tests/
# With coverage
python test_runner.py --coverage
๐ง Development
Setup Validation
python setup_validation.py
Run Examples
python examples/basic_example.py
python comprehensive_demo.py
Code Quality
# Format and lint
ruff format .
ruff check .
# Type checking
mypy line_api/
๐๏ธ Project Structure
line-api/
โโโ line_api/ # Main package
โ โโโ __init__.py # Package exports
โ โโโ core/ # Core functionality
โ โ โโโ client.py # Main LineAPI client
โ โโโ messaging/ # Messaging API
โ โโโ flex_messages/ # Flex Message components
โ โโโ rich_menu/ # Rich Menu management
โ โโโ login/ # LINE Login
โ โโโ liff/ # LIFF integration
โ
โโโ tests/ # Test suite
โ โโโ __init__.py
โ โโโ conftest.py # Test configuration
โ โโโ test_core.py # Core module tests
โ
โโโ examples/ # Usage examples
โ โโโ basic_usage.py # Basic API usage
โ
โโโ docs/ # Documentation
โโโ scripts/ # Development scripts
โ
โโโ .github/ # GitHub configurations
โโโ .gitignore # Git ignore rules
โโโ pyproject.toml # Project configuration
โโโ README.md # This file
โโโ CHANGELOG.md # Version history
โโโ CONTRIBUTING.md # Contribution guidelines
โโโ CODE_OF_CONDUCT.md # Community guidelines
๐ฏ Project Goals
- Type Safety: Full Pydantic v2 integration with strict type checking
- Async-First: Built with
asynciofor high performance - Developer Experience: Excellent IDE support with complete type hints
- Comprehensive: Covers all major LINE platform features
- Well-Tested: High test coverage with property-based testing
- Modular: Independent components that work together seamlessly
๐ง Implementation Status
โ Completed
- Core configuration management with Pydantic
- LINE Messaging API with async support
- Text message creation and sending
- Flex Messages: Complete type-safe Flex Message creation
- JSON Export utilities: Export to LINE Flex Message Simulator
- Clipboard integration: Automatic copy functionality
- Webhook Integration: Complete webhook handling with FastAPI
- Event Processing: Message, postback, follow/unfollow events
- Signature Verification: LINE webhook signature verification
- Type-Safe Models: Pydantic models for all LINE event types
- Comprehensive test infrastructure
- Development tooling setup
๐ In Progress
- Advanced message types (images, videos, audio)
- Rate limiting enhancements
๐ Planned
- Rich Menu management
- LINE Login integration
- LIFF SDK integration
๐ค How to Contribute
We welcome contributions! Please see our Contributing Guidelines for details on how to get started.
- Check the open issues
- Fork the repository and create your feature branch
- Write tests for your changes
- Ensure all tests pass and code is properly formatted
- Submit a pull request with a clear description
Please read our Code of Conduct before contributing.
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Resources
Official LINE Documentation
- LINE Developers Portal
- Messaging API Reference
- LINE Login Documentation
- LIFF Documentation
- Flex Message Simulator
Related Projects
Ready to build the future of LINE API integration! ๐
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file linekit-2.0.1.tar.gz.
File metadata
- Download URL: linekit-2.0.1.tar.gz
- Upload date:
- Size: 171.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12360185bc70890079c1fe571d78cae0fa6758748ae102b1458b398c10f46861
|
|
| MD5 |
80cd8253f3c4f3cc078aa17d5359b72e
|
|
| BLAKE2b-256 |
df41cb23bbdf14928d00f4ef944952c379a47077cc53dfe0f83c0185f43a1564
|
File details
Details for the file linekit-2.0.1-py3-none-any.whl.
File metadata
- Download URL: linekit-2.0.1-py3-none-any.whl
- Upload date:
- Size: 35.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3702a06247a03f5e8c91d150638943ed4749fce1d8314e3d2e6404ea24ef5234
|
|
| MD5 |
a04165ce2dd4425b5689d0084132733c
|
|
| BLAKE2b-256 |
6ec3b54eb755e07e5e48bef88090145f2421e71082987b0eabe3530426416a45
|