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.0.0.tar.gz (12.7 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.0.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for martix-1.0.0.tar.gz
Algorithm Hash digest
SHA256 46b6e57ee93298c784e5dbfa5bfa678a1a0a770e56525e71cb9929586d340e0a
MD5 bd4bd85516cff1847f326046689c5601
BLAKE2b-256 be5d9299f99b99a4a62158238ee82da8249edefe4f5c35c6f106be2b475cd435

See more details on using hashes here.

File details

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

File metadata

  • Download URL: martix-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 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.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1e6df1b37dad669b0384a883fb0545453de3646b97773541b235d572f8ec8f83
MD5 52ef8dc061bc97d52b145be5e301bfd1
BLAKE2b-256 b5e6593202ee280ed6ef98057232f92bda43432f35e4f3a56b0626ba271f9b99

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