mautrix.client.api — mautrix-python 0.21.0 documentation (original) (raw)

mautrix-python

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.Clientor 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 existingmautrix.api.HTTPAPI instance, or provide the base_url and other arguments for creating it as kwargs.

Parameters:

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:

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:

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,_ 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:

ClaimKeysResponse

async create_device_msc4190(device_id, initial_display_name)

Create a Device for a user of the homeserver using appservice interface defined in MSC4190

Parameters:

Return type:

None

async create_filter(filter_params)

Upload a new filter definition to the homeserver.

See also: API reference

Parameters:

filter_params (Filter) – The filter data.

Returns:

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

Return type:

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:

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:

Returns:

The ID of the newly created room.

Raises:

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

Return type:

RoomID

async classmethod discover(domain, session=None)

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

Parameters:

Returns:

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

Raises:

WellKnownError – for other errors

Return type:

URL | None

async download_media(url, timeout_ms=None)

Download a file from the content repository.

See also: API reference

Parameters:

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:

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:

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 (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:

JSON

async get_avatar_url(user_id)

Get the avatar URL of a user.

See also: API reference

Parameters:

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

Returns:

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

Return type:

ContentURI | None

async get_displayname(user_id)

Get the display name of a user.

See also: API reference

Parameters:

user_id (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:

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:

EventContext

async get_filter(filter_id)

Download a filter.

See also: API reference

Parameters:

filter_id (FilterID) – The filter ID to download.

Returns:

The filter data.

Return type:

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 (RoomID) – The ID of the room to get the members of.

Returns:

A dictionary from user IDs to Member info objects.

Return type:

dict[UserID, Member]

async get_joined_rooms()

Get the list of rooms the user is in.

Return type:

list[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:

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:

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:

Returns:

A list of most recent member events for each user.

Return type:

list[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:

Return type:

PaginatedMessages

Returns:

async get_presence(user_id)

Get the presence info of a user.

See also: API reference

Parameters:

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

Returns:

The presence info of the given user.

Return type:

PresenceEventContent

async get_profile(user_id)

Get the combined profile information for a user.

See also: API reference

Parameters:

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

Returns:

The profile information of the given user.

Return type:

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:

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:

Returns:

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

Return type:

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 (RoomID) – The ID of the room.

Returns:

The visibility of the room in the directory.

Return type:

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:

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 (RoomID) – The room ID to get tags from.

Returns:

The m.tag account data event.

Return type:

RoomTagAccountDataEventContent

async get_state(room_id)

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

See also: API reference

Parameters:

room_id (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[StateEvent]

async get_state_event(room_id, event_type, state_key='', *, format='content')

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:

Returns:

The state event.

Return type:

StateEventContent | StateEvent

async get_url_preview(url, timestamp=None)

Get information about a URL for a client.

See also: API reference

Parameters:

Return type:

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:

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:

Returns:

The ID of the room the user joined.

Return type:

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:

Returns:

The ID of the room the user joined.

Return type:

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 optionalreason. Like with other membership changes, a user can directly adjust the target member’s state by calling EventMethods.send_state_event() withEventType.ROOM_MEMBER as the event type and the user_id as the state key.

See also: API reference

Parameters:

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:

Returns:

The ID of the room the user knocked on.

Return type:

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:

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:

Returns:

The login response.

Return type:

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_: UserID_

classmethod parse_user_id(mxid)

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

Parameters:

mxid (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:

Returns:

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

Return type:

QueryKeysResponse

react(room_id, event_id, key, **kwargs)

Parameters:

Return type:

Awaitable[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:

Returns:

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

Return type:

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:

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 (RoomAlias) – The room alias.

Returns:

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

Return type:

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:

Returns:

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

Return type:

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:

Returns:

The ID of the event that was sent.

Raises:

ValueError – if both text and html are None.

Return type:

Awaitable[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:

Returns:

The ID of the event that was sent.

Return type:

Awaitable[EventID]

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

Send an image to a room.

Parameters:

Returns:

The ID of the event that was sent.

Return type:

Awaitable[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:

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[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:

Returns:

The ID of the event that was sent.

Return type:

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:

Returns:

The ID of the event that was sent.

Raises:

ValueError – if both text and html are None.

Return type:

Awaitable[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:

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 andstate_key will be overridden.

See also: API reference

Parameters:

Returns:

The ID of the event that was sent.

Return type:

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:

Returns:

The ID of the event that was sent.

Return type:

Awaitable[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:

Returns:

The ID of the event that was sent.

Raises:

ValueError – if both text and html are None.

Return type:

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:

Return type:

None

async set_displayname(displayname, check_current=True)

Set the display name of the current user.

See also: API reference

Parameters:

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:

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 specifyPresence.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:

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:

Return type:

Awaitable[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:

Return type:

None

async upload_cross_signing_keys(keys, auth=None)

Parameters:

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:

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[EncryptionKeyAlgorithm, int]

async upload_many_signatures(signatures)

Parameters:

signatures (dict[_UserID,_ dict[_DeviceID,_ DeviceKeys | CrossSigningKeys] ])

Return type:

None

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:

Returns:

The MXC URI to the uploaded file.

Raises:

Return type:

ContentURI

async upload_one_signature(user_id, device_id, keys)

Parameters:

Return type:

None

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:

VersionsResponse

async whoami()

Get information about the current user.

Returns:

The user ID and device ID of the current user.

Return type:

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_