mautrix.client.api

class mautrix.client.ClientAPI

ClientAPI is a medium-level wrapper around the HTTPAPI that provides many easy-to-use functions for accessing the client-server API.

This class can be used directly, but generally you should use the higher-level wrappers that inherit from this class, such as mautrix.client.Client or mautrix.appservice.IntentAPI.

Examples

>>> from mautrix.client import ClientAPI
>>> client = ClientAPI("@user:matrix.org", base_url="https://matrix-client.matrix-org",
                       token="syt_123_456")
>>> await client.whoami()
WhoamiResponse(user_id="@user:matrix.org", device_id="DEV123")
>>> await client.get_joined_rooms()
["!roomid:matrix.org"]
__init__(mxid='', device_id='', api=None, **kwargs)

Initialize a ClientAPI. You must either provide the api parameter with an existing mautrix.api.HTTPAPI instance, or provide the base_url and other arguments for creating it as kwargs.

Parameters
  • mxid (mautrix.types.UserID) – The Matrix ID of the user. This is used for things like setting profile metadata. Additionally, the homeserver domain is extracted from this string and used for setting aliases and such. This can be changed later using set_mxid.

  • device_id (mautrix.types.DeviceID) – The device ID corresponding to the access token used.

  • api (Optional[mautrix.api.HTTPAPI]) – The mautrix.api.HTTPAPI instance to use. You can also pass the kwargs to create a HTTPAPI instance rather than creating the instance yourself.

  • kwargs – If api is not specified, then the arguments to pass when creating a HTTPAPI.

Return type

None

async add_room_alias(room_id, alias_localpart, override=False)

Create a new mapping from room alias to room ID.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The room ID to set.

  • alias_localpart (str) – The localpart of the room alias to set.

  • override (bool) – Whether or not the alias should be removed and the request retried if the server responds with HTTP 409 Conflict

Return type

None

async ban_user(room_id, user_id, reason='', extra_content=None)

Ban a user in the room. If the user is currently in the room, also kick them. When a user is banned from a room, they may not join it or be invited to it until they are unbanned. The caller must have the required power level in order to perform this operation.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room from which the user should be banned.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the user being banned.

  • reason (str) – The reason the user has been kicked. This will be supplied as the reason on the target’s updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the ban event content. If a non-empty dict is passed, the ban will be created using the PUT /state/m.room.member/... endpoint instead of POST /ban.

Return type

None

async beeper_update_profile(custom_fields)

Set custom fields on the user’s profile. Only works on Hungryserv.

Parameters

custom_fields (dict[str, typing.Any]) – A dictionary of fields to set in the custom content of the profile.

Return type

None

async claim_keys(one_time_keys, timeout=10000)

Claim one-time keys for use in pre-key messages.

See also: API reference

Parameters
Returns

One-time keys for the queried devices and errors for homeservers that could not be reached.

Return type

mautrix.types.ClaimKeysResponse

async create_filter(filter_params)

Upload a new filter definition to the homeserver.

See also: API reference

Parameters

filter_params (mautrix.types.Filter) – The filter data.

Returns

A filter ID that can be used in future requests to refer to the uploaded filter.

Return type

mautrix.types.FilterID

async create_mxc()

Create a media ID for uploading media to the homeserver.

See also: API reference

Returns

MediaCreateResponse Containing the MXC URI that can be used to upload a file to later

Return type

mautrix.types.MediaCreateResponse

async create_room(alias_localpart=None, visibility=RoomDirectoryVisibility.PRIVATE, preset=RoomCreatePreset.PRIVATE, name=None, topic=None, is_direct=False, invitees=None, initial_state=None, room_version=None, creation_content=None, power_level_override=None, beeper_auto_join_invites=False, custom_request_fields=None)

Create a new room with various configuration options.

See also: API reference

