Skip to main content

Messaging wire for MoFox Bot with HTTP/WebSocket transports and routing helpers.

Project description

MoFox Wire

PyPI version Python versions License

MoFox Wire is a lightweight, high-performance messaging wire designed for MoFox Bot and similar chatbot applications. It provides a robust foundation for building message-driven systems with support for typed message envelopes, flexible routing, and multiple transport protocols.

โœจ Features

  • ๐Ÿท๏ธ Typed Messages: Full TypeScript-style type safety with TypedDict message models
  • ๐Ÿš€ High Performance: Built with async/await and optimized for high-throughput scenarios
  • ๐ŸŒ Multiple Transports: Support for HTTP and WebSocket protocols out of the box
  • ๐Ÿ”„ Flexible Routing: Sophisticated message routing with middleware support
  • ๐Ÿ“ฆ JSON Serialization: Efficient JSON-based message serialization with orjson
  • ๐Ÿ›ก๏ธ Error Handling: Comprehensive error handling and processing guarantees
  • ๐ŸŽฏ Easy Integration: Simple API for quick integration with existing projects

๐Ÿš€ Installation

Install from PyPI (recommended):

pip install mofox-wire

Install from source:

git clone https://github.com/mofox-bot/mofox-wire.git
cd mofox-wire
pip install -e .

For development:

pip install -e ".[dev]"

๐Ÿ“‹ Requirements

  • Python 3.11+
  • aiohttp >= 3.12.0
  • fastapi >= 0.116.0
  • orjson >= 3.10.0
  • uvicorn >= 0.35.0
  • websockets >= 15.0.1

๐Ÿ—๏ธ Architecture

MoFox Bus follows a layered architecture:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Application   โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   Runtime API   โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚     Router      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   Codec/Types   โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   Transport     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  • Types: TypedDict models for messages and metadata
  • Codec: JSON serialization/deserialization utilities
  • Transport: HTTP and WebSocket client/server implementations
  • Router: Message routing and filtering capabilities
  • Runtime: High-level API for message processing and middleware

๐Ÿ“– Quick Start

Basic Message Handling

import asyncio
from mofox_bus import MessageRuntime, MessageBuilder, MessageEnvelope

async def handle_message(envelope: MessageEnvelope) -> MessageEnvelope | None:
    """Simple message handler that processes incoming messages"""
    print(f"Processing message: {envelope.get('content', 'No content')}")

    # Process the message (modify, filter, etc.)
    if envelope.get('content') == 'hello':
        response = MessageBuilder.text_message('world')
        response['reply_to'] = envelope.get('id')
        return response

    return None

async def main():
    # Create runtime
    runtime = MessageRuntime()

    # Register handler
    runtime.add_handler(handle_message)

    # Create a test message
    message = MessageBuilder.text_message('hello')
    message['id'] = 'msg-001'

    # Process the message
    await runtime.process_message(message)

if __name__ == '__main__':
    asyncio.run(main())

HTTP Server Example

from mofox_bus import MessageServer
import uvicorn

async def main():
    # Create HTTP server
    server = MessageServer()

    # Add message handler
    server.add_handler(lambda env: print(f"Received: {env}"))

    # Start server (will run until interrupted)
    config = uvicorn.Config(server.app, host="0.0.0.0", port=8000)
    server = uvicorn.Server(config)
    await server.serve()

if __name__ == '__main__':
    asyncio.run(main())

WebSocket Client Example

from mofox_bus.transport import WebSocketClient
from mofox_bus import MessageBuilder

async def main():
    # Create WebSocket client
    client = WebSocketClient("ws://localhost:8000/ws")

    await client.connect()

    # Send a message
    message = MessageBuilder.text_message("Hello from WebSocket client!")
    await client.send_message(message)

    # Receive messages
    async for envelope in client.listen():
        print(f"Received: {envelope}")

if __name__ == '__main__':
    asyncio.run(main())

๐Ÿ“š API Reference

Core Components

MessageRuntime

The main runtime for processing messages with middleware support.

runtime = MessageRuntime()
runtime.add_handler(handler_func)
runtime.add_middleware(middleware_func)
await runtime.process_message(envelope)

MessageBuilder

