Skip to main content

A python wrapper for matrix bots

Project description

Martix - Simplified Matrix Library for Python

Martix is a high-level Python library that simplifies working with the Matrix protocol. It provides an intuitive, telegram-bot-like API for creating Matrix bots and clients.

Features

  • Simple API: Easy-to-use decorators and methods inspired by python-telegram-bot
  • Event Handling: Comprehensive event system for messages, commands, invites, and more
  • File Support: Built-in support for sending and receiving files, images, audio, and documents
  • Persistent State: Automatic sync token management to resume from last position
  • Type Safety: Full type hints and dataclass-based objects
  • Async/Await: Built on asyncio for high performance
  • Error Handling: Comprehensive exception system

Installation

pip install martix

Or install from source:

git clone https://github.com/daradege/martix.git
cd martix
pip install -e .

Quick Start

import martix

# Initialize client
user = "@mybot:example.com"
password = "my_password"
host = "https://matrix.example.com"

client = martix.Client(user, password, host)
client.command_prefix = "!"  # Default is "/"

@client.on_ready()
async def ready():
    print(f"Logged in as {client.user.username}")

@client.on_message()
async def on_message(message: martix.Message):
    print(f"Message from {message.user.display_name}: {message.text}")
    
    # Handle different message types
    if message.photo:
        await message.reply("Nice photo!")
    elif message.document:
        content = await message.document.download(client.client)
        await message.reply(f"Downloaded {len(content)} bytes")

@client.on_command("start")
async def start_command(command: martix.Command):
    await command.reply(f"Hello {command.user.display_name}!")

@client.on_command("echo")
async def echo_command(command: martix.Command):
    if command.args:
        await command.reply(f"You said: {command.args_string}")

# Start the bot
client.run()

Message Types

Martix supports all Matrix message types:

@client.on_message()
async def handle_message(message: martix.Message):
    # Text messages
    print(message.text)
    
    # Images
    if message.photo:
        await message.photo.download(client.client, "image.jpg")
    
    # Documents
    if message.document:
        content = await message.document.download(client.client)
    
    # Audio files
    if message.audio:
        print(f"Audio duration: {message.audio.duration}ms")
    
    # Message metadata
    print(f"From: {message.user.display_name}")
    print(f"Room: {message.room.name}")
    print(f"Time: {message.time}")

Sending Messages

# Send text message
await client.send_message(room_id, "Hello World!")

# Send with reply
await message.reply("This is a reply")

# Send files
await client.send_file(room_id, "document.pdf")
await client.send_image(room_id, "photo.jpg", "Caption here")

# React to messages
await message.react("👍")

Room Management

# Join/leave rooms
await client.join_room("!room:example.com")
await client.leave_room("!room:example.com")

# Get room list
rooms = await client.get_rooms()
for room in rooms:
    print(f"Room: {room.name} ({room.member_count} members)")

# Handle invites
@client.on_invite()
async def on_invite(room, event):
    await client.join_room(room.room_id)
    await client.send_message(room.room_id, "Thanks for inviting me!")

Event Handlers

Martix supports various event types:

@client.on_ready()
async def ready():
    """Called when bot is ready"""
    pass

@client.on_message()
async def on_message(message: martix.Message):
    """Handle all messages"""
    pass

@client.on_command("commandname")
async def command_handler(command: martix.Command):
    """Handle specific commands"""
    pass

@client.on_invite()
async def on_invite(room, event):
    """Handle room invitations"""
    pass

@client.on_member_join()
async def on_member_join(room, event):
    """Handle member joins"""
    pass

@client.on_member_leave()
async def on_member_leave(room, event):
    """Handle member leaves"""
    pass

Configuration

client = martix.Client(
    user_id="@bot:example.com",
    password="password",
    homeserver="https://matrix.example.com",
    device_name="My Bot"  # Optional
)

# Set command prefix
client.command_prefix = "!"  # Default is "/"

Error Handling

from martix import MartixError, AuthenticationError, NetworkError

try:
    await client.start()
except AuthenticationError:
    print("Login failed - check credentials")
except NetworkError:
    print("Connection failed - check homeserver URL")
except MartixError as e:
    print(f"Martix error: {e}")

Advanced Usage

File Downloads

@client.on_message()
async def handle_files(message: martix.Message):
    if message.document:
        # Download to memory
        content = await message.document.download(client.client)
        
        # Download to file
        await message.document.download(client.client, "downloaded_file.pdf")
        
        # Access file metadata
        print(f"Filename: {message.document.filename}")
        print(f"Size: {message.document.size} bytes")
        print(f"MIME type: {message.document.mimetype}")

Custom Event Handling

# Multiple handlers for the same event
@client.on_message()
async def log_message(message: martix.Message):
    print(f"Logged: {message.text}")

@client.on_message()
async def process_message(message: martix.Message):
    # Process the message
    pass

# Multiple command handlers
@client.on_command("help")
async def help_command(command: martix.Command):
    await command.reply("Help text here")

@client.on_command("help")
async def log_help_usage(command: martix.Command):
    print(f"Help command used by {command.user.username}")

Examples

Check the examples/ directory for complete bot examples:

  • basic_bot.py - Simple message and command handling
  • file_bot.py - File upload/download handling

Requirements

  • Python 3.8+
  • matrix-nio
  • aiofiles
  • Pillow (for image handling)

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

Support

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

martix-1.2.1.tar.gz (13.1 kB view details)

Uploaded Source

Built Distribution

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

martix-1.2.1-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file martix-1.2.1.tar.gz.

File metadata

  • Download URL: martix-1.2.1.tar.gz
  • Upload date:
  • Size: 13.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for martix-1.2.1.tar.gz
Algorithm Hash digest
SHA256 1f592c04fe2c881db182af5794dcb7d5120158643904f73bc8830fab39726989
MD5 7ea6ba83b35f2380817d12927bc0f3eb
BLAKE2b-256 c9f90aec0aad24e43f02883dab9aeedb9a262de621432ba4cf284cf1a5533b38

See more details on using hashes here.

File details

Details for the file martix-1.2.1-py3-none-any.whl.

File metadata

  • Download URL: martix-1.2.1-py3-none-any.whl
  • Upload date:
  • Size: 14.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for martix-1.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d6ffd56d771d401ac9be3d46161f7364e54204ca6998f11dd8cead16830e8e0c
MD5 4a2b592e5781f9b4e8f20c9fd486a78e
BLAKE2b-256 4f8683d6489137446c1fdf9015872d496bf4e45e97fb9240029f8cff68311da1

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