Parameters
  • alias_localpart (Optional[str]) – The desired room alias local part. If this is included, a room alias will be created and mapped to the newly created room. The alias will belong on the same homeserver which created the room. For example, if this was set to “foo” and sent to the homeserver “example.com” the complete room alias would be #foo:example.com.

  • visibility (mautrix.types.RoomDirectoryVisibility) – A public visibility indicates that the room will be shown in the published room list. A private visibility will hide the room from the published room list. Defaults to private. NB: This should not be confused with join_rules which also uses the word public.

  • preset (mautrix.types.RoomCreatePreset) – Convenience parameter for setting various default state events based on a preset. Defaults to private (invite-only).

  • name (Optional[str]) – If this is included, an m.room.name event will be sent into the room to indicate the name of the room. See Room Events for more information on m.room.name.

  • topic (Optional[str]) – If this is included, an m.room.topic event will be sent into the room to indicate the topic for the room. See Room Events for more information on m.room.topic.

  • is_direct (bool) – This flag makes the server set the is_direct flag on the m.room.member events sent to the users in invite and invite_3pid. See Direct Messaging for more information.

  • invitees (Optional[list[mautrix.types.UserID]]) – A list of user IDs to invite to the room. This will tell the server to invite everyone in the list to the newly created room.

  • initial_state (Optional[list[mautrix.types.StateEvent | mautrix.types.StrippedStateEvent | dict[str, mautrix.types.JSON]]]) –

    A list of state events to set in the new room. This allows the user to override the default state events set in the new room. The expected format of the state events are an object with type, state_key and content keys set.

    Takes precedence over events set by is_public, but gets overriden by name and topic keys.

  • room_version (Optional[str]) – The room version to set for the room. If not provided, the homeserver will use its configured default.

  • creation_content (Optional[Union[mautrix.types.RoomCreateStateEventContent, dict[str, mautrix.types.JSON]]]) – Extra keys, such as m.federate, to be added to the m.room.create event. The server will ignore creator and room_version. Future versions of the specification may allow the server to ignore other keys.

  • power_level_override (Optional[Union[mautrix.types.PowerLevelStateEventContent, dict[str, mautrix.types.JSON]]]) – The power level content to override in the default power level event. This object is applied on top of the generated m.room.power_levels event content prior to it being sent to the room. Defaults to overriding nothing.

  • beeper_auto_join_invites (bool) – A Beeper-specific extension which auto-joins all members in the invite array instead of sending invites.

  • custom_request_fields (Optional[dict[str, typing.Any]]) – Additional fields to put in the top-level /createRoom content. Non-custom fields take precedence over fields here.

Returns

The ID of the newly created room.

Raises

MatrixResponseError – If the response does not contain a room_id field.

Return type

mautrix.types.RoomID

async classmethod discover(domain, session=None)

Follow the server discovery spec to find the actual URL when given a Matrix server name.

Parameters
  • domain (str) – The server name (end of user ID) to discover.

  • session (Optional[aiohttp.ClientSession]) – Optionally, the aiohttp ClientSession object to use.

Returns

The parsed URL if the discovery succeeded. None if the request returned a 404 status.

Raises

WellKnownError – for other errors

Return type

yarl.URL | None

async download_media(url, timeout_ms=None)

Download a file from the content repository.

See also: API reference

Parameters
  • url (mautrix.types.ContentURI) – The MXC URI to download.

  • timeout_ms (Optional[int]) – The maximum number of milliseconds that the client is willing to wait to start receiving data. Used for asynchronous uploads.

Returns

The raw downloaded data.

Return type

bytes

async download_thumbnail(url, width=None, height=None, resize_method=None, allow_remote=None, timeout_ms=None)

Download a thumbnail for a file in the content repository.

See also: API reference

Parameters
  • url (mautrix.types.ContentURI) – The MXC URI to download.

  • width (Optional[int]) – The _desired_ width of the thumbnail. The actual thumbnail may not match the size specified.

  • height (Optional[int]) – The _desired_ height of the thumbnail. The actual thumbnail may not match the size specified.

  • resize_method (Optional[Literal['crop', 'scale']]) – The desired resizing method. Either crop or scale.

  • allow_remote (Optional[bool]) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.

  • timeout_ms (Optional[int]) – The maximum number of milliseconds that the client is willing to wait to start receiving data. Used for asynchronous Uploads.

Returns

The raw downloaded data.

async fill_member_event(room_id, user_id, content)

Fill a membership event content that is going to be sent in send_member_event().

This is used to set default fields like the displayname and avatar, which are usually set by the server in the sugar membership endpoints like /join and /invite, but are not set automatically when sending member events manually.

This default implementation only calls fill_member_event_callback.

Parameters
Returns

The filled member event content.

Return type

mautrix.types.MemberStateEventContent | None

async forget_room(room_id)

Stop remembering a particular room, i.e. forget it.

In general, history is a first class citizen in Matrix. After this API is called, however, a user will no longer be able to retrieve history for this room. If all users on a homeserver forget a room, the room is eligible for deletion from that homeserver.

If the user is currently joined to the room, they must leave the room before calling this API.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room to forget.

Return type

None

async get_account_data(type, room_id=None)

Get a specific account data event from the homeserver.

See also: API reference

Parameters
Returns

The data in the event.

Return type

mautrix.types.JSON

async get_avatar_url(user_id)

Get the avatar URL of a user.

See also: API reference

Parameters

user_id (mautrix.types.UserID) – The ID of the user whose avatar to get.

Returns

The mxc:// URI to the user’s avatar.

Return type

Optional[mautrix.types.ContentURI]

async get_displayname(user_id)

Get the display name of a user.

See also: API reference

Parameters

user_id (mautrix.types.UserID) – The ID of the user whose display name to get.

Returns

The display name of the given user.

Return type

str | None

