Skip to main content

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 rowiret 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 Wire 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_wire 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_wire 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_wire.transport import WebSocketClient
from mofox_wire 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 Wire 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_wire_HOST=0.0.0.0
mofox_wire_PORT=8000
mofox_wire_LOG_LEVEL=INFO
mofox_wire_MAX_CONNECTIONS=1000

Programmatic Configuration

from mofox_wire 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_wire

# Run type checking
mypy mofox_wire

Code Formatting

# Format code
black mofox_wire
isort mofox_wire

# Lint code
ruff check mofox_wire

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 Wire
  • 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 Wire - Building the future of messaging infrastructure, one message at a time. 🚀

Metadata

Release files for mofox-wire 0.1.7

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

Source distribution (sdist)

Source distribution for mofox-wire 0.1.7
File Size Uploaded Provenance Actions
mofox_wire-0.1.7.tar.gz 91.2 kB Without provenance Details for mofox_wire-0.1.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mofox-wire 0.1.7
File Interpreter ABI Platform Actions
mofox_wire-0.1.7-py3-none-any.whl Python 3 none any Details for mofox_wire-0.1.7-py3-none-any.whl

Total release size: 149.9 kB

Release files / mofox_wire-0.1.7.tar.gz

Download URL mofox_wire-0.1.7.tar.gz
Size 91.2 kB
Tags Source
SHA-256 checksum
How to use checksums
7c7c8d6e559522572db9cd59fdc4c2ff5c85cea753afc3be8dd6f212aff1d329
BLAKE2b-256 checksum
How to use checksums
2915c5e11756f1365d7c02af6915b5db59e7896816da059ec47bc6bd0c7a2f3e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release files / mofox_wire-0.1.7-py3-none-any.whl

Download URL mofox_wire-0.1.7-py3-none-any.whl
Size 58.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e3f155586461420ebe3768c1ac966eaf9226873ba50cf81fc03e9714c797d9cd
BLAKE2b-256 checksum
How to use checksums
ed9e570dd95cab2d72e17d13ab7744072ea92189abf97e9c74b1a5790a51f6bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Security for mofox-wire 0.1.7

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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