Skip to main content

Comprehensive LINE API integration library with Flex Messages, Rich Menus, LINE Login, LIFF, and Mini Apps

Project description

LineKit - LINE API Integration Library

Python 3.9+ License: MIT Code style: ruff

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.

๐Ÿš€ Features

  • ๐Ÿš€ Push Messages: Send messages directly to users
  • ๐Ÿ“ฑ Multiple Message Types: Text, images, locations, stickers, and Flex messages
  • ๐ŸŽจ Flex Messages: Type-safe Flex Message creation with Pydantic models
  • ๏ฟฝ 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

๐Ÿ›  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. Create Flex Messages

from line_api import (
    FlexBox,
    FlexBubble,
    FlexLayout,
    FlexMessage,
    FlexText,
    print_flex_json,
)

# Create a simple flex message
def create_welcome_message():
    # Create text components
    title = FlexText.create(
        text="๐ŸŽ‰ Welcome!",
        weight="bold",
        size="xl",
        color="#1E3A8A",
    )

    subtitle = FlexText.create(
        text="Thank you for using our LINE API Integration Library!",
        wrap=True,
        color="#555555",
    )

    # 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/

4. 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
  • โœ… 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 asyncio for 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.

  1. Check the open issues
  2. Fork the repository and create your feature branch
  3. Write tests for your changes
  4. Ensure all tests pass and code is properly formatted
  5. 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

Related Projects


Ready to build the future of LINE API integration! ๐Ÿš€

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

linekit-1.0.1.tar.gz (111.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

linekit-1.0.1-py3-none-any.whl (32.9 kB view details)

Uploaded Python 3

File details

Details for the file linekit-1.0.1.tar.gz.

File metadata

  • Download URL: linekit-1.0.1.tar.gz
  • Upload date:
  • Size: 111.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for linekit-1.0.1.tar.gz
Algorithm Hash digest
SHA256 14f2534cdb6dc549d11c2580047e2741b717206d177b697c7ec28c7c33123b36
MD5 254a57b1b250576a29d3847177783ae9
BLAKE2b-256 af1d1b783786ec044e94421c4ed64f3b49559a7c280d7cd9c7cbfed531f8f71b

See more details on using hashes here.

File details

Details for the file linekit-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: linekit-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 32.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for linekit-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ca9e1cdec925ca0c410fc239e150f0f84c5b5f529150830921d6cdc7d23bb220
MD5 630650f08364f104659651f432f515ad
BLAKE2b-256 55870d4b078e45492bf69a00d1e6515ced61810d59776a73975ad6f3575ffd6e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page