Utility for creating typed message envelopes.

# Text message
msg = MessageBuilder.text_message("Hello world", user_id="user123")

# Image message
msg = MessageBuilder.image_message("https://example.com/image.jpg", user_id="user123")

# Custom message
msg = MessageBuilder.create_message(
    content="Custom content",
    message_type="custom",
    user_id="user123",
    platform="discord"
)

Router

Advanced message routing and filtering.

router = Router()

# Add route with predicate
router.add_route(
    predicate=lambda env: env.get('platform') == 'discord',
    handler=discord_handler
)

# Process messages
await router.route(envelope)

Message Types

MoFox Bus provides several built-in message types:

  • Text Messages: Standard text content
  • Image Messages: Image URLs and metadata
  • Seg Messages: Structured content with segments
  • Custom Messages: Extensible message format

Transport Layer

HTTP Transport

# Server
server = MessageServer()
server.add_handler(handler)
await server.start(host="0.0.0.0", port=8000)

# Client
client = MessageClient("http://localhost:8000")
await client.send_message(envelope)

WebSocket Transport

# Server
ws_server = WebSocketServer()
ws_server.add_handler(handler)
await ws_server.start(host="0.0.0.0", port=8001)

# Client
ws_client = WebSocketClient("ws://localhost:8001/ws")
await ws_client.connect()
await ws_client.send_message(envelope)

๐Ÿ”ง Configuration

Environment Variables

# Default settings
MOFOX_BUS_HOST=0.0.0.0
MOFOX_BUS_PORT=8000
MOFOX_BUS_LOG_LEVEL=INFO
MOFOX_BUS_MAX_CONNECTIONS=1000

Programmatic Configuration

from mofox_bus import MessageRuntime

runtime = MessageRuntime(
    max_workers=10,
    error_handler=custom_error_handler,
    middleware=[middleware1, middleware2]
)

๐Ÿงช Development

Running Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=mofox_bus

# Run type checking
mypy mofox_bus

Code Formatting

# Format code
black mofox_bus
isort mofox_bus

# Lint code
ruff check mofox_bus

Building Documentation

# Install documentation dependencies
pip install -e ".[docs]"

# Build docs
mkdocs build

๐Ÿ“ Changelog

[0.1.0] - 2024-XX-XX

Added

  • Initial release of MoFox Bus
  • Core message runtime with middleware support
  • HTTP and WebSocket transport implementations
  • Typed message models with TypedDict
  • Message routing and filtering capabilities
  • JSON serialization with orjson optimization
  • Comprehensive error handling
  • Full async/await support

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests (pytest)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the GPL-3.0 License. See the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • The MoFox Bot team for the original concept and requirements
  • Contributors who have helped shape this library
  • The Python async community for inspiration and best practices

๐Ÿ“ž Support

๐Ÿ”— Related Projects


MoFox Bus - Building the future of messaging infrastructure, one message at a time. ๐Ÿš€

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

mofox_wire-0.1.4.tar.gz (97.5 kB view details)

Uploaded Source

Built Distribution

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

mofox_wire-0.1.4-py3-none-any.whl (59.2 kB view details)

Uploaded Python 3

File details

Details for the file mofox_wire-0.1.4.tar.gz.

File metadata

  • Download URL: mofox_wire-0.1.4.tar.gz
  • Upload date:
  • Size: 97.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for mofox_wire-0.1.4.tar.gz
Algorithm Hash digest
SHA256 7ab272d662095a01d27342d634addc298550560c95c2fc36a88cb7d75d5c983a
MD5 fc7d0268accf36dbbffff43596fb3a12
BLAKE2b-256 77680d1d7b023fa2895386909fc16ff2d0d434fcd52ce6fcb61a0345bf2c434c

See more details on using hashes here.

File details

Details for the file mofox_wire-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: mofox_wire-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 59.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for mofox_wire-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c23dd4942587af0eb33ddf2dfadac6d9edbf24977d15d9b8a48dfe7031fc0829
MD5 345ca2bd8a0589ba86d69310b8ce8e31
BLAKE2b-256 5f7ea752e1c5efdfc087adddc0f9cfa84dbca4a4eebd8427197fc028fcd13693

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