async get_event(room_id, event_id)

Get a single event based on room_id/event_id. You must have permission to retrieve this event e.g. by being a member in the room for this event.

See also: API reference

Parameters
Returns

The event.

Return type

mautrix.types.Event

async get_event_context(room_id, event_id, limit=10, filter=None)

Get a number of events that happened just before and after the specified event. This allows clients to get the context surrounding an event, as well as get the state at an event and paginate in either direction.

Parameters
  • room_id (mautrix.types.RoomID) – The room to get events from.

  • event_id (mautrix.types.EventID) – The event to get context around.

  • limit (int | None) – The maximum number of events to return. The limit applies to the total number of events before and after the requested event. A limit of 0 means no other events are returned, while 2 means one event before and one after are returned.

  • filter (Optional[mautrix.types.RoomEventFilter]) – A JSON RoomEventFilter_ to filter returned events with.

Returns

The event itself, up to limit/2 events before and after the event, the room state at the event, and pagination tokens to scroll up and down.

Return type

mautrix.types.EventContext

async get_filter(filter_id)

Download a filter.

See also: API reference

Parameters

filter_id (mautrix.types.FilterID) – The filter ID to download.

Returns

The filter data.

Return type

mautrix.types.Filter

async get_joined_members(room_id)

Get a user ID -> member info map for a room. The current user must be in the room for it to work, unless it is an Application Service in which case any of the AS’s users must be in the room. This API is primarily for Application Services and should be faster to respond than /members as it can be implemented more efficiently on the server.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room to get the members of.

Returns

A dictionary from user IDs to Member info objects.

Return type

dict[mautrix.types.UserID, mautrix.types.Member]

async get_joined_rooms()

Get the list of rooms the user is in.

Return type

list[mautrix.types.RoomID]

async get_login_flows()

Get login flows supported by the homeserver.

See also: API reference

Returns

The list of login flows that the homeserver supports.

Return type

mautrix.types.LoginFlowList

async get_media_repo_config()

This endpoint allows clients to retrieve the configuration of the content repository, such as upload limitations. Clients SHOULD use this as a guide when using content repository endpoints. All values are intentionally left optional. Clients SHOULD follow the advice given in the field description when the field is not available.

NOTE: Both clients and server administrators should be aware that proxies between the client and the server may affect the apparent behaviour of content repository APIs, for example, proxies may enforce a lower upload size limit than is advertised by the server on this endpoint.

See also: API reference

Returns

The media repository config.

Return type

mautrix.types.MediaRepoConfig

async get_members(room_id, at=None, membership=None, not_membership=None)

Get the list of members for a room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to get the member events for.

  • at (Optional[mautrix.types.SyncToken]) – The point in time (pagination token) to return members for in the room. This token can be obtained from a prev_batch token returned for each room by the sync API. Defaults to the current state of the room, as determined by the server.

  • membership (Optional[mautrix.types.Membership]) – The kind of membership to filter for. Defaults to no filtering if unspecified. When specified alongside not_membership, the two parameters create an ‘or’ condition: either the membership is the same as membership or is not the same as not_membership.

  • not_membership (Optional[mautrix.types.Membership]) – The kind of membership to exclude from the results. Defaults to no filtering if unspecified.

Returns

A list of most recent member events for each user.

Return type

list[mautrix.types.StateEvent]

async get_messages(room_id, direction, from_token=None, to_token=None, limit=None, filter_json=None)

Get a list of message and state events for a room. Pagination parameters are used to paginate history in the room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to get events from.

  • direction (mautrix.types.PaginationDirection) – The direction to return events from.

  • from_token (Optional[mautrix.types.SyncToken]) –

    The token to start returning events from. This token can be obtained from a prev_batch token returned for each room by the sync endpoint, or from a start or end token returned by a previous request to this endpoint.

    Starting from Matrix v1.3, this field can be omitted to fetch events from the beginning or end of the room.

  • to_token (Optional[mautrix.types.SyncToken]) – The token to stop returning events at.

  • limit (Optional[int]) – The maximum number of events to return. Defaults to 10.

  • filter_json (Optional[Union[str, dict, mautrix.types.RoomEventFilter]]) – A JSON RoomEventFilter_ to filter returned events with.

Return type

mautrix.types.PaginatedMessages

Returns:

async get_presence(user_id)

Get the presence info of a user.

See also: API reference

Parameters

user_id (mautrix.types.UserID) – The ID of the user whose presence info to get.

Returns

The presence info of the given user.

Return type

mautrix.types.PresenceEventContent

async get_profile(user_id)

Get the combined profile information for a user.

See also: API reference

Parameters

user_id (mautrix.types.UserID) – The ID of the user whose profile to get.

Returns

The profile information of the given user.

Return type

mautrix.types.Member

async get_push_rule(scope, kind, rule_id)

Retrieve a single specified push rule.

