martix


Namemartix JSON
Version 0.2.5 PyPI version JSON
download
home_pageNone
SummaryA python wrapper for matrix bots
upload_time2025-07-28 06:36:37
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT License Copyright (c) 2025 Ali Safamanesh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords
VCS
bugtrack_url
requirements matrix-nio aiofiles pillow
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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

```bash
pip install martix
```

Or install from source:

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

## Quick Start

```python
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:

```python
@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

```python
# 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

```python
# 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:

```python
@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

```python
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

```python
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

```python
@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

```python
# 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

- GitHub Issues: https://github.com/daradege/martix/issues
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "martix",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Ali Safamanesh <daradege@proton.me>",
    "download_url": "https://files.pythonhosted.org/packages/52/6a/332ae4f1f817de77df8ac8e1853bcaa12340d008597cf2267359d6d3192f/martix-0.2.5.tar.gz",
    "platform": null,
    "description": "# Martix - Simplified Matrix Library for Python\n\nMartix 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.\n\n## Features\n\n- **Simple API**: Easy-to-use decorators and methods inspired by python-telegram-bot\n- **Event Handling**: Comprehensive event system for messages, commands, invites, and more\n- **File Support**: Built-in support for sending and receiving files, images, audio, and documents\n- **Persistent State**: Automatic sync token management to resume from last position\n- **Type Safety**: Full type hints and dataclass-based objects\n- **Async/Await**: Built on asyncio for high performance\n- **Error Handling**: Comprehensive exception system\n\n## Installation\n\n```bash\npip install martix\n```\n\nOr install from source:\n\n```bash\ngit clone https://github.com/daradege/martix.git\ncd martix\npip install -e .\n```\n\n## Quick Start\n\n```python\nimport martix\n\n# Initialize client\nuser = \"@mybot:example.com\"\npassword = \"my_password\"\nhost = \"https://matrix.example.com\"\n\nclient = martix.Client(user, password, host)\nclient.command_prefix = \"!\"  # Default is \"/\"\n\n@client.on_ready()\nasync def ready():\n    print(f\"Logged in as {client.user.username}\")\n\n@client.on_message()\nasync def on_message(message: martix.Message):\n    print(f\"Message from {message.user.display_name}: {message.text}\")\n    \n    # Handle different message types\n    if message.photo:\n        await message.reply(\"Nice photo!\")\n    elif message.document:\n        content = await message.document.download(client.client)\n        await message.reply(f\"Downloaded {len(content)} bytes\")\n\n@client.on_command(\"start\")\nasync def start_command(command: martix.Command):\n    await command.reply(f\"Hello {command.user.display_name}!\")\n\n@client.on_command(\"echo\")\nasync def echo_command(command: martix.Command):\n    if command.args:\n        await command.reply(f\"You said: {command.args_string}\")\n\n# Start the bot\nclient.run()\n```\n\n## Message Types\n\nMartix supports all Matrix message types:\n\n```python\n@client.on_message()\nasync def handle_message(message: martix.Message):\n    # Text messages\n    print(message.text)\n    \n    # Images\n    if message.photo:\n        await message.photo.download(client.client, \"image.jpg\")\n    \n    # Documents\n    if message.document:\n        content = await message.document.download(client.client)\n    \n    # Audio files\n    if message.audio:\n        print(f\"Audio duration: {message.audio.duration}ms\")\n    \n    # Message metadata\n    print(f\"From: {message.user.display_name}\")\n    print(f\"Room: {message.room.name}\")\n    print(f\"Time: {message.time}\")\n```\n\n## Sending Messages\n\n```python\n# Send text message\nawait client.send_message(room_id, \"Hello World!\")\n\n# Send with reply\nawait message.reply(\"This is a reply\")\n\n# Send files\nawait client.send_file(room_id, \"document.pdf\")\nawait client.send_image(room_id, \"photo.jpg\", \"Caption here\")\n\n# React to messages\nawait message.react(\"\ud83d\udc4d\")\n```\n\n## Room Management\n\n```python\n# Join/leave rooms\nawait client.join_room(\"!room:example.com\")\nawait client.leave_room(\"!room:example.com\")\n\n# Get room list\nrooms = await client.get_rooms()\nfor room in rooms:\n    print(f\"Room: {room.name} ({room.member_count} members)\")\n\n# Handle invites\n@client.on_invite()\nasync def on_invite(room, event):\n    await client.join_room(room.room_id)\n    await client.send_message(room.room_id, \"Thanks for inviting me!\")\n```\n\n## Event Handlers\n\nMartix supports various event types:\n\n```python\n@client.on_ready()\nasync def ready():\n    \"\"\"Called when bot is ready\"\"\"\n    pass\n\n@client.on_message()\nasync def on_message(message: martix.Message):\n    \"\"\"Handle all messages\"\"\"\n    pass\n\n@client.on_command(\"commandname\")\nasync def command_handler(command: martix.Command):\n    \"\"\"Handle specific commands\"\"\"\n    pass\n\n@client.on_invite()\nasync def on_invite(room, event):\n    \"\"\"Handle room invitations\"\"\"\n    pass\n\n@client.on_member_join()\nasync def on_member_join(room, event):\n    \"\"\"Handle member joins\"\"\"\n    pass\n\n@client.on_member_leave()\nasync def on_member_leave(room, event):\n    \"\"\"Handle member leaves\"\"\"\n    pass\n```\n\n## Configuration\n\n```python\nclient = martix.Client(\n    user_id=\"@bot:example.com\",\n    password=\"password\",\n    homeserver=\"https://matrix.example.com\",\n    device_name=\"My Bot\"  # Optional\n)\n\n# Set command prefix\nclient.command_prefix = \"!\"  # Default is \"/\"\n```\n\n## Error Handling\n\n```python\nfrom martix import MartixError, AuthenticationError, NetworkError\n\ntry:\n    await client.start()\nexcept AuthenticationError:\n    print(\"Login failed - check credentials\")\nexcept NetworkError:\n    print(\"Connection failed - check homeserver URL\")\nexcept MartixError as e:\n    print(f\"Martix error: {e}\")\n```\n\n## Advanced Usage\n\n### File Downloads\n\n```python\n@client.on_message()\nasync def handle_files(message: martix.Message):\n    if message.document:\n        # Download to memory\n        content = await message.document.download(client.client)\n        \n        # Download to file\n        await message.document.download(client.client, \"downloaded_file.pdf\")\n        \n        # Access file metadata\n        print(f\"Filename: {message.document.filename}\")\n        print(f\"Size: {message.document.size} bytes\")\n        print(f\"MIME type: {message.document.mimetype}\")\n```\n\n### Custom Event Handling\n\n```python\n# Multiple handlers for the same event\n@client.on_message()\nasync def log_message(message: martix.Message):\n    print(f\"Logged: {message.text}\")\n\n@client.on_message()\nasync def process_message(message: martix.Message):\n    # Process the message\n    pass\n\n# Multiple command handlers\n@client.on_command(\"help\")\nasync def help_command(command: martix.Command):\n    await command.reply(\"Help text here\")\n\n@client.on_command(\"help\")\nasync def log_help_usage(command: martix.Command):\n    print(f\"Help command used by {command.user.username}\")\n```\n\n## Examples\n\nCheck the `examples/` directory for complete bot examples:\n\n- `basic_bot.py` - Simple message and command handling\n- `file_bot.py` - File upload/download handling\n\n## Requirements\n\n- Python 3.8+\n- matrix-nio\n- aiofiles\n- Pillow (for image handling)\n\n## License\n\nMIT License - see LICENSE file for details.\n\n## Contributing\n\nContributions are welcome! Please read CONTRIBUTING.md for guidelines.\n\n## Support\n\n- GitHub Issues: https://github.com/daradege/martix/issues",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Ali Safamanesh\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "A python wrapper for matrix bots",
    "version": "0.2.5",
    "project_urls": {
        "github": "https://github.com/daradege/martix",
        "website": "https://martix.daradege.ir"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "048e1574dd8807f96ace2ae9eb59ff318d7f69562a6e4e6a9c4e177bf95efe82",
                "md5": "6bec86639ec70a050d1b3e4cd4db90c3",
                "sha256": "f3b873b47de9b83760c4d246f35706b5aad83ac783b1a702c8e4103e2895cc96"
            },
            "downloads": -1,
            "filename": "martix-0.2.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6bec86639ec70a050d1b3e4cd4db90c3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 13547,
            "upload_time": "2025-07-28T06:36:36",
            "upload_time_iso_8601": "2025-07-28T06:36:36.639570Z",
            "url": "https://files.pythonhosted.org/packages/04/8e/1574dd8807f96ace2ae9eb59ff318d7f69562a6e4e6a9c4e177bf95efe82/martix-0.2.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "526a332ae4f1f817de77df8ac8e1853bcaa12340d008597cf2267359d6d3192f",
                "md5": "959c2f5b898d641a70a99c9088b65038",
                "sha256": "d86ff409b79954fa998217ebe06a8ae4d7d00b9d4743922f4bcdebd4a375a2f1"
            },
            "downloads": -1,
            "filename": "martix-0.2.5.tar.gz",
            "has_sig": false,
            "md5_digest": "959c2f5b898d641a70a99c9088b65038",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 11561,
            "upload_time": "2025-07-28T06:36:37",
            "upload_time_iso_8601": "2025-07-28T06:36:37.955821Z",
            "url": "https://files.pythonhosted.org/packages/52/6a/332ae4f1f817de77df8ac8e1853bcaa12340d008597cf2267359d6d3192f/martix-0.2.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-28 06:36:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "daradege",
    "github_project": "martix",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "matrix-nio",
            "specs": [
                [
                    ">=",
                    "0.20.0"
                ]
            ]
        },
        {
            "name": "aiofiles",
            "specs": [
                [
                    ">=",
                    "23.0.0"
                ]
            ]
        },
        {
            "name": "pillow",
            "specs": [
                [
                    ">=",
                    "10.0.0"
                ]
            ]
        }
    ],
    "lcname": "martix"
}
        
Elapsed time: 1.04212s