Matrix Python SDK

repository·master·Indexed 42 days ago

https://github.com/matrix-org/matrix-python-sdk

A Matrix client-server SDK for Python (supporting 2.7 and 3.4+) providing both low-level HTTP API wrappers via MatrixHttpApi and a high-level object-oriented client model via MatrixClient. It supports user registration, authentication, room management, event listeners, and media uploads. Note: maintainers recommend using the matrix-nio library for a more featureful and actively maintained alternative.

Tokens
2.5K
Snippets
13
Records
14
Agent score
4%

What's inside Matrix Python SDK

  1. How the SDK layers work: API vs Client

    master

    The SDK provides two distinct layers of interaction:

    1. API Layer (matrix_client.api): A low-level layer that wraps raw HTTP API calls. It has minimal business logic. You can provide an access token for requests and a custom txn_id (transaction ID) which the SDK will increment for each request.
    2. Client Layer (matrix_client.client): A high-level layer that wraps the API layer. It provides a rich object model (such as Room objects) to perform actions more easily.

    Choose the API layer if you need direct access to raw HTTP calls, and the Client layer if you want to work with high-level abstractions and object models.

  2. Install the matrix-python-sdk

    master

    You can install the SDK via the stable PyPI release or by installing the development version from source.

    Stable release

    Install using pip. This will automatically install all necessary dependencies.

    Development version

    Clone the repository and install using setup.py from the root directory.

    Note: The maintainers strongly recommend using the matrix-nio library instead of this SDK, as it is more featureful and actively maintained.

    # Stable release
    pip install matrix_client
    
    # Development version
    git clone https://github.com/matrix-org/matrix-python-sdk.git
    cd matrix-python-sdk
    python setup.py install
  3. Use the low-level API layer

    master

    The MatrixHttpApi class allows you to make direct HTTP API calls to a Matrix homeserver using an access token.

    from matrix_client.api import MatrixHttpApi
    
    matrix = MatrixHttpApi("https://matrix.org", token="some_token")
    response = matrix.send_message("!roomid:matrix.org", "Hello!")
  4. Use the high-level Client API

    master

    The MatrixClient class provides an object-oriented way to interact with a Matrix homeserver. It supports user registration, logging in, creating rooms, and sending messages through room objects.

    from matrix_client.client import MatrixClient
    
    client = MatrixClient("http://localhost:8008")
    
    # New user registration
    token = client.register_with_password(username="foobar", password="monkey")
    
    # Existing user login
    token = client.login(username="foobar", password="monkey")
    
    # Room interaction
    room = client.create_room("my_room_alias")
    room.send_text("Hello!")
  5. Listen for events in the background

    master

    To continuously receive events without blocking your main thread, use start_listener_thread.

    • start_listener_thread(timeout_ms=30000, exception_handler=None): Starts a daemon thread that runs listen_forever.
    • listen_forever(timeout_ms=30000, exception_handler=None, bad_sync_timeout=5): A blocking loop that polls the server. Use this if you want to run the sync loop in your main thread.
    • stop_listener_thread(): Stops the background thread.

    If an exception_handler is provided, it will be called when errors occur during sync.

    def handle_error(e):
        print(f"Error occurred: {e}")
    
    client.start_listener_thread(timeout_ms=10000, exception_handler=handle_error)
    
    # ... do other work ...
    
    client.stop_listener_thread()
  6. Add event listeners to MatrixClient

    master

    You can register callbacks to react to incoming events. MatrixClient provides several types of listeners:

    • add_listener(callback, event_type=None): Global listener for all events. If event_type is provided, it only triggers for that specific type.
    • add_presence_listener(callback): Triggers when presence updates arrive.
    • add_invite_listener(callback): Triggers when an invite arrives. Callback signature: func(room_id, state).
    • add_leave_listener(callback): Triggers when the client leaves a room. Callback signature: func(room_id, room).
    • add_ephemeral_listener(callback, event_type=None): Triggers for ephemeral events.

    To stop listening, use the corresponding remove_*_listener(uid) method with the UUID returned by the add method.

    def my_global_callback(event):
        print(f"New event: {event['type']}")
    
    # Register global listener
    listener_id = client.add_listener(my_global_callback)
    
    # Register invite listener
    def on_invite(room_id, state):
        print(f"Invited to {room_id}")
    
    client.add_invite_listener(on_invite)
  7. Login to a homeserver

    master

    Use the login method to authenticate with a username and password. This method returns the access token and automatically initiates a /sync request to populate the client state if sync=True (default).

    Parameters

    • username (str): Account username.
    • password (str): Account password.
    • limit (int): Number of messages to return when syncing (deprecated, use sync filters).
    • sync (bool): Whether to initiate a /sync request after logging in.
    • device_id (str, optional): ID of the client device. If not specified, the server auto-generates one.
    client = MatrixClient("https://matrix.org")
    token = client.login(username="myuser", password="mypassword")
  8. Manage rooms: Create and Join

    master

    Use the following methods to manage room membership:

    • create_room(alias=None, is_public=False, invitees=None): Creates a new room. Returns a Room object.
    • join_room(room_id_or_alias): Joins an existing room via its ID or alias. Returns a Room object.
    # Create a room
    new_room = client.create_room(alias="#myroom:matrix.org", is_public=True)
    
    # Join a room
    room = client.join_room("#existing:matrix.org")
  9. Initialize MatrixClient

    master

    The MatrixClient class is the primary entrypoint for interacting with a Matrix homeserver. You can initialize it by providing the base_url (the URL of the homeserver preceding /_matrix, e.g., https://matrix.org) and an optional token for an existing session.

    Configuration Options

    • base_url (str): The homeserver URL.
    • token (str, optional): An existing access token.
    • user_id (str, optional): Deprecated. Use the token to retrieve the user ID.
    • valid_cert_check (bool): Whether to validate the homeserver's certificate (defaults to True).
    • sync_filter_limit (int): Limit for the sync filter (defaults to 20).
    • cache_level (CACHE): Level of caching to use. Must be one of CACHE.NONE, CACHE.SOME, or CACHE.ALL.
    • encryption (bool): Whether to enable end-to-end encryption support.
    • encryption_conf (dict, optional): Configuration parameters for encryption, passed to OlmDevice.
    from matrix_client import MatrixClient, CACHE
    
    client = MatrixClient(
        base_url="https://matrix.org",
        token="your_access_token",
        cache_level=CACHE.ALL,
        encryption=True
    )