See also: API reference

Parameters
Returns

The push rule information.

Return type

mautrix.types.PushRule

async get_room_directory(limit=None, server=None, since=None, search_query=None, include_all_networks=None, third_party_instance_id=None)

Get a list of public rooms from the server’s room directory.

See also: API reference

Parameters
  • limit (Optional[int]) – The maximum number of results to return.

  • server (Optional[str]) – The server to fetch the room directory from. Defaults to the user’s server.

  • since (Optional[mautrix.types.DirectoryPaginationToken]) – A pagination token from a previous request, allowing clients to get the next (or previous) batch of rooms. The direction of pagination is specified solely by which token is supplied, rather than via an explicit flag.

  • search_query (Optional[str]) – A string to search for in the room metadata, e.g. name, topic, canonical alias etc.

  • include_all_networks (Optional[bool]) – Whether or not to include rooms from all known networks/protocols from application services on the homeserver. Defaults to false.

  • third_party_instance_id (Optional[str]) – The specific third party network/protocol to request from the homeserver. Can only be used if include_all_networks is false.

Returns

The relevant pagination tokens, an estimate of the total number of public rooms and the paginated chunk of public rooms.

Return type

mautrix.types.RoomDirectoryResponse

async get_room_directory_visibility(room_id)

Get the visibility of the room on the server’s public room directory.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room.

Returns

The visibility of the room in the directory.

Return type

mautrix.types.RoomDirectoryVisibility

async get_room_tag(room_id, tag)

Get the info of a specific tag for a room.

Parameters
Returns

The info about the tag, or None if the room does not have the specified tag.

Return type

mautrix.types.RoomTagInfo | None

async get_room_tags(room_id)

Get all tags for a specific room. This is equivalent to getting the m.tag account data event for the room.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The room ID to get tags from.

Returns

The m.tag account data event.

Return type

mautrix.types.RoomTagAccountDataEventContent

async get_state(room_id)

Get the state events for the current state of a room.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room to look up the state for.

Returns

A list of state events with the most recent of each event_type/state_key pair.

Return type

list[mautrix.types.StateEvent]

async get_state_event(room_id, event_type, state_key='')

Looks up the contents of a state event in a room. If the user is joined to the room then the state is taken from the current state of the room. If the user has left the room then the state is taken from the state of the room when they left.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to look up the state in.

  • event_type (mautrix.types.EventType) – The type of state to look up.

  • state_key (str) – The key of the state to look up. Defaults to empty string.

Returns

The state event.

Return type

mautrix.types.StateEventContent

async get_url_preview(url, timestamp=None)

Get information about a URL for a client.

See also: API reference

Parameters
  • url (str) – The URL to get a preview of.

  • timestamp (Optional[int]) – 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.

Return type

mautrix.types.MXOpenGraph

async invite_user(room_id, user_id, reason=None, extra_content=None)

Invite a user to participate in a particular room. They do not start participating in the room until they actually join the room.

Only users currently in the room can invite other users to join that room.

If the user was invited to the room, the homeserver will add a m.room.member event to the room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to which to invite the user.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the invitee.

  • reason (Optional[str]) – The reason the user was invited. This will be supplied as the reason on the m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the invite event content. If a non-empty dict is passed, the invite event will be created using the PUT /state/m.room.member/... endpoint instead of POST /invite.

Return type

None

async join_room(room_id_or_alias, servers=None, third_party_signed=None, max_retries=4)

Start participating in a room, i.e. join it by its ID or alias, with an optional list of servers to ask about the ID from.

See also: API reference

Parameters
  • room_id_or_alias (Union[mautrix.types.RoomID, mautrix.types.RoomAlias]) – The ID of the room to join, or an alias pointing to the room.

  • servers (Optional[list[str]]) – A list of servers to ask about the room ID to join. Not applicable for aliases, as aliases already contain the necessary server information.

  • third_party_signed (Optional[mautrix.types.JSON]) – A signature of an m.third_party_invite token to prove that this user owns a third party identity which has been invited to the room.

  • max_retries (int) – The maximum number of retries. Used to circumvent a Synapse bug with accepting invites over federation. 0 means only one join call will be attempted. See: matrix-org/synapse#2807

Returns

The ID of the room the user joined.

Return type

mautrix.types.RoomID

async join_room_by_id(room_id, third_party_signed=None, extra_content=None)

Start participating in a room, i.e. join it by its ID.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to join.

  • third_party_signed (Optional[mautrix.types.JSON]) – A signature of an m.third_party_invite token to prove that this user owns a third party identity which has been invited to the room.

  • extra_content (Optional[dict[str, typing.Any]]) – Additional properties for the join event content. If a non-empty dict is passed, the join event will be created using the PUT /state/m.room.member/... endpoint instead of POST /join.

Returns

The ID of the room the user joined.

