Skip to main content

pig-messenger

PyPI version Python

Messenger abstraction library for building bots across optional platform adapters.

English | 简体中文

Features

  • Universal Abstractions: Single API for Telegram, Slack, Discord, WhatsApp, Feishu
  • Streaming Support: 3-strategy streaming (draft/edit/batch) for real-time responses
  • Distributed State: Redis-backed state management with agent locking and follow-up queues
  • Lifecycle Handling: Retry paths, error handling, and graceful shutdown
  • Type Safe: Full type hints and dataclass-based models

Installation

pip install pig-messenger

Optional dependencies:

pip install pig-messenger[redis]       # For distributed state
pip install pig-messenger[encryption]  # For credential encryption
pip install pig-messenger[telegram]    # For Telegram adapter
pip install pig-messenger[slack]       # For Slack adapter
pip install pig-messenger[discord]     # For Discord adapter
pip install pig-messenger[whatsapp]    # For WhatsApp adapter
pip install pig-messenger[feishu]      # For Feishu adapter
pip install pig-messenger[all]         # All adapters

Quick Start

from pig_messenger import MessengerManager, MessengerRegistry, MessengerType
from pig_messenger.adapters.telegram import TelegramMessengerAdapter


# Register adapter
@MessengerRegistry.register(MessengerType.TELEGRAM)
class MyTelegramAdapter(TelegramMessengerAdapter):
    pass


# Create manager
def agent_factory(message, thread):
    return f"Echo: {message.text}"


manager = MessengerManager(agent_factory=agent_factory)

# Handle events
await manager.handle_event(MessengerType.TELEGRAM, raw_event, adapter=adapter)

Architecture

Core Components

  • BaseMessengerAdapter: Abstract base for platform adapters
  • MessengerThread: Unified interface for sending messages with streaming
  • MessengerManager: Orchestrates message lifecycle with agent execution
  • MessengerState: Redis-backed distributed state management
  • MessengerRegistry: Decorator-based adapter registration

Platform Adapters

Platform Features Char Limit
Telegram Draft streaming, file uploads 4096
Slack Block Kit, reactions, markdown conversion 3500
Discord Threads, reactions, embeds 2000
WhatsApp Twilio-based 1600
Feishu Card messages, streaming updates Custom

Streaming Strategies

MessengerThread automatically selects the best streaming strategy:

  1. Draft Streaming (Telegram): Native draft frames with final commit
  2. Edit Streaming (Slack, Discord): Post initial, edit at intervals, auto-split on overflow
  3. Batch Fallback: Collect all chunks, split, post sequentially

Configuration Examples

Telegram

from pig_messenger.adapters.telegram import TelegramMessengerAdapter, TelegramConfig

config = TelegramConfig.from_env()  # Load from environment
adapter = TelegramMessengerAdapter(config=config)

Environment variables:

TELEGRAM_BOT_TOKEN=your_bot_token

Slack

from pig_messenger.adapters.slack import SlackMessengerAdapter, SlackConfig

config = SlackConfig(bot_token="xoxb-...", signing_secret="...")
adapter = SlackMessengerAdapter(config=config)

Discord

from pig_messenger.adapters.discord import DiscordMessengerAdapter, DiscordConfig

config = DiscordConfig(bot_token="your_bot_token", intents=["guilds", "messages"])
adapter = DiscordMessengerAdapter(config=config)

Feishu

from pig_messenger.adapters.feishu import FeishuAdapter

adapter = FeishuAdapter(app_id="cli_xxx", app_secret="xxx")

Distributed State Management

from pig_messenger import MessengerState
import redis.asyncio as redis

# Create Redis connection
redis_client = redis.Redis(host="localhost", port=6379)

# Initialize state management
state = MessengerState(redis_client=redis_client)

# Use in manager
manager = MessengerManager(agent_factory=agent_factory, state=state)

Advanced Features

Streaming Responses

async def streaming_agent(message, thread):
    async def generate_chunks():
        yield "Thinking"
        yield "..."
        yield "\n\nThis is a streaming response!"

    # Automatically selects best strategy
    await thread.stream(generate_chunks())

File Uploads

# Upload from URL
await thread.post_file(url="https://example.com/file.pdf", filename="document.pdf")

# Upload from content
await thread.post_file_content(content=file_bytes, filename="image.png", content_type="image/png")

Structured Messages (Slack Block Kit)

blocks = [{"type": "section", "text": {"type": "mrkdwn", "text": "*Hello World*"}}]
await thread.post_blocks(blocks, text_fallback="Hello World")

Error Handling and Retries

The manager automatically retries transient errors (429, 502, 503, 504) with exponential backoff:

manager = MessengerManager(
    agent_factory=agent_factory,
    max_retries=3,  # Default: 3
    retry_delay=1.0,  # Default: 1.0 second
)

Development

# Install dev dependencies
pip install pig-messenger[dev]

# Run tests
pytest tests/

# Type checking
mypy src/pig_messenger/

# Code formatting
ruff format src/

License

MIT

Links

Metadata

Release files for pig-messenger 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pig-messenger 0.2.0
File Size Uploaded
pig_messenger-0.2.0.tar.gz 44.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pig-messenger 0.2.0
File Interpreter ABI Platform
pig_messenger-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 84.2 kB

Release files / pig_messenger-0.2.0.tar.gz

Download URL pig_messenger-0.2.0.tar.gz
Size 44.6 kB
Tags Source
SHA-256 checksum
How to use checksums
4e9041159aa7391b20e3509846fddec43aeef8884582ad72a8a5e68d186b5841
BLAKE2b-256 checksum
How to use checksums
e24888a5a0e2aef1a25b29f8108a392d849e9f9d3c6a05d4223df068db4f73f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 4, 2026.

Transparency log

Release files / pig_messenger-0.2.0-py3-none-any.whl

Download URL pig_messenger-0.2.0-py3-none-any.whl
Size 39.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6d576f4d6e7d438cbdf8dbb4ff9c58e9bcec80f1dd3df90770bf5bc7ff46dcdb
BLAKE2b-256 checksum
How to use checksums
6e558c2ceaed7e59a40df315a952aa586865e29b33555c71c2e5cbffa0e540cd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 4, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.0.3

2 release files

0.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page