Matrix Client SDK

0.4.0 · active · verified Thu Apr 16

The `matrix-client` library is a Client-Server SDK for the Matrix protocol, providing functionality to interact with Matrix homeservers. It is currently at version 0.4.0 and releases are infrequent, often addressing breaking changes or incompatibilities with the Matrix protocol or Synapse homeserver.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to log into a Matrix homeserver, join a room, send a message, and then log out. Ensure `MATRIX_HOMESERVER_URL`, `MATRIX_USERNAME`, `MATRIX_PASSWORD`, and `MATRIX_ROOM` environment variables are set or replaced with actual values.

import os
from matrix_client.client import MatrixClient

HOMESERVER_URL = os.environ.get('MATRIX_HOMESERVER_URL', 'https://matrix.org')
USERNAME = os.environ.get('MATRIX_USERNAME', 'test_user')
PASSWORD = os.environ.get('MATRIX_PASSWORD', 'test_password')
ROOM_ID_OR_ALIAS = os.environ.get('MATRIX_ROOM', '#test:matrix.org') # Replace with a valid room

try:
    # For matrix-client v0.4.0+, `use_authorization_header=True` is recommended
    # for better compatibility with modern Synapse versions.
    client = MatrixClient(HOMESERVER_URL, use_authorization_header=True)
    client.login(username=USERNAME, password=PASSWORD)
    print(f"Successfully logged in as {USERNAME}")

    # Try to join a room
    room = client.join_room(ROOM_ID_OR_ALIAS)
    print(f"Successfully joined room: {room.name} ({room.room_id})")

    # Send a message
    room.send_text("Hello from matrix-client Python SDK!")
    print("Sent a test message.")

    # Logout
    client.logout()
    print("Logged out.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure MATRIX_HOMESERVER_URL, MATRIX_USERNAME, MATRIX_PASSWORD, and MATRIX_ROOM are set correctly and are valid.")

view raw JSON →