Return type

mautrix.types.RoomID

async kick_user(room_id, user_id, reason='', extra_content=None)

Kick a user from the room.

The caller must have the required power level in order to perform this operation.

Kicking a user adjusts the target member’s membership state to be leave with an optional reason. Like with other membership changes, a user can directly adjust the target member’s state by calling EventMethods.send_state_event() with EventType.ROOM_MEMBER as the event type and the user_id as the state key.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room from which the user should be kicked.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the user being kicked.

  • reason (str) – The reason the user has been kicked. This will be supplied as the reason on the target’s updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the kick event content. If a non-empty dict is passed, the kick event will be created using the PUT /state/m.room.member/... endpoint instead of POST /kick.

Return type

None

async knock_room(room_id_or_alias, reason=None, servers=None)

Knock on a room, i.e. request to join it by its ID or alias, with an optional list of servers to ask about the ID from.

See also: API reference

Parameters
  • room_id_or_alias (Union[mautrix.types.RoomID, mautrix.types.RoomAlias]) – The ID of the room to knock on, or an alias pointing to the room.

  • reason (Optional[str]) – The reason for knocking on the room. This will be supplied as the reason on the updated m.room.member event.

  • servers (Optional[list[str]]) – A list of servers to ask about the room ID to knock. Not applicable for aliases, as aliases already contain the necessary server information.

Returns

The ID of the room the user knocked on.

Return type

mautrix.types.RoomID

async leave_room(room_id, reason=None, extra_content=None, raise_not_in_room=False)

Stop participating in a particular room, i.e. leave the room.

If the user was already in the room, they will no longer be able to see new events in the room. If the room requires an invite to join, they will need to be re-invited before they can re-join.

If the user was invited to the room, but had not joined, this call serves to reject the invite.

The user will still be allowed to retrieve history from the room which they were previously allowed to see.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to leave.

  • reason (Optional[str]) – The reason for leaving the room. This will be supplied as the reason on the updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the leave event content. If a non-empty dict is passed, the leave event will be created using the PUT /state/m.room.member/... endpoint instead of POST /leave.

  • raise_not_in_room (bool) – Should errors about the user not being in the room be raised?

Return type

None

async login(identifier=None, login_type=<LoginType.PASSWORD: 'm.login.password'>, device_name=None, device_id=None, password=None, store_access_token=True, update_hs_url=False, **kwargs)

Authenticates the user, and issues an access token they can use to authorize themself in subsequent requests.

See also: API reference

Parameters
  • login_type (mautrix.types.LoginType) – The login type being used.

  • identifier (Optional[Union[mautrix.types.UserIdentifier, mautrix.types.UserID]]) – Identification information for the user.

  • device_name (Optional[str]) – A display name to assign to the newly-created device. Ignored if device_id correspnods to a known device.

  • device_id (Optional[str]) – ID of the client device. If this does not correspond to a known client device, a new device will be created. The server will auto-generate a device_id if this is not specified.

  • password (Optional[str]) – The user’s password. Required when type is m.login.password.

  • store_access_token (bool) – Whether or not mautrix-python should store the returned access token in this ClientAPI instance for future requests.

  • update_hs_url (bool) – Whether or not mautrix-python should use the returned homeserver URL in this ClientAPI instance for future requests.

  • **kwargs – Additional arguments for other login types.

  • kwargs (str) –

Returns

The login response.

Return type

mautrix.types.LoginResponse

async logout(clear_access_token=True)

Invalidates an existing access token, so that it can no longer be used for authorization. The device associated with the access token is also deleted. Device keys for the device are deleted alongside the device.

See also: API reference

Parameters

clear_access_token (bool) – Whether or not mautrix-python should forget the stored access token.

Return type

None

async logout_all(clear_access_token=True)

Invalidates all access tokens for a user, so that they can no longer be used for authorization. This includes the access token that made this request. All devices for the user are also deleted. Device keys for the device are deleted alongside the device.

This endpoint does not require UI (user-interactive) authorization because UI authorization is designed to protect against attacks where the someone gets hold of a single access token then takes over the account. This endpoint invalidates all access tokens for the user, including the token used in the request, and therefore the attacker is unable to take over the account in this way.

See also: API reference

Parameters

clear_access_token (bool) – Whether or not mautrix-python should forget the stored access token.

Return type

None

property mxid: mautrix.types.UserID
classmethod parse_user_id(mxid)

Parse the localpart and server name from a Matrix user ID.

Parameters

mxid (mautrix.types.UserID) – The Matrix user ID.

Returns

A tuple of (localpart, server_name).

Raises

ValueError – if the given user ID is invalid.

Return type

tuple[str, str]

async query_keys(device_keys, token='', timeout=10000)

Fetch devices and their identity keys for the given users.

See also: API reference

