mautrix-python

repository·master·Indexed 42 days ago

https://github.com/mautrix/python

An asyncio-based Matrix framework for building low-level API requests, high-level bridges, and client-side applications. It includes the ClientAPI for homeserver interaction, AppServiceAPI for application services, and a variety of state stores (PostgreSQL, SQLite, and file-based) for persistence.

Tokens
8.4K
Snippets
29
Records
48
Agent score
52%

What's inside mautrix-python

  1. Overview of mautrix-python components

    master

    mautrix-python is an asyncio-based Matrix framework for Python 3.10+. It provides several layers of abstraction depending on your use case:

    • Low-level API: mautrix.api for basic HTTP requests and mautrix.client.api for direct Client API endpoint functions.
    • Application Service: mautrix.appservice for building medium-level application services, including transaction support, user/alias queries, and room state storage.
    • End-to-End Encryption (E2EE): mautrix.crypto handles complex key exchanges using libolm via python-olm.
    • Bridging: mautrix.bridge provides high-level utilities for building bridges, including double-puppeting and end-to-bridge encryption helpers.
    • Client Framework: mautrix.client offers high-level syncing, event handling, and E2EE helpers for client-side applications.
    • Utilities: mautrix.util contains Matrix HTML tools, a 'manhole' system for interactive debugging, YAML/Database helpers, and HMAC-SHA256 signing utilities.
  2. Use mautrix.client mixins

    master

    The mautrix.client module provides several specialized mixins that add specific capabilities to a client implementation:

    • Syncer: Handles synchronization logic.
    • DecryptionDispatcher: Manages the dispatching of decrypted messages.
    • EncryptingAPI: Provides interfaces for encrypting data.
    • StoreUpdatingAPI: Provides interfaces for updating the internal state/store.
  3. Use the AppService client API

    master

    The mautrix.appservice module provides the client API for interacting with Matrix appservices. It contains two primary classes for managing appservice functionality:

    • AppServiceAPI: The main interface for an appservice client.
    • ChildAppServiceAPI: An interface designed for child appservices (sub-services) within a larger appservice hierarchy.
  4. Implement a custom StateStore for mautrix.client

    master

    The mautrix.client.state_store.StateStore class defines the interface for storing and retrieving client state. To persist or manage state in a custom way, you must provide an implementation of this class.

    Available implementations include:

    • In-memory: Uses RAM for storage (volatile).
    • Async database: Uses asyncpg (PostgreSQL) or aiosqlite (SQLite) for persistent storage.
    • Flat file: Uses local files for storage.
  5. Use opt_prometheus for conditional metrics without a hard dependency

    master

    The mautrix.util.opt_prometheus module provides no-op (no-operation) implementations of Prometheus metrics: Counter, Gauge, Summary, Histogram, Info, and Enum.

    Use this module to write code that uses metrics without forcing a hard dependency on the prometheus_client library. This allows your application to function normally even if prometheus_client is not installed in the environment. You can check if the library is available using the is_installed boolean.

  6. Understand the architecture of mautrix.client via mixins

    master

    The mautrix.client.Client class is a lightweight wrapper. Most of its high-level functionality is provided by various mixins that are included in the class.

    While most users should use the high-level Client class, developers building specialized components (like those in the appservice module) may need to extend specific mixins directly. For example, mautrix.appservice.api.IntentAPI extends mautrix.client.StoreUpdatingAPI rather than the full Client class.

  7. Use mautrix.types for strongly-typed identifiers

    master

    The mautrix.types module provides specialized classes for common Matrix identifiers used throughout the library. Instead of using raw strings, you should use these types to ensure data integrity and clarity when interacting with the API.

    Key identifier types include:

    • UserID: Represents a Matrix user ID (e.g., @user:example.com).
    • RoomID: Represents a unique Matrix room ID.
    • RoomAlias: Represents a human-readable room alias.
    • EventID: Represents a unique identifier for a specific event.
    • DeviceID: Represents a specific device identifier.
    • SessionID: Represents a session identifier.
    • SyncToken: Used for pagination and state tracking during sync operations.
    • ContentURI: Represents a URI pointing to content.
    • FilterID: Represents an identifier for a filter.
    • SigningKey and IdentityKey: Used for cryptographic operations and identity verification.
  8. Use mautrix.util.async_db instead of mautrix.util.db

    master
    The mautrix.util.db module (which uses SQLAlchemy) is deprecated as of version 0.15.0. For all new development and database interactions, use the mautrix.util.async_db utility instead, as it is the recommended way to handle asynchronous database operations in this project.
  9. Implement and register bridge commands

    master

    To extend the bridge with new commands, you can use the command_handler decorator to register a function as a command handler. Commands are processed via a CommandProcessor which receives CommandEvent objects.

    Available command categories (sections) for organizing help documentation include:

    • SECTION_GENERAL
    • SECTION_ADMIN
    • SECTION_AUTH
    • SECTION_RELAY
    from mautrix.bridge.commands import command_handler, CommandEvent
    
    @command_handler
    def my_custom_command(event: CommandEvent) -> None:
        # Implementation logic here
        pass
  10. How CommandProcessor handles raw commands

    master

    The CommandProcessor is responsible for receiving raw command strings from the bridge and routing them to the correct CommandHandler.

    Workflow:

    1. Normalization: The command is converted to lowercase.
    2. Lookup: The processor checks registered command_handlers and command_aliases.
    3. Delegation: If a command is unknown, the processor checks if the sender has a command_status marked as "next". If so, it treats the current input as arguments for the previously pending command.
    4. Execution: The handler is called. If an unhandled exception occurs, the processor logs the error and (if evt.print_error_traceback is enabled for admins) sends the traceback to the user.
  11. Use bridge commands for management and metadata

    master

    The bridge provides several built-in commands to manage ongoing actions, check the bridge version, and access help documentation. These commands are typically triggered via a command prefix (e.g., $cmdprefix).

    Available Commands

    CommandDescriptionAuth Required
    cancelCancels an ongoing action if one is currently in progress.No
    versionDisplays the bridge name, repository URL, and version number.No
    helpShows a help message containing available commands and usage instructions.No

    Command Contexts

    How you interact with commands depends on the type of room you are in:

    • Management Room: Commands can be sent directly without a prefix.
    • Portal Room: You must always prefix commands with the configured $cmdprefix. Management commands are not bridged in portal rooms.
    • Standard Room: You must prefix commands with the configured $cmdprefix.
  12. Select rooms to clean with sub-commands

    master

    After running clean-rooms, you can use the following sub-commands to specify which rooms should be targeted for cleanup. These commands must be used in the order: clean-rooms $\rightarrow$ selection command $\rightarrow$ confirm-clean.

    Cleans the recommended set of rooms, which includes all Unidentified (U) rooms and Inactive portal (I) rooms.

    clean-groups <letters>

    Cleans all rooms belonging to the specified groups. The <letters> argument is a string of the first letters of the group names.

    • M: Management rooms
    • A: Active portal rooms
    • U: Unidentified rooms
    • I: Inactive portal rooms
    • T: Tombstoned rooms

    Example: $cmdprefix+sp clean-groups MUI cleans Management, Unidentified, and Inactive rooms.*

    clean-range <group><start>-<end>

    Cleans a specific range of rooms within a group. The range is 1-indexed based on the list provided by the clean-rooms command.

    Example: $cmdprefix+sp clean-range I2-6 cleans rooms 2 through 6 from the Inactive portal (I) group.

    # Clean specific groups
    $cmdprefix+sp clean-groups AU
    
    # Clean a range within a group (e.g., Inactive rooms 2 through 6)
    $cmdprefix+sp clean-range I2-6