### MatrixHttpApi Initialization and Sync Example Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Demonstrates how to initialize the MatrixHttpApi client with a base URL and token, and how to perform an initial synchronization of the client's state with the homeserver. This is a common starting point for interacting with the Matrix API. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="foobar") response = matrix.sync() ``` -------------------------------- ### Install Development Version of Matrix Client SDK Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/README.rst Installs the development version of the matrix-python-sdk by cloning the repository and running setup.py. This method also installs all required dependencies. ```shell git clone https://github.com/matrix-org/matrix-python-sdk.git cd matrix-python-sdk python setup.py install ``` -------------------------------- ### Install Matrix Client SDK Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/README.rst Installs the stable release of the matrix-client SDK from PyPI, including all necessary dependencies. ```shell pip install matrix_client ``` -------------------------------- ### GET URL Preview Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves a preview for a given URL. ```APIDOC ## GET URL Preview ### Description Get preview for URL. ### Method GET ### Endpoint `/preview_url` (Implied) ### Parameters #### Query Parameters - **url** (str) - Required - URL to get a preview. - **ts** (double) - Optional - The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested version available. ``` -------------------------------- ### MatrixClient Event Listener Setup in Python Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Shows how to add various types of listeners to the MatrixClient for handling different event types, including ephemeral events, invites, room leaves, general events, and presence updates. ```python def ephemeral_callback(roomchunk): pass client.add_ephemeral_listener(ephemeral_callback, event_type="m.some.event") def invite_callback(room_id, state): pass client.add_invite_listener(invite_callback) def leave_callback(room_id, room): pass client.add_leave_listener(leave_callback) def event_callback(roomchunk): pass client.add_listener(event_callback, event_type="m.room.message") def presence_callback(roomchunk): pass client.add_presence_listener(presence_callback) ``` -------------------------------- ### Send Message Example Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Illustrates how to send a text message to a specific Matrix room using the MatrixHttpApi client. This method is fundamental for real-time communication within Matrix. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="foobar") # Assuming matrix.sync() has been called previously response = matrix.send_message("!roomid:matrix.org", "Hello!") ``` -------------------------------- ### Room Management Operations with Python Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Provides examples for managing Matrix rooms, including setting room names and topics, inviting, kicking, and banning users, managing access control (invite-only, guest access), modifying power levels, and leaving a room. Requires a logged-in client with appropriate permissions. ```python from matrix_client.client import MatrixClient client = MatrixClient("https://matrix.org") client.login(username="admin", password="adminpass") room = client.join_room("#myroom:matrix.org") # Set room name and topic room.set_room_name("My Awesome Room") room.set_room_topic("Discussing awesome things") # Invite user to room success = room.invite_user("@friend:matrix.org") print(f"Invite sent: {success}") # Kick user from room room.kick_user("@troublemaker:matrix.org", reason="Spamming") # Ban user from room room.ban_user("@badactor:matrix.org", reason="Harassment") # Unban user room.unban_user("@reformed:matrix.org") # Set room access control room.set_invite_only(True) # Make room invite-only room.set_guest_access(False) # Disable guest access # Modify power levels room.modify_user_power_levels( users={"@moderator:matrix.org": 50, "@admin:matrix.org": 100}, users_default=0 ) # Leave room success = room.leave() print(f"Left room: {success}") ``` -------------------------------- ### End-to-End Encryption Setup and Usage with matrix-python-sdk Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Explains how to enable and use end-to-end encryption for secure communication. Initializes the client with encryption enabled, logs in with a device ID, joins an encrypted room, and sends encrypted messages. Encryption is automatic once enabled. ```python from matrix_client.client import MatrixClient # Initialize client with encryption enabled client = MatrixClient( "https://matrix.org", encryption=True, encryption_conf={} # Optional encryption configuration ) # Login with device_id for encryption token = client.login( username="secureuser", password="securepass", device_id="MY_DEVICE_ID" ) # Join or create encrypted room room = client.join_room("#encrypted:matrix.org") # Enable encryption in room (cannot be disabled once enabled) success = room.enable_encryption() if success: print("Encryption enabled for room") # Check if room is encrypted if room.encrypted: print("This room uses end-to-end encryption") # Send messages normally - encryption is handled automatically room.send_text("This message is encrypted!") ``` -------------------------------- ### Low-Level HTTP API Calls with matrix-python-sdk Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Demonstrates direct Matrix HTTP API calls for sending messages, syncing, retrieving room state, setting topics, and getting user display names. Requires an access token and room/user IDs. Handles potential MatrixRequestErrors. ```python from matrix_client.api import MatrixHttpApi from matrix_client.errors import MatrixRequestError # Initialize API with base URL and token api = MatrixHttpApi("https://matrix.org", token="your_access_token") # Send message directly via API try: response = api.send_message( room_id="!roomid:matrix.org", text_content="Hello via API!" ) print(f"Message event ID: {response['event_id']}") except MatrixRequestError as e: print(f"API call failed with code {e.code}: {e.content}") # Sync to get latest events sync_response = api.sync(timeout_ms=30000) print(f"Next batch token: {sync_response['next_batch']}") # Get room state state = api.get_room_state("!roomid:matrix.org") for event in state: print(f"State event: {event['type']}") # Set room topic api.set_room_topic("!roomid:matrix.org", "New topic via API") # Get user display name display_name = api.get_display_name("@user:matrix.org") print(f"User display name: {display_name}") ``` -------------------------------- ### GET /rooms/{roomId}/state/m.room.topic Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the topic of a specific room. ```APIDOC ## GET /rooms/{roomId}/state/m.room.topic ### Description Retrieves the topic of a specific room. ### Method GET ### Endpoint `/rooms/{roomId}/state/m.room.topic` ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. ``` -------------------------------- ### Perform Sync Request with Matrix Client (Python) Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Initiates a synchronization request to the Matrix server to receive updates. Allows specifying a starting point ('since'), a timeout, a filter, whether to request the full state, and presence updates. ```python api.sync(since=None, timeout_ms=30000, filter=None, full_state=None, set_presence=None) ``` -------------------------------- ### GET Key Changes Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves a list of users who have updated their device identity keys. ```APIDOC ## GET Key Changes ### Description Gets a list of users who have updated their device identity keys. ### Method GET ### Endpoint `/get_keys` (Implied) ### Parameters #### Query Parameters - **from_token** (str) - Required - The desired start point of the list. Should be the `next_batch` field from a response to an earlier call to `/sync`. - **to_token** (str) - Required - The desired end point of the list. Should be the `next_batch` field from a recent call to `/sync` - typically the most recent such call. ``` -------------------------------- ### Get Room Power Levels Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the power levels for a specific room. ```APIDOC ## GET /rooms/{room_id}/state/m.room.power_levels ### Description Perform GET /rooms/$room_id/state/m.room.power_levels ### Method GET ### Endpoint /rooms/{room_id}/state/m.room.power_levels ### Parameters #### Path Parameters * **room_id** (str) - Required - The room ID #### Query Parameters None #### Request Body None ### Response #### Success Response (200) * **users** (dict) - A dictionary mapping user IDs to their power levels. * **default** (int) - The default power level for users not explicitly listed. #### Response Example ```json { "users": { "@user1:matrix.org": 100 }, "default": 50 } ``` ``` -------------------------------- ### Initialize and Use MatrixClient in Python Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Demonstrates how to create a MatrixClient instance, register a new user, create a room, and send a message. It also shows how to log in with an existing token and add event listeners. ```python from matrix_client.api import MatrixClient # Create a new user and send a message: client = MatrixClient("https://matrix.org") token = client.register_with_password(username="foobar", password="monkey") room = client.create_room("myroom") room.send_image(file_like_object) # Send a message with an already logged in user: client = MatrixClient("https://matrix.org", token="foobar", user_id="@foobar:matrix.org") client.add_listener(func) # NB: event stream callback client.rooms[0].add_listener(func) # NB: callbacks just for this room. room = client.join_room("#matrix:matrix.org") response = room.send_text("Hello!") response = room.kick("@bob:matrix.org") # Incoming event callbacks (scopes): def user_callback(user, incoming_event): pass def room_callback(room, incoming_event): pass def global_callback(incoming_event): pass ``` -------------------------------- ### GET /rooms/{roomId}/messages Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves messages from a specific room. You can specify the direction, limit, and a token to start or stop returning events. ```APIDOC ## GET /rooms/{roomId}/messages ### Description Retrieves messages from a specific room. You can specify the direction, limit, and a token to start or stop returning events. ### Method GET ### Endpoint `/rooms/{roomId}/messages` ### Parameters #### Query Parameters - **room_id** (str) - Required - The room's id. - **token** (str) - Required - The token to start returning events from. - **direction** (str) - Required - The direction to return events from. One of: ["b", "f"]. - **limit** (int) - Optional - The maximum number of events to return. Defaults to 10. - **to** (str) - Optional - The token to stop returning events at. ``` -------------------------------- ### MatrixClient Constructor Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Initializes a new MatrixClient instance. This client provides an API for interacting with Matrix homeservers. ```APIDOC ## MatrixClient Constructor ### Description Initializes a new MatrixClient instance. This client provides an API for interacting with Matrix homeservers. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from matrix_client.client import MatrixClient # Example with authentication token client = MatrixClient("https://matrix.org", token="your_access_token") # Example for a new user registration client = MatrixClient("https://matrix.org") # Example with custom options client = MatrixClient( base_url="https://matrix.org", user_id="@user:matrix.org", valid_cert_check=False, cache_level=MatrixClient.CACHE.SOME, encryption=True ) ``` ### Response #### Success Response (200) Returns an initialized `MatrixClient` object. #### Response Example None (Constructor does not return a response in the typical HTTP sense). ``` -------------------------------- ### GET /rooms/{roomId}/state Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the state of a specific room. ```APIDOC ## GET /rooms/{roomId}/state ### Description Retrieves the state of a specific room. ### Method GET ### Endpoint `/rooms/{roomId}/state` ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. ``` -------------------------------- ### Create a New Matrix Room in Python Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Demonstrates the function to create a new room on the Matrix homeserver. It allows specifying an alias, public visibility, and inviting other users. ```python client = MatrixClient("https://matrix.org") # Create a public room with an alias new_room = client.create_room(alias="#my-public-room:matrix.org", is_public=True) # Create a private room and invite users new_room = client.create_room(is_public=False, invitees=["@user1:matrix.org", "@user2:matrix.org"]) ``` -------------------------------- ### GET /rooms/{roomId}/state/m.room.name Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the name of a specific room. ```APIDOC ## GET /rooms/{roomId}/state/m.room.name ### Description Retrieves the name of a specific room. ### Method GET ### Endpoint `/rooms/{roomId}/state/m.room.name` ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. ``` -------------------------------- ### MatrixClient Methods Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md This section covers various methods available on the MatrixClient instance for managing rooms, listeners, and user data. ```APIDOC ## MatrixClient Methods ### Description This section covers various methods available on the MatrixClient instance for managing rooms, listeners, and user data. ### `add_ephemeral_listener(callback, event_type=None)` Adds a listener for ephemeral events. * **Parameters:** * `callback` (func) - Callback function to be executed when an ephemeral event arrives. * `event_type` (str, optional) - The specific event type to filter for. Defaults to None (all ephemeral events). * **Returns:** `uuid.UUID` - A unique identifier for the listener. ### `add_invite_listener(callback)` Adds a listener for incoming room invites. * **Parameters:** * `callback` (func) - Callback function to be executed when an invite arrives. It receives `room_id` and `state` as arguments. ### `add_leave_listener(callback)` Adds a listener for when the client leaves a room. * **Parameters:** * `callback` (func) - Callback function to be executed when the client leaves a room. It receives `room_id` and the `room` object as arguments. ### `add_listener(callback, event_type=None)` Adds a general event listener. * **Parameters:** * `callback` (func) - Callback function to be executed when an event arrives. * `event_type` (str, optional) - The specific event type to filter for. Defaults to None (all events). * **Returns:** `uuid.UUID` - A unique identifier for the listener. ### `add_presence_listener(callback)` Adds a listener for presence updates. * **Parameters:** * `callback` (func) - Callback function to be executed when a presence update arrives. * **Returns:** `uuid.UUID` - A unique identifier for the listener. ### `create_room(alias=None, is_public=False, invitees=None)` Creates a new room on the homeserver. * **Parameters:** * `alias` (str, optional) - The canonical alias for the room. * `is_public` (bool, optional) - Determines if the room is public or private. Defaults to False. * `invitees` (list[str], optional) - A list of user IDs to invite to the room upon creation. * **Returns:** `Room` - An object representing the newly created room. * **Raises:** `MatrixRequestError` - If the room creation fails. ### `get_rooms()` Deprecated. Returns a dictionary of rooms the user has joined. * **Returns:** `dict` - A dictionary where keys are room IDs and values are `Room` objects. ### `get_sync_token()` Retrieves the current sync token. * **Returns:** `str` - The sync token. ### `users` (property) Provides access to a dictionary mapping user IDs to `User` objects. * **Type:** `dict` ``` -------------------------------- ### Get Room Members Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves a list of members for a given room. ```APIDOC ## GET /rooms/{room_id}/members ### Description Get the list of members for this room. ### Method GET ### Endpoint /rooms/{room_id}/members ### Parameters #### Path Parameters * **room_id** (str) - Required - The room to get the member events for. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) * **members** (list) - A list of membership events for the room. #### Response Example ```json [ { "sender": "@user1:matrix.org", "type": "m.room.member", "content": { "membership": "join", "displayname": "User One" } } ] ``` ``` -------------------------------- ### Matrix Client SDK - High-Level Client Usage Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/README.rst Demonstrates the high-level client usage for the Matrix SDK. This includes creating a client instance, registering a new user or logging in an existing one, creating a room, and sending a text message. ```python from matrix_client.client import MatrixClient client = MatrixClient("http://localhost:8008") # New user token = client.register_with_password(username="foobar", password="monkey") # Existing user token = client.login(username="foobar", password="monkey") room = client.create_room("my_room_alias") room.send_text("Hello!") ``` -------------------------------- ### POST /register Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Registers a new user or guest account. Allows for various registration options including username, password, and device details. ```APIDOC ## POST /register ### Description Registers a new user or guest account. Allows for various registration options including username, password, and device details. ### Method POST ### Endpoint `/register` ### Parameters #### Query Parameters - **kind** (str) - Optional - Specify kind of account to register. Can be ‘guest’ or ‘user’. - **bind_email** (bool) - Optional - Whether to use email in registration and authentication. - **username** (str) - Optional - The localpart of a Matrix ID. - **password** (str) - Optional - The desired password of the account. - **device_id** (str) - Optional - ID of the client device. - **initial_device_display_name** (str) - Optional - Display name to be assigned. - **inhibit_login** (bool) - Optional - Whether to login after registration. Defaults to false. #### Request Body - **auth_body** (dict) - Optional - Authentication Params. ### Request Example ```json { "auth_body": { "type": "m.login.password", "identifier": { "type": "m.id.user", "user": "username" }, "password": "password" } } ``` ### Response #### Success Response (200) - **access_token** (str) - The access token for the newly registered user. - **user_id** (str) - The Matrix ID of the new user. - **device_id** (str) - The device ID of the client. #### Response Example ```json { "access_token": "syt_abcdefghijklmnopqrstuvwxyz", "user_id": "@newuser:example.com", "device_id": "aBcDeFgHiJkLmNoPqRsT" } ``` ``` -------------------------------- ### Register New User Account (Python) Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Handles user registration on a Matrix homeserver, supporting both standard password-based registration and guest account creation. It returns an access token for the newly created user or guest. Requires `matrix_client.client` and `matrix_client.api`. ```python from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError client = MatrixClient("https://matrix.org") # Register new user with password try: token = client.register_with_password( username="newuser", password="securepassword" ) print(f"Registration successful, access token: {token}") print(f"User ID: {client.user_id}") except MatrixRequestError as e: print(f"Registration failed: {e}") # Register as guest (if homeserver allows) try: guest_token = client.register_as_guest() print(f"Guest registration successful: {guest_token}") except MatrixRequestError as e: print(f"Guest registration failed: {e}") ``` -------------------------------- ### Get Room Membership Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the membership state of a user in a specific room. ```APIDOC ## GET /rooms/{room_id}/state/m.room.member/{user_id} ### Description Perform GET /rooms/$room_id/state/m.room.member/$user_id ### Method GET ### Endpoint /rooms/{room_id}/state/m.room.member/{user_id} ### Parameters #### Path Parameters * **room_id** (str) - Required - The room ID * **user_id** (str) - Required - The user ID #### Query Parameters None #### Request Body None ### Response #### Success Response (200) * **membership** (str) - The membership state (e.g., 'join', 'leave'). * **displayname** (str) - The display name of the user. * **avatar_url** (str) - The avatar URL of the user. #### Response Example ```json { "membership": "join", "displayname": "Alice", "avatar_url": "mxc://matrix.org/avatar" } ``` ``` -------------------------------- ### POST /initialSync Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Performs an initial synchronization of the user's account. Deprecated; use sync instead. ```APIDOC ## POST /initialSync ### Description Performs an initial synchronization of the user's account. Deprecated; use sync instead. ### Method POST ### Endpoint `/initialSync` ### Parameters #### Query Parameters - **limit** (int) - Optional - The limit parameter to provide for the sync request. Defaults to 1. ``` -------------------------------- ### Get Room ID from Alias Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the room ID associated with a given room alias. ```APIDOC ## GET /room_alias/{room_alias} ### Description Get room id from its alias. ### Method GET ### Endpoint /room_alias/{room_alias} ### Parameters #### Path Parameters * **room_alias** (str) - Required - The room alias name. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) * **room_id** (str) - The room’s ID. #### Response Example ```json { "room_id": "!someroom:matrix.org" } ``` ``` -------------------------------- ### Initialize and Authenticate Matrix Client (Python) Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Initializes the MatrixClient and logs in using provided username and password. It handles potential authentication errors, returning an access token upon successful login. Requires the `matrix_client.client` and `matrix_client.api` modules. ```python from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError # Connect to homeserver client = MatrixClient("https://matrix.org") # Login with existing user credentials try: token = client.login(username="myuser", password="mypassword") print(f"Logged in with token: {token}") print(f"User ID: {client.user_id}") except MatrixRequestError as e: if e.code == 403: print("Invalid username or password") else: print(f"Login failed: {e}") ``` -------------------------------- ### GET /rooms/{roomId}/state/{event_type} Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves a specific state event from a room. Raises MatrixRequestError with code 404 if the event is not found. ```APIDOC ## GET /rooms/{roomId}/state/{event_type} ### Description Retrieves a specific state event from a room. Raises MatrixRequestError with code 404 if the event is not found. ### Method GET ### Endpoint `/rooms/{roomId}/state/{event_type}` ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. - **event_type** (str) - Required - The type of the event. ``` -------------------------------- ### Room Management Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md APIs for interacting with Matrix rooms. ```APIDOC ## POST /rooms/{room_id_or_alias}/join ### Description Joins a Matrix room using its ID or alias. ### Method POST ### Endpoint /rooms/{room_id_or_alias}/join ### Parameters #### Path Parameters - **room_id_or_alias** (str) - Required - The ID or alias of the room to join. ### Request Example ```json { "room_id_or_alias": "!abcdefg:matrix.org" } ``` ### Response #### Success Response (200) - **Room** (object) - The joined Room object. #### Response Example ```json { "room_id": "!abcdefg:matrix.org", "name": "Example Room" } ``` #### Errors - **MatrixRequestError** - If joining the room fails. ``` ```APIDOC ## DELETE /_matrix/client/r0/directory/aliases/{room_alias} ### Description Removes the mapping of a room alias. ### Method DELETE ### Endpoint /_matrix/client/r0/directory/aliases/{room_alias} ### Parameters #### Path Parameters - **room_alias** (str) - Required - The alias to be removed. ### Request Example ```json { "room_alias": "#myalias:matrix.org" } ``` ### Response #### Success Response (200) - **success** (bool) - True if the alias is removed, False otherwise. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Get Authenticated User ID (Python) Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Determines and returns the user ID of the currently authenticated user on the Matrix server. This is a utility function for identifying the active user. ```python api.whoami() ``` -------------------------------- ### Get Room Membership Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Retrieves the membership state of a specific user within a given Matrix room. This is useful for checking if a user has joined, left, or been invited to a room. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="foobar") membership_event = matrix.get_membership(room_id="!roomid:matrix.org", user_id="@user:matrix.org") ``` -------------------------------- ### Media Download and Upload Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Handles downloading and uploading media files, including generating thumbnails. ```APIDOC ## Media Download ### Description Download raw media from provided mxc URL. ### Method GET (Implicit) ### Endpoint `/media/...` (Derived from mxcUrl) ### Parameters #### Query Parameters - **mxcurl** (str) - Required - mxc media URL. - **allow_remote** (bool) - Optional - Indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true. ## Media Upload ### Description Uploads media content to the Matrix server. ### Method POST (Implicit) ### Endpoint `/media/upload` (Implicit) ### Parameters #### Request Body - **content** (bytes/file) - Required - The media content to upload. - **content_type** (str) - Required - The MIME type of the content. - **filename** (str) - Optional - The name of the file. ## Media Thumbnail Download ### Description Download raw media thumbnail from provided mxc URL. ### Method GET (Implicit) ### Endpoint `/media/.../thumbnail` (Derived from mxcUrl) ### Parameters #### Query Parameters - **mxcurl** (str) - Required - mxc media URL. - **width** (int) - Required - Desired thumbnail width. - **height** (int) - Required - Desired thumbnail height. - **method** (str) - Optional - Thumb creation method. Must be in ['scale', 'crop']. Defaults to 'scale'. - **allow_remote** (bool) - Optional - Indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true. ``` -------------------------------- ### Get Room ID from Alias Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Converts a Matrix room alias (e.g., '#myroom:matrix.org') into its corresponding room ID (e.g., '!abcdefg:matrix.org'). This is often needed when interacting with rooms via their human-readable aliases. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="foobar") room_id = matrix.get_room_id("#myroom:matrix.org") ``` -------------------------------- ### Event Synchronization and Backfill with matrix-python-sdk Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Demonstrates synchronizing events, including continuous listening with error handling, and backfilling message history. Also shows how to access event history and retrieve joined room members. Requires client login and joining a room. ```python from matrix_client.client import MatrixClient client = MatrixClient("https://matrix.org") client.login(username="myuser", password="mypassword") room = client.join_room("#history:matrix.org") # Manual sync to get latest events client.listen_for_events(timeout_ms=30000) # Continuous listening with error handling def handle_sync_error(exception): print(f"Sync error occurred: {exception}") # Custom error handling logic client.listen_forever( timeout_ms=30000, exception_handler=handle_sync_error, bad_sync_timeout=5 ) # Backfill previous messages room.backfill_previous_messages(reverse=False, limit=50) # Access event history events = room.get_events() for event in events: if event['type'] == "m.room.message": print(f"{event['sender']}: {event['content']['body']}") # Get joined members members = room.get_joined_members() for member in members: print(f"Member: {member.user_id} - {member.get_display_name(room)}") ``` -------------------------------- ### User Profile Management with Python Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Shows how to retrieve and update user profile information, including display names and avatars. It demonstrates fetching a user's details, setting one's own display name and avatar, and also setting room-specific profile information. ```python from matrix_client.client import MatrixClient from matrix_client.user import User client = MatrixClient("https://matrix.org") client.login(username="myuser", password="mypassword") # Get user profile information user = User(client.api, "@someone:matrix.org") display_name = user.get_display_name() avatar_url = user.get_avatar_url() print(f"Display name: {display_name}") print(f"Avatar URL: {avatar_url}") # Set your own display name user = User(client.api, client.user_id) user.set_display_name("My New Name") # Upload and set avatar with open("avatar.png", "rb") as f: avatar_data = f.read() mxc_url = client.upload(avatar_data, "image/png", "avatar.png") user.set_avatar_url(mxc_url) # Set room-specific profile room = client.join_room("#myroom:matrix.org") room.set_user_profile( displayname="Room Nickname", avatar_url=mxc_url, reason="Updating room profile" ) ``` -------------------------------- ### Create Room Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Creates a new Matrix room with specified parameters. ```APIDOC ## POST /createRoom ### Description Perform /createRoom. ### Method POST ### Endpoint /createRoom ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **alias** (str) - Optional - The room alias name to set for this room. * **name** (str) - Optional - Name for new room. * **is_public** (bool) - Optional - The public/private visibility. Defaults to False. * **invitees** (list[str]) - Optional - The list of user IDs to invite. * **federate** (bool) - Optional - Can a room be federated. Defaults to True. ### Request Example ```json { "name": "My New Room", "is_public": true, "invitees": ["@bob:example.org"] } ``` ### Response #### Success Response (200) * **room_id** (str) - The ID of the newly created room. * **room_alias** (str) - The alias of the newly created room, if provided. #### Response Example ```json { "room_id": "!newroom:example.org", "room_alias": "#newroom:example.org" } ``` ``` -------------------------------- ### Upload Content Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Uploads content to the homeserver and returns an MXC URL for the uploaded content. ```APIDOC ## POST /upload ### Description Upload content to the home server and receive a MXC url. ### Method POST ### Endpoint /upload ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **content** (bytes) - Required - The data of the content. * **content_type** (str) - Required - The mimetype of the content. * **filename** (str) - Optional - Filename of the content. ### Request Example ```json { "content": "", "content_type": "image/jpeg", "filename": "photo.jpg" } ``` ### Response #### Success Response (200) * **mxc_url** (str) - The MXC URL of the uploaded content. #### Response Example ```json { "mxc_url": "mxc://matrix.org/abcdefg" } ``` ### Errors * **MatrixUnexpectedResponse** - If the homeserver gave a strange response. * **MatrixRequestError** - If the upload failed for some reason. ``` -------------------------------- ### Room Join Rule API Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Configure the rule that governs how users can join a room. ```APIDOC ## POST /rooms/{roomId}/state/m.room.join_rule ### Description Sets the rule for users wishing to join the room. ### Method POST ### Endpoint `/rooms/{roomId}/state/m.room.join_rule` ### Parameters #### Path Parameters - **roomId** (str) - Required - The room to set the rules for. #### Request Body - **join_rule** (str) - Required - The chosen rule. One of: ["public", "knock", "invite", "private"] ### Response #### Success Response (200) - **content** (dict) - The response content indicating success. #### Response Example ```json { "content": {} } ``` ``` -------------------------------- ### Create Room Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Shows how to create a new Matrix room. This function allows specifying room name, visibility, initial invitees, and whether the room should be federated. It returns the newly created room's ID. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="foobar") new_room_id = matrix.create_room(name="My New Room", is_public=True, invitees=["@user:matrix.org"]) ``` -------------------------------- ### Matrix Client SDK - Low-Level API Usage Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/README.rst Illustrates the low-level API interaction with the Matrix SDK. This involves creating a MatrixHttpApi instance with a server URL and an access token to send messages to a room. ```python from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token="some_token") response = matrix.send_message("!roomid:matrix.org", "Hello!") ``` -------------------------------- ### Basic Chat Client Implementation with Python Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Implements a simple interactive chat client that connects to a Matrix server, logs in, joins a room, and handles incoming messages while allowing users to send messages. It requires the matrix-client library and uses basic Python constructs for input/output and error handling. ```python #!/usr/bin/env python3 from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError import sys def on_message(room, event): if event['type'] == "m.room.member": if event['membership'] == "join": print(f"{event['content']['displayname']} joined") elif event['type'] == "m.room.message": if event['content']['msgtype'] == "m.text": print(f"{event['sender']}: {event['content']['body']}") def main(): client = MatrixClient("https://matrix.org") try: client.login("myuser", "mypassword") except MatrixRequestError as e: if e.code == 403: print("Bad username or password") sys.exit(1) else: print("Login failed") sys.exit(2) try: room = client.join_room("#general:matrix.org") except MatrixRequestError as e: print(f"Failed to join room: {e}") sys.exit(3) room.add_listener(on_message) client.start_listener_thread() print("Chat client started. Type /quit to exit.") while True: msg = input() if msg == "/quit": break else: room.send_text(msg) client.stop_listener_thread() if __name__ == '__main__': main() ``` -------------------------------- ### Upload and Send Media with Python Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Demonstrates how to upload various media types (images, videos, audio) to a Matrix server and then send them to a specific room. It utilizes the `upload` method for sending files and corresponding `send_image`, `send_video`, and `send_audio` methods for room messages. ```python from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError client = MatrixClient("https://matrix.org") client.login(username="myuser", password="mypassword") room = client.join_room("#media:matrix.org") # Upload image file try: with open("photo.jpg", "rb") as f: image_data = f.read() mxc_url = client.upload( content=image_data, content_type="image/jpeg", filename="photo.jpg" ) print(f"Uploaded to: {mxc_url}") # Send image to room room.send_image( url=mxc_url, name="photo.jpg", w=1920, h=1080, size=len(image_data), mimetype="image/jpeg" ) except MatrixRequestError as e: print(f"Upload failed: {e}") # Send video with open("video.mp4", "rb") as f: video_data = f.read() video_url = client.upload(video_data, "video/mp4", "video.mp4") room.send_video( url=video_url, name="video.mp4", duration=120000, # milliseconds size=len(video_data) ) # Send audio file with open("audio.mp3", "rb") as f: audio_data = f.read() audio_url = client.upload(audio_data, "audio/mpeg", "audio.mp3") room.send_audio(url=audio_url, name="audio.mp3", duration=180000) ``` -------------------------------- ### Query Keys API Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Queries the homeserver for public keys by user and optionally by device. ```APIDOC ## Query Keys API ### Description Queries the homeserver for public keys by user and optionally by device. ### Method POST (Implied) ### Endpoint `/keys/query` ### Parameters #### Request Body - **user_devices** (dict) - Required - The devices whose keys to download. Should be formatted as `: []`. No `device_ids` indicates all devices for the corresponding user. #### Query Parameters - **timeout** (int) - Optional - The time (in milliseconds) to wait when downloading keys from remote servers. - **token** (str) - Optional - If the client is fetching keys as a result of a device update received in a sync request, this should be the `since` token of that sync request, or any later sync token. ``` -------------------------------- ### User Membership Actions Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md Manages user membership in rooms, including kicking and leaving. ```APIDOC ## Kick User ### Description Removes a user from a room. ### Method POST (Implicitly calls set_membership with membership='leave') ### Endpoint `/rooms/{roomId}/kick` (Implied) ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. #### Request Body - **user_id** (str) - Required - The user ID to kick. - **reason** (str) - Optional - The reason for kicking the user. Defaults to an empty string. ## Leave Room ### Description Leaves a specific room. ### Method POST ### Endpoint `/rooms/{roomId}/leave` ### Parameters #### Path Parameters - **room_id** (str) - Required - The room ID. ``` -------------------------------- ### Event Listening Source: https://github.com/matrix-org/matrix-python-sdk/blob/master/docs/source/matrix_client.md APIs for listening to and managing event streams. ```APIDOC ## POST /sync ### Description Polls the homeserver for new events. This is a low-level method that `listen_for_events` and `listen_forever` use. ### Method POST ### Endpoint /sync ### Parameters #### Query Parameters - **timeout_ms** (int) - Optional - How long to poll the Home Server for before retrying. Defaults to 30000. ### Request Example ```json { "timeout_ms": 60000 } ``` ### Response #### Success Response (200) - **sync_data** (object) - Data returned from the /sync request, containing events and state. #### Response Example ```json { "next_batch": "t300_abc...", "rooms": { ... } } ``` ``` ```APIDOC ## Background Event Listening ### Description Manages background threads for listening to Matrix events. ### Methods - **start_listener_thread(timeout_ms=30000, exception_handler=None)**: Starts a listener thread to listen for events in the background. - **Parameters:** - **timeout_ms** (int) - How long to poll the Home Server for before retrying. - **exception_handler** (func) - Optional exception handler function. - **stop_listener_thread()**: Stops the background listener thread. - **listen_forever(timeout_ms=30000, exception_handler=None, bad_sync_timeout=5)**: Keeps listening for events forever in the current thread. This method will block. - **Parameters:** - **timeout_ms** (int) - How long to poll the Home Server for before retrying. - **exception_handler** (func) - Optional exception handler function. - **bad_sync_timeout** (int) - Base time to wait after an error before retrying. ### Event Listener Management - **remove_ephemeral_listener(uid)**: Removes an ephemeral listener by its unique ID. - **remove_listener(uid)**: Removes a general listener by its unique ID. - **remove_presence_listener(uid)**: Removes a presence listener by its unique ID. ``` -------------------------------- ### Listen for Matrix Room Events (Python) Source: https://context7.com/matrix-org/matrix-python-sdk/llms.txt Sets up event listeners to receive real-time updates from Matrix rooms. Supports both global listeners for all events and room-specific listeners. Requires an authenticated client instance and initiates a background thread to handle incoming events. ```python from matrix_client.client import MatrixClient import time client = MatrixClient("https://matrix.org") client.login(username="myuser", password="mypassword") # Global listener for all events def global_message_handler(event): if event['type'] == "m.room.message": print(f"Global: {event['sender']}: {event['content']['body']}") client.add_listener(global_message_handler, event_type="m.room.message") # Room-specific listener room = client.join_room("#myroom:matrix.org") def room_message_handler(room_obj, event): if event['type'] == "m.room.message": sender = event['sender'] body = event['content']['body'] print(f"[{room_obj.display_name}] {sender}: {body}") listener_id = room.add_listener(room_message_handler) # Start background listener thread client.start_listener_thread() ```