Parameters
  • device_keys (list[mautrix.types.UserID] | set[mautrix.types.UserID] | dict[mautrix.types.UserID, list[mautrix.types.DeviceID]]) – The keys to be downloaded. A map from user ID, to a list of device IDs, or to an empty list to indicate all devices for the corresponding user.

  • token (mautrix.types.SyncToken) – 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. This allows the server to ensure its response contains the keys advertised by the notification in that sync.

  • timeout (int) – The time (in milliseconds) to wait when downloading keys from remote servers.

Returns

Information on the queried devices and errors for homeservers that could not be reached.

Return type

mautrix.types.QueryKeysResponse

react(room_id, event_id, key, **kwargs)
Parameters
Return type

Awaitable[mautrix.types.EventID]

async redact(room_id, event_id, reason=None, extra_content=None, **kwargs)

Send an event to redact a previous event.

Redacting an event strips all information out of an event which isn’t critical to the integrity of the server-side representation of the room.

This cannot be undone.

Users may redact their own events, and any user with a power level greater than or equal to the redact power level of the room may redact events there.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room the event is in.

  • event_id (mautrix.types.EventID) – The ID of the event to redact.

  • reason (Optional[str]) – The reason for the event being redacted.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Extra content for the event.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method. Used by IntentAPI to pass the timestamp massaging field to AppServiceAPI.request().

Returns

The ID of the event that was sent to redact the other event.

Return type

mautrix.types.EventID

async remove_push_rule(scope, kind, rule_id)

Remove a push rule.

See also: API reference

Parameters
Return type

None

async remove_room_alias(alias_localpart, raise_404=False)

Remove a mapping of room alias to room ID.

Servers may choose to implement additional access control checks here, for instance that room aliases can only be deleted by their creator or server administrator.

See also: API reference

Parameters
  • alias_localpart (str) – The room alias to remove.

  • raise_404 (bool) – Whether 404 errors should be raised as exceptions instead of ignored.

Return type

None

async remove_room_tag(room_id, tag)

Remove a tag from a specific room.

See also: API reference

Parameters
Return type

None

async resolve_room_alias(room_alias)

Request the server to resolve a room alias to a room ID.

The server will use the federation API to resolve the alias if the domain part of the alias does not correspond to the server’s own domain.

See also: API reference

Parameters

room_alias (mautrix.types.RoomAlias) – The room alias.

Returns

The room ID and a list of servers that are aware of the room.

Return type

mautrix.types.RoomAliasInfo

async search_users(search_query, limit=10)

Performs a search for users on the homeserver. The homeserver may determine which subset of users are searched, however the homeserver MUST at a minimum consider the users the requesting user shares a room with and those who reside in public rooms (known to the homeserver). The search MUST consider local users to the homeserver, and SHOULD query remote users as part of the search.

The search is performed case-insensitively on user IDs and display names preferably using a collation determined based upon the Accept-Language header provided in the request, if present.

See also: API reference

Parameters
  • search_query (str) – The query to search for.

  • limit (int | None) – The maximum number of results to return.

Returns

The results of the search and whether or not the results were limited.

Return type

mautrix.types.UserSearchResults

send_emote(room_id, text=None, html=None, relates_to=None, **kwargs)

Send an emote to a room. Emotes are usually displayed by prepending a star and the user’s display name to the message, which means they’re usually written in the third person.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • text (Optional[str]) – The text to send. If set to None, the given HTML will be parsed to generate a plaintext representation.

  • html (Optional[str]) – The HTML to send.

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Raises

ValueError – if both text and html are None.

Return type

Awaitable[mautrix.types.EventID]

send_file(room_id, url, info=None, file_name=None, file_type=<MessageType.FILE: 'm.file'>, relates_to=None, **kwargs)

Send a file to a room.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • url (mautrix.types.ContentURI) – The Matrix content repository URI of the file. You can upload files using upload_media().

  • info (Optional[mautrix.types.BaseFileInfo]) – Additional metadata about the file, e.g. mimetype, image size, video duration, etc

  • file_name (Optional[str]) – The name for the file to send.

  • file_type (mautrix.types.MessageType) – The general file type to send. The file type can be further specified by setting the mimetype field of the info parameter. Defaults to MessageType.FILE (unspecified file type, e.g. document)

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Return type

Awaitable[mautrix.types.EventID]

send_image(room_id, url, info=None, file_name=None, relates_to=None, **kwargs)

Send an image to a room.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • url (mautrix.types.ContentURI) – The Matrix content repository URI of the image. You can upload files using upload_media().

  • info (Optional[mautrix.types.ImageInfo]) – Additional metadata about the image, e.g. mimetype and image size

  • file_name (Optional[str]) – The file name for the image to send.

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Return type

Awaitable[mautrix.types.EventID]

async send_member_event(room_id, user_id, membership, extra_content=None)

Send a membership event manually.

Parameters
Returns

The event ID of the new member event.

Return type

mautrix.types.EventID

send_message(room_id, content, **kwargs)

Send a message to a room.

Parameters
Returns

The ID of the event that was sent.

Return type

Awaitable[mautrix.types.EventID]

async send_message_event(room_id, event_type, content, txn_id=None, **kwargs)

Send a message event to a room. Message events allow access to historical events and pagination, making them suited for “once-off” activity in a room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • event_type (mautrix.types.EventType) – The type of message to send.

  • content (mautrix.types.EventContent) – The content to send.

  • txn_id (Optional[str]) – The transaction ID to use. If not provided, a random ID will be generated.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method. Used by IntentAPI to pass the timestamp massaging field to AppServiceAPI.request().

Returns

The ID of the event that was sent.

Return type

mautrix.types.EventID

send_notice(room_id, text=None, html=None, relates_to=None, **kwargs)

Send a notice text message to a room. Notices are like normal text messages, but usually sent by bots to tell other bots not to react to them. If you’re a bot, please send notices instead of normal text, unless there is a reason to do something else.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • text (Optional[str]) – The text to send. If set to None, the given HTML will be parsed to generate a plaintext representation.

  • html (Optional[str]) – The HTML to send.

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Raises

ValueError – if both text and html are None.

Return type

Awaitable[mautrix.types.EventID]

async send_receipt(room_id, event_id, receipt_type='m.read')

Update the marker for the given receipt type to the event ID specified.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room which to send the receipt to.

  • event_id (mautrix.types.EventID) – The last event ID to acknowledge.

  • receipt_type (str) – The type of receipt to send. Currently only m.read is supported.

Return type

None

async send_state_event(room_id, event_type, content, state_key='', ensure_joined=True, **kwargs)

Send a state event to a room. State events with the same room_id, event_type and state_key will be overridden.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to set the state in.

  • event_type (mautrix.types.EventType) – The type of state to send.

  • content (mautrix.types.StateEventContent) – The content to send.

  • state_key (str) – The key for the state to send. Defaults to empty string.

  • ensure_joined (bool) – Used by IntentAPI to determine if it should ensure the user is joined before sending the event.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method. Used by IntentAPI to pass the timestamp massaging field to AppServiceAPI.request().

Returns

The ID of the event that was sent.

Return type

mautrix.types.EventID

send_sticker(room_id, url, info=None, text='', relates_to=None, **kwargs)

Send a sticker to a room. Stickers are basically images, but they’re usually rendered slightly differently.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • url (mautrix.types.ContentURI) – The Matrix content repository URI of the sticker. You can upload files using upload_media().

  • info (Optional[mautrix.types.ImageInfo]) – Additional metadata about the sticker, e.g. mimetype and image size

  • text (str) – A textual description of the sticker.

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Return type

Awaitable[mautrix.types.EventID]

async send_text(room_id, text=None, html=None, msgtype=<MessageType.TEXT: 'm.text'>, relates_to=None, **kwargs)

Send a text message to a room.

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to send the message to.

  • text (Optional[str]) – The text to send. If set to None, the given HTML will be parsed to generate a plaintext representation.

  • html (Optional[str]) – The HTML to send.

  • msgtype (mautrix.types.MessageType) – The message type to send. Defaults to MessageType.TEXT (normal text message).

  • relates_to (Optional[mautrix.types.RelatesTo]) – Message relation metadata used for things like replies.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method.

Returns

The ID of the event that was sent.

Raises

ValueError – if both text and html are None.

Return type

mautrix.types.EventID

async send_to_device(event_type, messages)

Send to-device events to a set of client devices.

See also: API reference

Parameters
Return type

None

async send_to_one_device(event_type, user_id, device_id, message)

Send a to-device event to a single device.

Parameters
Return type

None

async set_account_data(type, data, room_id=None)

Store account data on the homeserver.

See also: API reference

Parameters
Return type

None

async set_avatar_url(avatar_url, check_current=True)

Set the avatar of the current user.

See also: API reference

Parameters
  • avatar_url (mautrix.types.ContentURI) – The mxc:// URI to the new avatar.

  • check_current (bool) – Whether or not to check if the avatar is already set.

Return type

None

async set_displayname(displayname, check_current=True)

Set the display name of the current user.

See also: API reference

Parameters
  • displayname (str) – The new display name for the user.

  • check_current (bool) – Whether or not to check if the displayname is already set.

Return type

None

async set_fully_read_marker(room_id, fully_read, read_receipt=None, extra_content=None)

Set the position of the read marker for the given room, and optionally send a new read receipt.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room which to set the read marker in.

  • fully_read (mautrix.types.EventID) – The last event up to which the user has either read all events or is not interested in reading the events.

  • read_receipt (Optional[mautrix.types.EventID]) – The new position for the user’s normal read receipt, i.e. the last event the user has seen.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional fields to include in the /read_markers request.

Return type

None

async set_presence(presence=PresenceState.ONLINE, status=None)

Set the current user’s presence state. When setting the status, the activity time is updated to reflect that activity; the client does not need to specify Presence.last_active_ago.

See also: API reference

Parameters
Return type

None

async set_push_rule(scope, kind, rule_id, actions, pattern=None, before=None, after=None, conditions=None)

Create or modify a push rule.

See also: API reference

Parameters
Return type

None

async set_room_directory_visibility(room_id, visibility)

Set the visibility of the room in the server’s public room directory.

Servers may choose to implement additional access control checks here, for instance that room visibility can only be changed by the room creator or a server administrator.

Parameters
Return type

None

async set_room_tag(room_id, tag, info=None)

Add or update a tag for a specific room.

See also: API reference

Parameters
Return type

None

async set_typing(room_id, timeout=0)

This tells the server that the user is typing for the next N milliseconds where N is the value specified in the timeout key. If the timeout is equal to or less than zero, it tells the server that the user has stopped typing.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room in which the user is typing.

  • timeout (int) – The length of time in milliseconds to mark this user as typing.

Return type

None

sync(since=None, timeout=30000, filter_id=None, full_state=False, set_presence=None)

Perform a sync request. See also: /sync API reference

This method doesn’t parse the response at all. You should use mautrix.client.Syncer to parse sync responses and dispatch the data into event handlers. mautrix.client.Client includes Syncer.

Parameters
  • since (str) – Optional. A token which specifies where to continue a sync from.

  • timeout (int) – Optional. The time in milliseconds to wait.

  • filter_id (int) – A filter ID.

  • full_state (bool) – Return the full state for every room the user has joined Defaults to false.

  • set_presence (str) – Should the client be marked as “online” or” offline”

Return type

Awaitable[mautrix.types.JSON]

async unban_user(room_id, user_id, reason='', extra_content=None)

Unban a user from the room. This allows them to be invited to the room, and join if they would otherwise be allowed to join according to its join rules. The caller must have the required power level in order to perform this operation.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room from which the user should be unbanned.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the user being banned.

  • reason (str) – The reason the user has been unbanned. This will be supplied as the reason on the target’s updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the unban (leave) event content. If a non-empty dict is passed, the unban will be created using the PUT /state/m.room.member/... endpoint instead of POST /unban.

Return type

None

async upload_keys(one_time_keys=None, device_keys=None)

Publishes end-to-end encryption keys for the device.

See also: API reference

Parameters
  • one_time_keys (Optional[dict[str, typing.Any]]) – One-time public keys for “pre-key” messages. The names of the properties should be in the format <algorithm>:<key_id>. The format of the key is determined by the key algorithm.

  • device_keys (Optional[dict[str, typing.Any]]) – Identity keys for the device. May be absent if no new identity keys are required.

Returns

For each key algorithm, the number of unclaimed one-time keys of that type currently held on the server for this device.

Return type

dict[mautrix.types.EncryptionKeyAlgorithm, int]

async upload_media(data, mime_type=None, filename=None, size=None, mxc=None, async_upload=False)

Upload a file to the content repository.

See also: API reference

Parameters
  • data (Union[bytes, bytearray, AsyncIterable[bytes]]) – The data to upload.

  • mime_type (Optional[str]) – The MIME type to send with the upload request.

  • filename (Optional[str]) – The filename to send with the upload request.

  • size (Optional[int]) – The file size to send with the upload request.

  • mxc (Optional[mautrix.types.ContentURI]) – An existing MXC URI which doesn’t have content yet to upload into.

  • async_upload (bool) – Should the media be uploaded in the background? If True, this will create a MXC URI using create_mxc(), start uploading in the background, and then immediately return the created URI. This is mutually exclusive with manually passing the mxc parameter.

Returns

The MXC URI to the uploaded file.

Raises
  • MatrixResponseError – If the response does not contain a content_uri field.

  • ValueError – if both async_upload and mxc are provided at the same time.

Return type

mautrix.types.ContentURI

async versions(no_cache=False)

Get client-server spec versions supported by the server.

Parameters

no_cache (bool) – If true, the versions will always be fetched from the server rather than using cached results when availab.e.

Returns

The supported Matrix spec versions and unstable features.

Return type

mautrix.types.VersionsResponse

async whoami()

Get information about the current user.

Returns

The user ID and device ID of the current user.

Return type

mautrix.types.WhoamiResponse

fill_member_event_callback: Callable[[RoomID, UserID, MemberStateEventContent], Awaitable[MemberStateEventContent | None]] | None
localpart: str
domain: str
device_id: DeviceID
api: HTTPAPI
log: TraceLogger
versions_cache: VersionsResponse | None