API

This document details the API of nio.

Logging

matrix-nio writes logs using python’s standard logging module. In order to see these logs, you will need to configure logging. In order to see all logs matrix-nio produces, you can build off of the following snippet:

import logging

logging.basicConfig(level=logging.DEBUG)

This snippet is very loud, and will produce a lot of output. If you want to see less output, you can set the logging level to INFO or WARNING. For example:

import logging

logging.basicConfig(level=logging.INFO)

In production, it is recommended to use WARNING or higher, as INFO may still be too noisy.

You can also attach your own logs to this system:

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger("my-app")
logger.info("Hello, world!")

For more information, seek the documentation for the logging module at https://docs.python.org/3/library/logging.html

Api

class nio.Api[source]

Matrix API class.

Static methods reflecting the Matrix REST API.

static content_repository_config(access_token: str) Tuple[str, str][source]

Get the content repository configuration, such as upload limits.

Returns the HTTP method and HTTP path for the request.

Parameters:

access_token (str) – The access token to be used with the request.

static delete_devices(access_token: str, devices: List[str], auth_dict: Dict[str, str] | None = None) Tuple[str, str, str][source]

Delete a device.

This API endpoint uses the User-Interactive Authentication API.

This tells the server to delete the given devices and invalidate their associated access tokens.

Should first be called with no additional authentication information.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • devices (List[str]) – A list of devices which will be deleted.

  • auth_dict (Dict) – Additional authentication information for the user-interactive authentication API.

static delete_pushrule(access_token: str, scope: str, kind: PushRuleKind, rule_id: str) Tuple[str, str][source]

Delete an existing user-created push rule.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • scope (str) – The scope of this rule, e.g. "global".

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

static delete_room_alias(access_token: str, alias: str) Tuple[str, str][source]

Delete a room alias

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • alias (str) – The room alias

static devices(access_token: str) Tuple[str, str][source]

Get the list of devices for the current user.

Returns the HTTP method and HTTP path for the request.

Parameters:

access_token (str) – The access token to be used with the request.

static direct_room_list(access_token: str, user_id: str) Tuple[str, str][source]

Lists all rooms flagged as direct the client is participating in.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used within the request

  • user_id (str) – The user id of the user to get the direct rooms for

static discovery_info() Tuple[str, str][source]

Get discovery information about a domain.

Returns the HTTP method and HTTP path for the request.

static download(server_name: str, media_id: str, filename: str | None = None, allow_remote: bool = True, file: PathLike | None = None) Tuple[str, str][source]

Get the content of a file from the content repository.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.

  • media_id (str) – The media ID from the mxc:// URI.

  • filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.

  • allow_remote (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.

  • file (os.PathLike) – The file to stream the downloaded content to.

static enable_pushrule(access_token: str, scope: str, kind: PushRuleKind, rule_id: str, enable: bool) Tuple[str, str, str][source]

Enable or disable an existing built-in or user-created push rule.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • scope (str) – The scope of this rule, e.g. "global".

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

  • enable (bool) – Whether to enable or disable the rule.

static encrypted_mxc_to_plumb(mxc, key: str, hash: str, iv: str, homeserver: str | None = None, mimetype: str | None = None) str | None[source]

Convert a matrix content URI to a encrypted mxc URI.

The return value of this function will have a URI schema of emxc://. The path of the URI will be converted just like the mxc_to_http() function does, but it will also contain query parameters that are necessary to decrypt the payload the URI is pointing to.

This function is useful to present a clickable URI that can be passed to a plumber program that will download and decrypt the content that the matrix content URI is pointing to.

The returned URI should never be converted to http and opened directly, as that would expose the decryption parameters to any middleman or ISP.

Parameters:
  • mxc (str) – The matrix content URI.

  • key (str) – The encryption key that can be used to decrypt the payload the URI is pointing to.

  • hash (str) – The hash of the payload.

  • iv (str) – The initial value needed to decrypt the payload.

  • mimetype (str) – The mimetype of the payload.

static get_openid_token(access_token: str, user_id: str) Tuple[str, str][source]

Gets an OpenID token object that the requester may supply to another service to verify their identity in matrix.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – The user who requested the OpenID token

static get_presence(access_token: str, user_id: str) Tuple[str, str][source]

Get the given user’s presence state.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – User id whose presence state to get.

static join(access_token: str, room_id: str) Tuple[str, str][source]

Join a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room identifier or alias to join.

static joined_members(access_token: str, room_id: str) Tuple[str, str][source]

Get the list of joined members for a room.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – Room id of the room where the user is typing.

static joined_rooms(access_token: str) Tuple[str, str][source]

Get the list of joined rooms for the logged in account.

Returns the HTTP method and HTTP path for the request.

Parameters:

access_token (str) – The access token to be used with the request.

static keys_claim(access_token: str, user_set: Dict[str, Iterable[str]]) Tuple[str, str, str][source]

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

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_set (Dict[str, List[str]]) – The users and devices for which to claim one-time keys to be claimed. A map from user ID, to a list of device IDs.

static keys_query(access_token: str, user_set: Iterable[str], token: str | None = None) Tuple[str, str, str][source]

Query the current devices and identity keys for the given users.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_set (Set[str]) – The users for which the keys should be downloaded.

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

static keys_upload(access_token: str, key_dict: Dict[str, Any]) Tuple[str, str, str][source]

Publish end-to-end encryption keys.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • key_dict (Dict) – The dictionary containing device and one-time keys that will be published to the server.

static login(user: str, password: str | None = None, device_name: str | None = '', device_id: str | None = '', token: str | None = None) Tuple[str, str, str][source]

Authenticate the user.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • user (str) – The fully qualified user ID or just local part of the user ID, to log in. If the user ID contains an ‘@’, but no ‘:’, the user ID will be considered to be an email address.

  • password (str) – The user’s password.

  • device_name (str) – A display name to assign to a newly-created device. Ignored if device_id corresponds to a known device

  • device_id (str) – ID of the client device. If this does not correspond to a known client device, a new device will be created.

  • token (str) – Token for token-based login.

static login_info() Tuple[str, str][source]

Get the Homeserver’s supported login types

Returns the HTTP method and HTTP path for the request.

static login_raw(auth_dict: Dict[str, Any]) Tuple[str, str, str][source]

Login to the homeserver using a raw dictionary.

Returns the HTTP method, HTTP path and data for the request.

Parameters:

auth_dict (Dict[str, Any) –

The authentication dictionary containing the elements for the logon. See the example below and here

for detailed documentation

Example

>>> auth_dict = {
>>>     "type": "m.login.password",
>>>     "identifier": {
>>>         "type": "m.id.thirdparty",
>>>         "medium": "email",
>>>         "address": "testemail@mail.org"
>>>     },
>>>     "password": "PASSWORDABCD",
>>>     "initial_device_display_name": "Test user"
>>> }
static logout(access_token: str, all_devices: bool = False)[source]

Logout the session.

Returns nothing.

Parameters:
  • access_token (str) – the access token to be used with the request.

  • all_devices (bool) – Logout all sessions from all devices if set to True.

static mimetype_to_msgtype(mimetype: str) str[source]

Turn a mimetype into a matrix message type.

static mxc_to_http(mxc: str, homeserver: str | None = None) str | None[source]

Convert a matrix content URI to a HTTP URI.

static profile_get(user_id: str, access_token: str | None = None) Tuple[str, str][source]

Get the combined profile information for a user.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • user_id (str) – User id to get the profile for.

  • access_token (str) – The access token to be used with the request. If omitted, an unauthenticated request is performed.

static profile_get_avatar(user_id: str, access_token: str | None = None) Tuple[str, str][source]

Get avatar URL.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • user_id (str) – User id to get avatar for.

  • access_token (str) – The access token to be used with the request. If omitted, an unauthenticated request is performed.

static profile_get_displayname(user_id: str, access_token: str | None = None) Tuple[str, str][source]

Get display name.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • user_id (str) – User id to get display name for.

  • access_token (str) – The access token to be used with the request. If omitted, an unauthenticated request is performed.

static profile_set_avatar(access_token: str, user_id: str, avatar_url: str) Tuple[str, str, str][source]

Set avatar url.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – User id to set display name for.

  • avatar_url (str) – matrix content URI of the avatar to set.

static profile_set_displayname(access_token: str, user_id: str, display_name: str) Tuple[str, str, str][source]

Set display name.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – User id to set display name for.

  • display_name (str) – Display name for user to set.

static put_room_alias(access_token: str, alias: str, room_id: str) Tuple[str, str, str][source]

Add an room alias

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • alias (str) – The room alias

  • room_id (str) – The room to point to

static register(user: str, password: str | None = None, device_name: str | None = '', device_id: str | None = '', auth_dict: dict[str, Any] | None = None)[source]

Register a new user.

Parameters:
  • user (str) – The fully qualified user ID or just local part of the user ID, to log in.

  • password (str) – The user’s password.

  • device_name (str) – A display name to assign to a newly-created device. Ignored if device_id corresponds to a known device

  • device_id (str) – ID of the client device. If this does not correspond to a known client device, a new device will be created.

  • auth_dict (Dict[str, Any, optional) –

    The authentication dictionary containing the elements for a particular registration flow. If not provided, then m.login.dummy is used. See the example below and here https://spec.matrix.org/latest/client-server-api/#account-registration-and-management for detailed documentation

    Example

    >>> auth_dict = {
    >>>     "type": "m.login.registration_token",
    >>>     "registration_token": "REGISTRATIONTOKEN",
    >>>     "session": "session-id-from-homeserver"
    >>> }
    

static room_ban(access_token: str, room_id: str, user_id: str, reason: str | None = None) Tuple[str, str, str][source]

Ban a user from a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that the user will be banned from.

  • user_id (str) – The user_id of the user that should be banned.

  • reason (str, optional) – A reason for which the user is banned.

static room_context(access_token: str, room_id: str, event_id: str, limit: int | None = None) Tuple[str, str][source]

Fetch a number of events that happened before and after an event. This allows clients to get the context surrounding an event.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room_id of the room that contains the event and its context.

  • event_id (str) – The event_id of the event that we wish to get the context for.

  • limit (int, optional) – The maximum number of events to request.

static room_create(access_token: str, visibility: RoomVisibility = RoomVisibility.private, alias: str | None = None, name: str | None = None, topic: str | None = None, room_version: str | None = None, room_type: str | None = None, federate: bool = True, is_direct: bool = False, preset: RoomPreset | None = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Dict[str, Any] | None = None, predecessor: Dict[str, Any] | None = None, space: bool = False) Tuple[str, str, str][source]

Create a new room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to RoomVisibility.private.

  • alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.

  • name (str, optional) – A name to set for the room.

  • topic (str, optional) – A topic to set for the room.

  • room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400 M_UNSUPPORTED_ROOM_VERSION error will be returned.

  • room_type (str, optional) –

    The room type to set. If not specified, the homeserver will use its default setting. In spec v1.2 the following room types are specified:

    • m.space

    Unspecified room types are permitted through the use of Namespaced Identifiers.

  • federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to True. Cannot be changed later.

  • is_direct (bool) – If this should be considered a direct messaging room. If True, the server will set the is_direct flag on m.room.member events sent to the users in invite. Defaults to False.

  • preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the visibility: RoomVisibility.public equates to RoomPreset.public_chat, and RoomVisibility.private equates to a RoomPreset.private_chat.

  • invite (list) – A list of user id to invite to the room.

  • initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediately by having a m.room.encryption event dict.

  • power_level_override (dict) – A m.room.power_levels content dict to override the default. The dict will be applied on top of the generated m.room.power_levels event before it is sent to the room.

  • space (bool) – Create as a Space (defaults to False).

static room_delete_alias(access_token: str, room_alias: str) Tuple[str, str][source]

Delete a room alias.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_alias (str) – The alias to delete

static room_forget(access_token: str, room_id: str) Tuple[str, str][source]

Forget a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that will be forgotten.

static room_get_event(access_token: str, room_id: str, event_id: str) Tuple[str, str][source]

Get a single event based on roomId/eventId.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the event is in.

  • event_id (str) – The event id to get.

static room_get_event_relations(access_token: str, room_id: str, event_id: str, rel_type: RelationshipType | None = None, event_type: str | None = None, direction: MessageDirection = MessageDirection.back, paginate_from: str | None = None, paginate_to: str | None = None, limit: int | None = None) Tuple[str, str][source]

Get all child events of a given parent event.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the event is in.

  • event_id (str) – The event id to get.

  • rel_type (RelationshipType, optional) – The relationship type to search for. Required if event_type is provided.

  • event_type – (str, optional): The event type of child events to search for. Ignored if rel_type is not provided.

  • direction (MessageDirection, optional) – The direction to return events from. Defaults to MessageDirection.back.

  • paginate_from (str, optional) – A pagination token from a previous result. When not provided, the server starts paginating from the most recent event.

  • paginate_to (str, optional) – The pagination token to stop returning results at. If not supplied, results continue until ‘limit’, or until there no more events.

  • limit (int, optional) – Limit for the maximum thread roots to include per paginated response. Homeservers will apply a default value, and override this with a maximum value.

static room_get_state(access_token: str, room_id: str) Tuple[str, str][source]

Fetch the current state for a room.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the state is fetched from.

static room_get_state_event(access_token, room_id: str, event_type: str, state_key: str = '') Tuple[str, str][source]

Fetch a state event.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the state is fetched from.

  • event_type (str) – The type of the event that will be fetched.

  • state_key – The key of the state to look up. Defaults to an empty string.

static room_get_threads(access_token: str, room_id: str, include: ThreadInclusion = ThreadInclusion.all, paginate_from: str | None = None, paginate_to: str | None = None, limit: int | None = None) Tuple[str, str][source]

Paginate through the list of the thread roots in a given room.

Optionally, filter for threads in which the requesting user has participated.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the event is in.

  • include (ThreadInclusion, optional) – Flag to filter whether to include just threads that the user participated in or all of them.

  • paginate_from (str, optional) – A pagination token from a previous result. When not provided, the server starts paginating from the most recent event.

  • paginate_to (str, optional) – The pagination token to stop returning results at. If not supplied, results continue until ‘limit’, or until there no more events.

  • limit (int, optional) – Limit for the maximum thread roots to include per paginated response. Servers will apply a default value, and override this with a maximum value.

static room_get_visibility(room_id: str) Tuple[str, str][source]

Get visibility of a room in the directory.

Returns the HTTP method and HTTP path for the request.

Parameters:

room_id (str) – The room ID to query.

static room_invite(access_token: str, room_id: str, user_id: str) Tuple[str, str, str][source]

Invite a user to a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that the user will be invited to.

  • user_id (str) – The user id of the user that should be invited.

static room_kick(access_token: str, room_id: str, user_id: str, reason: str | None = None) Tuple[str, str, str][source]

Kick a user from a room, or withdraw their invitation.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that the user will be kicked from.

  • user_id (str) – The user_id of the user that should be kicked.

  • reason (str, optional) – A reason for which the user is kicked.

static room_knock(access_token: str, room_id: str, reason: str | None = None) Tuple[str, str, str][source]

Knocks on a room for the user.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that the user will be knocking on.

  • reason (str, optional) – The reason the user is knocking.

static room_leave(access_token: str, room_id: str) Tuple[str, str][source]

Leave a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that will be left.

static room_messages(access_token: str, room_id: str, start: str | None = None, end: str | None = None, direction: MessageDirection = MessageDirection.back, limit: int = 10, message_filter: Dict[Any, Any] | None = None) Tuple[str, str][source]

Get room messages.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – room id of the room for which to download the messages

  • start (str) – The token to start returning events from.

  • end (str) – The token to stop returning events at.

  • direction (MessageDirection) – The direction to return events from.

  • limit (int) – The maximum number of events to return.

  • message_filter (Optional[Dict[Any, Any]]) – A filter dict that should be used for this room messages request.

static room_put_alias(access_token: str, room_alias: str, room_id: str) Tuple[str, str, str][source]

Add a room alias.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_alias (str) – The alias to add

  • room_id (str) – The room ID to map to

static room_put_state(access_token: str, room_id: str, event_type: str, body: Dict[Any, Any], state_key: str = '') Tuple[str, str, str][source]

Send a state event.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the event will be sent to.

  • event_type (str) – The type of the event that will be sent.

  • body (Dict) – The body of the event. The fields in this object will vary depending on the type of event.

  • state_key – The key of the state to look up. Defaults to an empty string.

static room_read_markers(access_token: str, room_id: str, fully_read_event: str, read_event: str | None = None, private_read_event: str | None = None) Tuple[str, str, str][source]

Update fully read marker and optionally read marker for a room.

This sets the position of the read marker for a given room, and optionally the location of the read receipt and private read receipt.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – Room id of the room where the read markers should be updated

  • fully_read_event (str) – The event ID the read marker should be located at.

  • read_event (Optional[str]) – The event ID to set the read receipt location at.

  • private_read_event (Optional[str]) – The event ID to set the private read receipt location at.

static room_redact(access_token: str, room_id: str, event_id: str, tx_id: str | UUID, reason: str | None = None) Tuple[str, str, str][source]

Strip information out of an event.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that contains the event that will be redacted.

  • event_id (str) – The ID of the event that will be redacted.

  • tx_id (str/UUID, optional) – A transaction ID for this event.

  • reason (str, optional) – A description explaining why the event was redacted.

static room_resolve_alias(room_alias: str) Tuple[str, str][source]

Resolve a room alias to a room ID.

Returns the HTTP method and HTTP path for the request.

Parameters:

room_alias (str) – The alias to resolve

static room_send(access_token: str, room_id: str, event_type: str, body: Dict[Any, Any], tx_id: str | UUID) Tuple[str, str, str][source]

Send a message event to a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room where the event will be sent to.

  • event_type (str) – The type of the message that will be sent.

  • body (Dict) – The body of the event. The fields in this object will vary depending on the type of event.

  • tx_id (str) – The transaction ID for this event.

static room_typing(access_token: str, room_id: str, user_id: str, typing_state: bool = True, timeout: int = 30000) Tuple[str, str, str][source]

Send a typing notice to the server.

This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – Room id of the room where the user is typing.

  • user_id (str) – The user who has started to type.

  • typing_state (bool) – A flag representing whether the user started or stopped typing

  • timeout (int) – For how long should the new typing notice be valid for in milliseconds.

static room_unban(access_token: str, room_id: str, user_id: str) Tuple[str, str, str][source]

Unban a user from a room.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – The room id of the room that the user will be unbanned from.

  • user_id (str) – The user_id of the user that should be unbanned.

static set_presence(access_token: str, user_id: str, presence: str, status_msg: str | None = None)[source]

This API sets the given user’s presence state.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – User id whose presence state to get.

  • presence (str) – The new presence state.

  • status_msg (str, optional) – The status message to attach to this state.

static set_pushrule(access_token: str, scope: str, kind: PushRuleKind, rule_id: str, before: str | None = None, after: str | None = None, actions: Sequence[PushAction] = (), conditions: Sequence[PushCondition] | None = None, pattern: str | None = None) Tuple[str, str, str][source]

Create or modify an existing user-created push rule.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • scope (str) – The scope of this rule, e.g. "global". Homeservers currently only process global rules for event matching, while device rules are a planned feature. It is up to clients to interpret any other scope name.

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind. For rules of room kind, this is the room ID to match for. For rules of sender kind, this is the user ID to match.

  • before (Optional[str]) – Position this rule before the one matching the given rule ID. The rule ID cannot belong to a predefined server rule. before and after cannot be both specified.

  • after (Optional[str]) – Position this rule after the one matching the given rule ID. The rule ID cannot belong to a predefined server rule. before and after cannot be both specified.

  • actions (Sequence[PushAction]) – Actions to perform when the conditions for this rule are met. The given actions replace the existing ones.

  • conditions (Sequence[PushCondition]) – Event conditions that must hold true for the rule to apply to that event. A rule with no conditions always hold true. Only applicable to underride and override rules.

  • pattern (Optional[str]) – Glob-style pattern to match against for the event’s content. Only applicable to content rules.

static set_pushrule_actions(access_token: str, scope: str, kind: PushRuleKind, rule_id: str, actions: Sequence[PushAction]) Tuple[str, str, str][source]

Set the actions for an existing built-in or user-created push rule.

Unlike set_pushrule, this method can edit built-in server rules.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • scope (str) – The scope of this rule, e.g. "global".

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

  • actions (Sequence[PushAction]) – Actions to perform when the conditions for this rule are met. The given actions replace the existing ones.

static space_get_hierarchy(access_token: str, space_id: str, from_page: str | None = None, limit: int | None = None, max_depth: int | None = None, suggested_only: bool = False) Tuple[str, str][source]

Get rooms/spaces that are a part of the provided space.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • space_id (str) – The ID of the space to get the hierarchy for.

  • from_page (str, optional) – Pagination token from a previous request to this endpoint.

  • limit (int, optional) – The maximum number of rooms to return.

  • max_depth (int, optional) – The maximum depth of the returned tree.

  • suggested_only (bool, optional) – Whether to only return rooms that are considered suggested. Defaults to False.

static sync(access_token: str, since: str | None = None, timeout: int | None = None, filter: None | str | Dict[Any, Any] = None, full_state: bool | None = None, set_presence: str | None = None) Tuple[str, str][source]

Synchronise the client’s state with the latest state on the server.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • since (str) – The room id of the room where the event will be sent to.

  • timeout (int) – The maximum time to wait, in milliseconds, before returning this request.

  • filter (Union[None, str, Dict[Any, Any]) – A filter ID or dict that should be used for this sync request.

  • full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter.

  • set_presence (str, optional) – Controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to “offline” then the client is not marked as being online when it uses this API. When set to “unavailable”, the client is marked as being idle. One of: [“offline”, “online”, “unavailable”]

static thumbnail(server_name: str, media_id: str, width: int, height: int, method: ResizingMethod = ResizingMethod.scale, allow_remote: bool = True) Tuple[str, str][source]

Get the thumbnail of a file from the content repository.

Returns the HTTP method and HTTP path for the request.

Note: The actual thumbnail may be larger than the size specified.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.

  • media_id (str) – The media ID from the mxc:// URI.

  • width (int) – The desired width of the thumbnail.

  • height (int) – The desired height of the thumbnail.

  • method (ResizingMethod) – The desired resizing method.

  • allow_remote (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.

static to_canonical_json(content_dict: Dict[Any, Any]) str[source]

Turn a dictionary into a canonical json string.

static to_device(access_token: str, event_type: str, content: Dict[Any, Any], tx_id: str | UUID) Tuple[str, str, str][source]

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

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • event_type (str) – The type of the event which will be sent.

  • content (Dict) – The messages to send. A map from user ID, to a map from device ID to message body. The device ID may also be *, meaning all known devices for the user.

  • tx_id (str) – The transaction ID for this event.

static to_json(content_dict: Dict[Any, Any]) str[source]

Turn a dictionary into a json string.

static update_device(access_token: str, device_id: str, content: Dict[str, str]) Tuple[str, str, str][source]

Update the metadata of the given device.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • device_id (str) – The device for which the metadata will be updated.

  • content (Dict) – A dictionary of metadata values that will be updated for the device.

static update_receipt_marker(access_token: str, room_id: str, event_id: str, receipt_type: ReceiptType = ReceiptType.read, thread_id: str = 'main') Tuple[str, str, str][source]

Update the marker of given receipt_type to specified event_id.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • room_id (str) – Room id of the room where the marker should be updated

  • event_id (str) – The event ID the read marker should be located at

  • receipt_type (ReceiptType) – The type of receipt to send. Currently, only m.read is supported by the Matrix specification.

  • thread_id (str) – The thread root’s event ID. Defaults to “main” to indicate the main timeline, and thus not in a thread.

static upload(access_token: str, filename: str | None = None) Tuple[str, str][source]

Upload a file’s content to the content repository.

Returns the HTTP method, HTTP path and empty data for the request. The real data should be read from the file that should be uploaded.

Note: This requests also requires the Content-Type http header to be set.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • filename (str) – The name of the file being uploaded

static upload_filter(access_token: str, user_id: str, event_fields: List[str] | None = None, event_format: EventFormat = EventFormat.client, presence: Dict[str, Any] | None = None, account_data: Dict[str, Any] | None = None, room: Dict[str, Any] | None = None) Tuple[str, str, str][source]

Upload a new filter definition to the homeserver.

Returns the HTTP method, HTTP path and data for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.

  • user_id (str) – ID of the user uploading the filter.

  • event_fields (Optional[List[str]]) – List of event fields to include. If this list is absent then all fields are included. The entries may include ‘.’ characters to indicate sub-fields. A literal ‘.’ character in a field name may be escaped using a ‘’.

  • event_format (EventFormat) – The format to use for events.

  • presence (Dict[str, Any]) – The presence updates to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

  • account_data (Dict[str, Any]) – The user account data that isn’t associated with rooms to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

  • room (Dict[str, Any]) – Filters to be applied to room data. The dict corresponds to the RoomFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

static whoami(access_token: str) Tuple[str, str][source]

Get information about the owner of a given access token.

Returns the HTTP method, HTTP path and data for the request.

Parameters:

access_token (str) – The access token to be used with the request.

nio Clients

class nio.ClientConfig(store: ~typing.Type[~nio.store.database.MatrixStore] | None = <class 'nio.store.database.DefaultStore'>, encryption_enabled: bool = True, store_name: str = '', pickle_key: str = 'DEFAULT_KEY', store_sync_tokens: bool = False, custom_headers: ~typing.Dict[str, str] | None = None)[source]

nio client configuration.

store

The store that should be used for state storage.

Type:

MatrixStore, optional

store_name

Filename that should be used for the store.

Type:

str, optional

encryption_enabled

Should end to end encryption be used.

Type:

bool, optional

pickle_key

A passphrase that will be used to encrypt end to end encryption keys.

Type:

str, optional

store_sync_tokens

Should the client store and restore sync tokens.

Type:

bool, optional

custom_headers

A dictionary of custom http headers.

Type:

Dict[str, str]

Raises an ImportWarning if encryption_enabled is true but the dependencies for encryption aren’t installed.

store

alias of DefaultStore

Client

class nio.Client(user: str, device_id: str | None = None, store_path: str | None = '', config: ClientConfig | None = None)[source]

Matrix no-IO client.

access_token

Token authorizing the user with the server. Is set after logging in.

Type:

str

user_id

The full mxid of the current user. This is set after logging in.

Type:

str

next_batch

The current sync token.

Type:

str

rooms

A dictionary containing a mapping of room ids to MatrixRoom objects. All the rooms a user is joined to will be here after a sync.

Type:

Dict[str, MatrixRoom)

invited_rooms

A dictionary containing a mapping of room ids to MatrixInvitedRoom objects. All the rooms a user is invited to will be here after a sync.

Type:

Dict[str, MatrixInvitedRoom)

Parameters:
  • user (str) – User that will be used to log in.

  • device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.

  • store_dir (str, optional) – The directory that should be used for state storage.

  • config (ClientConfig, optional) – Configuration for the client.

add_ephemeral_callback(callback: Callable[[MatrixRoom, EphemeralEvent], None], filter: Type[EphemeralEvent] | Tuple[Type[EphemeralEvent], ...]) None[source]

Add a callback that will be executed on ephemeral room events.

Parameters:
  • callback (Callable[MatrixRoom, EphemeralEvent]) – A function that will be called if the event type in the filter argument is found in the ephemeral room event list.

  • filter

  • (Union[Type[EphemeralEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • Tuple[Type[EphemeralEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • ...]]) – The event type or a tuple containing multiple types for which the function will be called.

add_event_callback(callback: Callable[[MatrixRoom, Event], Awaitable[None] | None], filter: Type[Event] | Tuple[Type[Event], None]) None[source]

Add a callback that will be executed on room events.

The callback can be used on joined rooms as well as on invited rooms. The room parameter for the callback will have a different type depending on if the room is joined or invited.

Parameters:
  • callback (Callable[[MatrixRoom, Event], Optional[Awaitable[None]]]) – A function that will be called if the event type in the filter argument is found in a room timeline.

  • filter (Union[Type[Event], Tuple[Type[Event], ...]]) – The event type or a tuple containing multiple types for which the function will be called.

add_global_account_data_callback(callback: Callable[[AccountDataEvent], None], filter: Type[AccountDataEvent] | Tuple[Type[AccountDataEvent], ...]) None[source]

Add a callback that will be executed on global account data events.

Parameters:
  • callback (Callable[[AccountDataEvent], None]) – A function that will be called if the event type in the filter argument is found in the account data event list.

  • filter

  • (Union[Type[AccountDataEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • Tuple[Type[AccountDataEvent – The event type or a tuple containing multiple types for which the function will be called.

  • ...]]) – The event type or a tuple containing multiple types for which the function will be called.

add_presence_callback(callback: Callable[[PresenceEvent], None], filter: Type | Tuple[Type])[source]

Add a callback that will be executed on presence events.

Parameters:
  • callback (Callable[[PresenceEvent], None]) – A function that will be called if the event type in the filter argument is found in the presence part of the sync response.

  • filter (Union[Type, Tuple[Type]]) – The event type or a tuple containing multiple types for which the function will be called.

add_room_account_data_callback(callback: Callable[[MatrixRoom, AccountDataEvent], None], filter: Type[AccountDataEvent] | Tuple[Type[AccountDataEvent], ...]) None[source]

Add a callback that will be executed on room account data events.

Parameters:
  • callback (Callable[[MatrixRoom, AccountDataEvent], None]) – A function that will be called if the event type in the filter argument is found in the room account data event list.

  • filter

  • (Union[Type[AccountDataEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • Tuple[Type[AccountDataEvent – The event type or a tuple containing multiple types for which the function will be called.

  • ...]]) – The event type or a tuple containing multiple types for which the function will be called.

add_to_device_callback(callback: Callable[[ToDeviceEvent], None], filter: Type[ToDeviceEvent] | Tuple[Type[ToDeviceEvent], ...]) None[source]

Add a callback that will be executed on to-device events.

Parameters:
  • callback (Callable[[ToDeviceEvent], None]) – A function that will be called if the event type in the filter argument is found in the to-device part of the sync response.

  • filter

  • (Union[Type[ToDeviceEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • Tuple[Type[ToDeviceEvent] – The event type or a tuple containing multiple types for which the function will be called.

  • ...]]) – The event type or a tuple containing multiple types for which the function will be called.

blacklist_device(device: OlmDevice) bool[source]

Mark a device as blacklisted.

Devices on the blacklist will not receive room encryption keys and therefore won’t be able to decrypt messages coming from this client.

Parameters:

device (OlmDevice) – The device which should be added to the blacklist.

Returns true if the device was added, false if it was on the blacklist already.

cancel_key_share(event: RoomKeyRequest) bool[source]

Cancel a previously interrupted key share event.

This method is the counterpart to the continue_key_share() method. If a user choses not to verify a device and does not want to share room keys with such a device it should cancel the request with this method.

>>> client.cancel_key_share(room_key_request)
Parameters:

event (RoomKeyRequest) – The event which we would like to cancel.

Returns:

True if the request was cancelled, False otherwise.

Return type:

bool

confirm_key_verification(transaction_id: str) ToDeviceMessage[source]

Confirm that the short auth string of a key verification matches.

Parameters:

transaction_id (str) – The transaction id of the interactive key verification.

Returns a ToDeviceMessage that should be sent to the homeserver.

If the other user already confirmed the short auth string on their side this function will also verify the device that is partaking in the verification process.

continue_key_share(event: RoomKeyRequest) bool[source]

Continue a previously interrupted key share event.

To handle room key requests properly client users need to add a callback for RoomKeyRequest:

>>> client.add_to_device_callback(callback, RoomKeyRequest)

This callback will be run only if a room key request needs user interaction, that is if a room key request is coming from an untrusted device.

After a user has verified the requesting device the key sharing can be continued using this method:

>>> client.continue_key_share(room_key_request)
Parameters:

event (RoomKeyRequest) – The event which we would like to continue.

If the key share event is continued successfully a to-device message will be queued up in the client.outgoing_to_device_messages list waiting to be sent out

Returns:

True if the request was continued, False otherwise.

Return type:

bool

create_key_verification(device: OlmDevice) ToDeviceMessage[source]

Start a new key verification process with the given device.

Parameters:

device (OlmDevice) – The device which we would like to verify

Returns a ToDeviceMessage that should be sent to to the homeserver.

decrypt_event(event: MegolmEvent) Event | BadEvent | UnknownBadEvent[source]

Try to decrypt an undecrypted megolm event.

Parameters:

event (MegolmEvent) – Event that should be decrypted.

Returns the decrypted event, raises EncryptionError if there was an error while decrypting.

property device_store: DeviceStore

Store containing known devices.

Returns a DeviceStore holding all known olm devices.

encrypt(room_id: str, message_type: str, content: Dict[Any, Any]) Tuple[str, Dict[str, str]][source]

Encrypt a message to be sent to the provided room.

Parameters:
  • room_id (str) – The room id of the room where the message will be sent.

  • message_type (str) – The type of the message.

  • content (str) – The dictionary containing the content of the message.

Raises GroupEncryptionError if the group session for the provided room isn’t shared yet.

Raises MembersSyncError if the room is encrypted but the room members aren’t fully loaded due to member lazy loading.

Returns a tuple containing the new message type and the new encrypted content.

export_keys(outfile: str, passphrase: str, count: int = 10000)[source]

Export all the Megolm decryption keys of this device.

The keys will be encrypted using the passphrase.

Note that this does not save other information such as the private identity keys of the device.

Parameters:
  • outfile (str) – The file to write the keys to.

  • passphrase (str) – The encryption passphrase.

  • count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.

get_active_key_requests(user_id: str, device_id: str) List[RoomKeyRequest][source]

Get key requests from a device that are waiting for verification.

Parameters:
  • user_id (str) – The id of the user for which we would like to find the active key requests.

  • device_id (str) – The id of the device for which we would like to find the active key requests.

Example

>>> # A to-device callback that verifies devices that
>>> # request room keys and continues the room key sharing process.
>>> # Note that a single user/device can have multiple key requests
>>> # queued up.
>>>   def key_share_cb(event):
...       user_id = event.sender
...       device_id = event.requesting_device_id
...       device = client.device_store[user_id][device_id]
...       client.verify_device(device)
...       for request in client.get_active_key_requests(
...           user_id, device_id):
...           client.continue_key_share(request)
>>>   client.add_to_device_callback(key_share_cb)
Returns:

A list of actively waiting key requests from the given user.

Return type:

list

get_active_sas(user_id: str, device_id: str) Sas | None[source]

Find a non-canceled SAS verification object for the provided user.

Parameters:
  • user_id (str) – The user for which we should find a SAS verification object.

  • device_id (str) – The device_id for which we should find the SAS verification object.

Returns the object if it’s found, otherwise None.

get_missing_sessions(room_id: str) Dict[str, List[str]][source]

Get users and devices for which we don’t have active Olm sessions.

Parameters:

room_id (str) – The room id of the room for which we should get the users with missing Olm sessions.

Raises LocalProtocolError if the room with the provided room id is

not found or the room is not encrypted.

get_users_for_key_claiming() Dict[str, List[str]][source]

Get the content for a key claim request that needs to be made.

Returns a dictionary containing users as the keys and a list of devices for which we will claim one-time keys.

Raises a LocalProtocolError if no key claim request needs to be made.

ignore_device(device: OlmDevice) bool[source]

Mark a device as ignored.

Ignored devices will still receive room encryption keys, despire not being verified.

Parameters:

device (OlmDevice) – the device to ignore

Returns true if device is ignored, or false if it is already on the list of ignored devices.

import_keys(infile: str, passphrase: str)[source]

Import Megolm decryption keys.

The keys will be added to the current instance as well as written to database.

Parameters:
  • infile (str) – The file containing the keys.

  • passphrase (str) – The decryption passphrase.

Raises EncryptionError if the file is invalid or couldn’t be

decrypted.

Raises the usual file errors if the file couldn’t be opened.

invalidate_outbound_session(room_id: str)[source]

Explicitly remove encryption keys for a room.

Parameters:

room_id (str) – Room id for the room the encryption keys should be removed.

property key_verifications: Dict[str, Sas]

Key verifications that the client is participating in.

load_store()[source]

Load the session store and olm account.

If the SqliteMemoryStore is set as the store a store path isn’t required, if no store path is provided and a store class that requires a path is used this method will be a no op.

This method does nothing if the store is already loaded.

Raises LocalProtocolError if a store class, user_id and device_id are

not set.

property logged_in: bool

Check if we are logged in.

Returns True if the client is logged in to the server, False otherwise.

property olm_account_shared: bool

Check if the clients Olm account is shared with the server.

Returns True if the Olm account is shared, False otherwise.

property outgoing_key_requests: Dict[str, OutgoingKeyRequest]

Our active key requests that we made.

property outgoing_to_device_messages: List[ToDeviceMessage]

To-device messages that we need to send out.

receive_response(response: Response) None | Coroutine[Any, Any, None][source]

Receive a Matrix Response and change the client state accordingly.

Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible.

Parameters:

response (Response) – the response that we wish the client to handle

restore_login(user_id: str, device_id: str, access_token: str)[source]

Restore a previous login to the homeserver.

Parameters:
  • user_id (str) – The full mxid of the current user.

  • device_id (str) – An unique identifier that distinguishes this client instance.

  • access_token (str) – Token authorizing the user with the server.

room_contains_unverified(room_id: str) bool[source]

Check if a room contains unverified devices.

Parameters:

room_id (str) – Room id of the room that should be checked.

Returns True if the room contains unverified devices, false otherwise. Returns False if no Olm session is loaded or if the room isn’t encrypted.

room_devices(room_id: str) Dict[str, Dict[str, OlmDevice]][source]

Get all Olm devices participating in a room.

Parameters:

room_id (str) – The id of the room for which we would like to collect all the devices.

Returns a dictionary holding the user as the key and a dictionary of the device id as the key and OlmDevice as the value.

Raises LocalProtocolError if no room is found with the given room_id.

property should_claim_keys: bool

Check if the client should claim one-time keys for some users.

This should be periodically checked and if true a keys claim request should be made with the return value of a get_users_for_key_claiming() call as the payload.

Keys need to be claimed for various reasons. Every time we need to send an encrypted message to a device and we don’t have a working Olm session with them we need to claim one-time keys to create a new Olm session.

Returns True if a key query is necessary, false otherwise.

property should_query_keys: bool

Check if the client should make a key query call to the server.

Returns True if a key query is necessary, false otherwise.

property should_upload_keys: bool

Check if the client should upload encryption keys.

Returns True if encryption keys need to be uploaded, false otherwise.

unblacklist_device(device: OlmDevice) bool[source]

Unmark a device as blacklisted.

Parameters:

device (OlmDevice) – The device which should be removed from the blacklist.

Returns true if the device was removed, false if it wasn’t on the blacklist and no removal happened.

unignore_device(device: OlmDevice) bool[source]

Unmark a device as ignored.

Parameters:

device (OlmDevice) – The device which should be removed from the list of ignored devices.

Returns true if the device was removed, false if it wasn’t on the list and no removal happened.

unverify_device(device: OlmDevice) bool[source]

Unmark a device as verified.

This method removes the device from the trusted devices and disables sharing room encryption keys with it. It also invalidates any encryption keys for rooms that the device takes part of.

Parameters:

device (OlmDevice) – The device which should be added to the trust list.

Returns true if the device was unverified, false if it was already unverified.

property users_for_key_query: Set[str]

Users for whom we should make a key query.

verify_device(device: OlmDevice) bool[source]

Mark a device as verified.

A device needs to be either trusted/ignored or blacklisted to either share room encryption keys with it or not. This method adds the device to the trusted devices and enables sharing room encryption keys with it.

Parameters:

device (OlmDevice) – The device which should be added to the trust list.

Returns true if the device was verified, false if it was already verified.

AsyncClient

class nio.AsyncClient(homeserver: str, user: str = '', device_id: str | None = '', store_path: str | None = '', config: AsyncClientConfig | None = None, ssl: bool | None = None, proxy: str | None = None)[source]

Bases: Client

An async IO matrix client.

Parameters:
  • homeserver (str) – The URL of the homeserver which we want to connect to.

  • user (str, optional) – The user which will be used when we log in to the homeserver.

  • device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.

  • store_path (str, optional) – The directory that should be used for state storage.

  • config (AsyncClientConfig, optional) – Configuration for the client.

  • ssl (bool/ssl.SSLContext, optional) – SSL validation mode. None for default SSL check (ssl.create_default_context() is used), False for skip SSL certificate validation connection.

  • proxy (str, optional) – The proxy that should be used for the HTTP connection. Supports SOCKS4(a), SOCKS5, HTTP (tunneling) via an URL like e.g. ‘socks5://user:password@127.0.0.1:1080’.

synced

An asyncio event that is fired every time the client successfully syncs with the server. Note, this event will only be fired if the sync_forever() method is used.

Type:

Event

A simple example can be found bellow.

Example

>>> client = AsyncClient("https://example.org", "example")
>>> login_response = loop.run_until_complete(
>>>     client.login("hunter1")
>>> )
>>> asyncio.run(client.sync_forever(30000))

This example assumes a full sync on every run. If a sync token is provided for the since parameter of the sync_forever method full_state should be set to True as well.

Example

>>> asyncio.run(
>>>     client.sync_forever(30000, since="token123",
>>>                         full_state=True)
>>> )

The client can also be configured to store and restore the sync token automatically. The full_state argument should be set to True in that case as well.

Example

>>> config = ClientConfig(store_sync_tokens=True)
>>> client = AsyncClient("https://example.org", "example",
>>>                      store_path="/home/example",
>>>                      config=config)
>>> login_response = loop.run_until_complete(
>>>     client.login("hunter1")
>>> )
>>> asyncio.run(client.sync_forever(30000, full_state=True))
async accept_key_verification(transaction_id: str, tx_id: str | None = None) ToDeviceResponse | ToDeviceError[source]

Accept a key verification start event.

Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.

Parameters:

transaction_id (str) – An transaction id of a valid key verification process.

add_response_callback(func: Coroutine[Any, Any, Response], cb_filter: Tuple[Type] | Type | None = None)[source]

Add a coroutine that will be called if a response is received.

Parameters:
  • func (Coroutine) – The coroutine that will be called with the response as the argument.

  • cb_filter (Type, optional) – A type or a tuple of types for which the callback should be called.

Example

>>> # A callback that will be called every time our `sync_forever`
>>> # method successfully syncs with the server.
>>> async def sync_cb(response):
...    print(f"We synced, token: {response.next_batch}")
...
>>> client.add_response_callback(sync_cb, SyncResponse)
>>> await client.sync_forever(30000)
async cancel_key_verification(transaction_id: str, reject: bool = False, tx_id: str | None = None) ToDeviceResponse | ToDeviceError[source]

Cancel a interactive key verification with the given device.

Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.

Parameters:
  • transaction_id (str) – An transaction id of a valid key verification process.

  • reject (bool) – Is the cancelation reason because we’re rejecting the short auth string and mark it as mismatching or a normal user cancelation.

Raises a LocalProtocolError no verification process with the given transaction ID exists or if reject is True and the short auth string couldn’t be shown yet because plublic keys weren’t yet exchanged.

async close()[source]

Close the underlying http session.

async confirm_short_auth_string(transaction_id: str, tx_id: str | None = None) ToDeviceResponse | ToDeviceError[source]

Confirm a short auth string and mark it as matching.

Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.

Parameters:

transaction_id (str) – An transaction id of a valid key verification process.

async content_repository_config() ContentRepositoryConfigResponse | ContentRepositoryConfigError[source]

Get the content repository configuration, such as upload limits.

Calls receive_response() to update the client state if necessary.

Returns either a ContentRepositoryConfigResponse if the request was successful or a ContentRepositoryConfigError if there was an error with the request.

async create_matrix_response(response_class: Type, transport_response: ClientResponse, data: Tuple[Any, ...] | None = None, save_to: PathLike | None = None) Response[source]

Transform a transport response into a nio matrix response.

Low-level function which is normally only used by other methods of this class.

Parameters:
  • response_class (Type) – The class that the requests belongs to.

  • transport_response (ClientResponse) – The underlying transport response that contains our response body.

  • data (Tuple, optional) – Extra data that is required to instantiate the response class.

  • save_to (PathLike, optional) – If set, the FileResponse body will be saved to this file.

Returns a subclass of Response depending on the type of the response_class argument.

async delete_devices(devices: List[str], auth: Dict[str, str] | None = None) DeleteDevicesResponse | DeleteDevicesError[source]

Delete a list of devices.

This tells the server to delete the given devices and invalidate their associated access tokens.

Calls receive_response() to update the client state if necessary.

Returns either a DeleteDevicesResponse if the request was successful or a DeleteDevicesError if there was an error with the request.

This endpoint supports user-interactive auth, calling this method without an auth dictionary will return a DeleteDevicesAuthResponse which can be used to introspect the valid authentication methods that the server supports.

Parameters:
  • devices (List[str]) – A list of devices which will be deleted.

  • auth (Dict) – Additional authentication information for the user-interactive authentication API.

Example

>>> devices = ["QBUAZIFURK", "AUIECTSRND"]
>>> auth = {"type": "m.login.password",
...         "user": "example",
...         "password": "hunter1"}
>>> await client.delete_devices(devices, auth)
async delete_pushrule(scope: str, kind: PushRuleKind, rule_id: str) DeletePushRuleResponse | DeletePushRuleError[source]

Delete an existing push rule.

Returns either a DeletePushRuleResponse if the request was successful or a DeletePushRuleError if there was an error with the request.

Parameters:
  • scope (str) – The scope of this rule, e.g. "global". Homeservers currently only process global rules for event matching, while device rules are a planned feature. It is up to clients to interpret any other scope name.

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

async devices() DevicesResponse | DevicesError[source]

Get the list of devices for the current user.

Calls receive_response() to update the client state if necessary.

Returns either a DevicesResponse if the request was successful or a DevicesError if there was an error with the request.

async discovery_info() DiscoveryInfoResponse | DiscoveryInfoError[source]

Get discovery information about current AsyncClient.homeserver.

Returns either a DiscoveryInfoResponse if the request was successful or a DiscoveryInfoError if there was an error with the request.

Some homeservers do not redirect requests to their main domain and instead require clients to use a specific URL for communication.

If the domain specified by the AsyncClient.homeserver URL implements the [.well-known](https://matrix.org/docs/spec/client_server/latest#id178), discovery mechanism, this method can be used to retrieve the actual homeserver URL from it.

Example

>>> client = AsyncClient(homeserver="https://example.org")
>>> response = await client.discovery_info()
>>> if isinstance(response, DiscoveryInfoResponse):
>>>     client.homeserver = response.homeserver_url
async download(mxc: str | None = None, filename: str | None = None, allow_remote: bool = True, server_name: str | None = None, media_id: str | None = None, save_to: PathLike | None = None) DiskDownloadResponse | MemoryDownloadResponse | DownloadError[source]

Get the content of a file from the content repository.

This method ignores AsyncClient.config.request_timeout and uses 0.

Calls receive_response() to update the client state if necessary.

Returns either a MemoryDownloadResponse or DiskDownloadResponse if the request was successful or a DownloadError if there was an error with the request.

The parameters server_name and media_id are deprecated and will be removed in a future release. Use mxc instead.

Parameters:
  • mxc (str, optional) – The mxc:// URI.

  • filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.

  • allow_remote (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.

  • server_name (str, optional) – [deprecated] The server name from the mxc:// URI.

  • media_id (str, optional) – [deprecated] The media ID from the mxc:// URI.

  • save_to (PathLike, optional) – If set, the downloaded file will be saved to this path, instead of being saved in-memory.

async enable_pushrule(scope: str, kind: PushRuleKind, rule_id: str, enable: bool) EnablePushRuleResponse | EnablePushRuleError[source]

Enable or disable an existing push rule.

Returns either a EnablePushRuleResponse if the request was successful or a EnablePushRuleError if there was an error with the request.

Parameters:
  • scope (str) – The scope of this rule, e.g. "global". Homeservers currently only process global rules for event matching, while device rules are a planned feature. It is up to clients to interpret any other scope name.

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

  • enable (bool) – Whether to enable or disable this rule.

export_keys(outfile: str, passphrase: str, count: int = 10000)[source]

Export all the Megolm decryption keys of this device.

The keys will be encrypted using the passphrase.

Note that this does not save other information such as the private identity keys of the device.

Parameters:
  • outfile (str) – The file to write the keys to.

  • passphrase (str) – The encryption passphrase.

  • count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.

async get_avatar(user_id: str | None = None) ProfileGetAvatarResponse | ProfileGetAvatarError[source]

Get a user’s avatar URL.

This queries the avatar matrix content URI of a user from the server. The currently logged in user is queried if no user is specified.

Calls receive_response() to update the client state if necessary.

Returns either a ProfileGetAvatarResponse if the request was successful or a ProfileGetAvatarError if there was an error with the request.

Parameters:

user_id (str) – User id of the user to get the avatar for.

async get_displayname(user_id: str | None = None) ProfileGetDisplayNameResponse | ProfileGetDisplayNameError[source]

Get a user’s display name.

This queries the display name of a user from the server. The currently logged in user is queried if no user is specified.

Calls receive_response() to update the client state if necessary.

Returns either a ProfileGetDisplayNameResponse if the request was successful or a ProfileGetDisplayNameError if there was an error with the request.

Parameters:

user_id (str) – User id of the user to get the display name for.

async get_openid_token(user_id: str) GetOpenIDTokenResponse | GetOpenIDTokenError[source]

Gets an OpenID token object that the requester may supply to another service to verify their identity in matrix.

Returns either a GetOpenIDTokenResponse if the request was successful or a GetOpenIDTokenError if there was an error with the request.

Parameters:

user_id (str) – The user who requested the OpenID token

async get_presence(user_id: str) PresenceGetResponse | PresenceGetError[source]

Get a user’s presence state.

This queries the presence state of a user from the server.

Calls receive_response() to update the client state if necessary.

Returns either a PresenceGetResponse if the request was successful or a PresenceGetError if there was an error with the request.

Parameters:

user_id (str) – User id of the user to get the presence state for.

async get_profile(user_id: str | None = None) ProfileGetResponse | ProfileGetError[source]

Get a user’s combined profile information.

This queries the display name and avatar matrix content URI of a user from the server. Additional profile information may be present. The currently logged in user is queried if no user is specified.

Calls receive_response() to update the client state if necessary.

Returns either a ProfileGetResponse if the request was successful or a ProfileGetError if there was an error with the request.

Parameters:

user_id (str) – User id of the user to get the profile for.

async get_timeout_retry_wait_time(got_timeouts: int) float[source]
async has_event_permission(room_id: str, event_name: str, event_type: str = 'event') bool | ErrorResponse[source]
async has_permission(room_id: str, permission_type: str) bool | ErrorResponse[source]
import_keys(infile: str, passphrase: str)[source]

Import Megolm decryption keys.

The keys will be added to the current instance as well as written to database.

Parameters:
  • infile (str) – The file containing the keys.

  • passphrase (str) – The decryption passphrase.

Raises EncryptionError if the file is invalid or couldn’t be

decrypted.

Raises the usual file errors if the file couldn’t be opened.

async join(room_id: str) JoinResponse | JoinError[source]

Join a room.

This tells the server to join the given room. If the room is not public, the user must be invited.

Calls receive_response() to update the client state if necessary.

Returns either a JoinResponse if the request was successful or a JoinError if there was an error with the request.

Parameters:

room_id – The room id or alias of the room to join.

async joined_members(room_id: str) JoinedMembersResponse | JoinedMembersError[source]

Get the list of joined members for a room.

Calls receive_response() to update the client state if necessary.

Returns either a JoinedMembersResponse if the request was successful or a JoinedMembersError if there was an error with the request.

Parameters:

room_id (str) – The room id of the room for which we wan’t to request the joined member list.

async joined_rooms() JoinedRoomsResponse | JoinedRoomsError[source]

Get the list of joined rooms.

Calls receive_response() to update the client state if necessary.

Returns either a JoinedRoomsResponse if the request was successful or a JoinedRoomsError if there was an error with the request.

async keys_claim(user_set: Dict[str, Iterable[str]]) KeysClaimResponse | KeysClaimError[source]

Claim one-time keys for a set of user and device pairs.

Automatically called by sync_forever() and room_send().

Calls receive_response() to update the client state if necessary.

Parameters:

user_set (Dict[str, Iterator[str]]) – A dictionary mapping from a user id to a iterator of device ids. If a user set for a specific room is required it can be obtained using the get_missing_sessions() method.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists or the room isn’t an encrypted room.

async keys_query() KeysQueryResponse | KeysQueryError[source]

Query the server for user keys.

This queries the server for device keys of users with which we share an encrypted room.

Automatically called by sync_forever() and room_send().

Calls receive_response() to update the client state if necessary.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded or if no key query needs to be performed.

async keys_upload() KeysUploadResponse | KeysUploadError[source]

Upload the E2E encryption keys.

This uploads the long lived session keys as well as the required amount of one-time keys.

Automatically called by sync_forever().

Calls receive_response() to update the client state if necessary.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded or if no encryption keys need to be uploaded.

async list_direct_rooms() DirectRoomsResponse | DirectRoomsErrorResponse[source]

Lists all rooms flagged with m.direct that the client is participating in.

Returns a DirectRoomListResponse if the request was successful, or DirectRoomListErrorResponse if there was an error, or the current user has never marked any rooms marked with m.direct

async login(password: str | None = None, device_name: str | None = '', token: str | None = None) LoginResponse | LoginError[source]

Login to the homeserver.

Calls receive_response() to update the client state if necessary.

Parameters:
  • password (str, optional) – The user’s password.

  • device_name (str) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.

  • token (str, optional) – A login token, for example provided by a single sign-on service.

Either a password or a token needs to be provided.

Returns either a LoginResponse if the request was successful or a LoginError if there was an error with the request.

async login_info() LoginInfoResponse | LoginInfoError[source]

Get the available login methods from the server

Returns either a LoginInfoResponse if the request was successful or a LoginInfoError if there was an error with the request.

async login_raw(auth_dict: Dict[str, Any]) LoginResponse | LoginError[source]

Login to the homeserver using a raw dictionary.

Calls receive_response() to update the client state if necessary.

Parameters:

auth_dict (Dict[str, Any]) –

The auth dictionary. See the example below and here

for detailed documentation

Example

>>> auth_dict = {
>>>     "type": "m.login.password",
>>>     "identifier": {
>>>         "type": "m.id.thirdparty",
>>>         "medium": "email",
>>>         "address": "testemail@mail.org"
>>>     },
>>>     "password": "PASSWORDABCD",
>>>     "initial_device_display_name": "Test user"
>>> }

Returns either a LoginResponse if the request was successful or a LoginError if there was an error with the request.

async logout(all_devices: bool = False) LogoutResponse | LogoutError[source]

Logout from the homeserver.

Calls receive_response() to update the client state if necessary.

Returns either ‘LogoutResponse’ if the request was successful or a Logouterror if there was an error with the request.

async mxc_to_http(mxc: str, homeserver: str | None = None) str | None[source]

Convert a matrix content URI to a HTTP URI.

async parse_body(transport_response: ClientResponse) Dict[Any, Any][source]

Parse the body of the response.

Low-level function which is normally only used by other methods of this class.

Parameters:

transport_response (ClientResponse) – The transport response that contains the body of the response.

Returns a dictionary representing the response.

async receive_response(response: Response) None[source]

Receive a Matrix Response and change the client state accordingly.

Automatically called for all “high-level” methods of this API (each function documents calling it).

Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible.

Parameters:

response (Response) – the response that we wish the client to handle

async register(username: str, password: str, device_name: str = '', session_token: str | None = None) RegisterResponse | RegisterErrorResponse[source]

Register with homeserver.

Calls receive_response() to update the client state if necessary.

Parameters:
  • username (str) – Username to register the new user as.

  • password (str) – New password for the user.

  • device_name (str, optional) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.

  • session_token (str, optional) – The session token the server provided during interactive registration. If not provided, the session token is not added to the request’s auth dict.

Returns a ‘RegisterResponse’ if successful.

async register_interactive(username: str, password: str, auth_dict: Dict[str, Any], device_name: str = '') RegisterInteractiveResponse | RegisterInteractiveError[source]

Makes a request to the register endpoint using the provided auth dictionary. This is allows for interactive registration flows from the homeserver.

Calls receive_response() to update the client state if necessary.

Parameters:
  • username (str) – Username to register the new user as.

  • password (str) – New password for the user.

  • auth_dict (dict) – The auth dictionary.

  • device_name (str) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.

Returns a ‘RegisterInteractiveResponse’ if successful.

async register_with_token(username: str, password: str, registration_token: str, device_name: str = '') RegisterResponse | RegisterErrorResponse[source]

Registers a user using a registration token. See https://spec.matrix.org/latest/client-server-api/#token-authenticated-registration

Returns either a RegisterResponse if the request was successful or a RegisterErrorResponse if there was an error with the request.

async request_room_key(event: MegolmEvent, tx_id: str | None = None) RoomKeyRequestResponse | RoomKeyRequestError[source]

Request a missing room key.

This sends out a message to other devices requesting a room key from them.

Calls receive_response() to update the client state if necessary.

Returns either a RoomKeyRequestResponse if the request was successful or a RoomKeyRequestError if there was an error with the request.

Raises a LocalProtocolError if the room key was already requested.

Parameters:

event (MegolmEvent) – An undecrypted MegolmEvent for which we would like to request the decryption key.

async room_ban(room_id: str, user_id: str, reason: str | None = None) RoomBanResponse | RoomBanError[source]

Ban a user from a room.

When a user is banned from a room, they may not join it or be invited to it until they are unbanned. If they are currently in the room, they will be kicked or have their invitation withdrawn first.

Calls receive_response() to update the client state if necessary.

Returns either a RoomBanResponse if the request was successful or a RoomBanError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that the user will be banned from.

  • user_id (str) – The user_id of the user that should be banned.

  • reason (str, optional) – A reason for which the user is banned.

async room_context(room_id: str, event_id: str, limit: int | None = None) RoomContextResponse | RoomContextError[source]

Fetch a number of events that happened before and after an event.

This allows clients to get the context surrounding an event.

Calls receive_response() to update the client state if necessary.

Returns either a RoomContextResponse if the request was successful or a RoomContextError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that contains the event and its context.

  • event_id (str) – The event_id of the event that we wish to get the context for.

  • limit (int, optional) – The maximum number of events to request.

async room_create(visibility: RoomVisibility = RoomVisibility.private, alias: str | None = None, name: str | None = None, topic: str | None = None, room_version: str | None = None, room_type: str | None = None, federate: bool = True, is_direct: bool = False, preset: RoomPreset | None = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Dict[str, Any] | None = None, predecessor: Dict[str, Any] | None = None, space: bool = False) RoomCreateResponse | RoomCreateError[source]

Create a new room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomCreateResponse if the request was successful or a RoomCreateError if there was an error with the request.

Parameters:
  • visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to RoomVisibility.private.

  • alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.

  • name (str, optional) – A name to set for the room.

  • topic (str, optional) – A topic to set for the room.

  • room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400 M_UNSUPPORTED_ROOM_VERSION error will be returned.

  • room_type (str, optional) –

    The room type to set. If not specified, the homeserver will use its default setting. In spec v1.2 the following room types are specified:

    • m.space

    Unspecified room types are permitted through the use of Namespaced Identifiers.

  • federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to True. Cannot be changed later.

  • is_direct (bool) – If this should be considered a direct messaging room. If True, the server will set the is_direct flag on m.room.member events sent to the users in invite. Defaults to False.

  • preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the visibility: RoomVisibility.public equates to RoomPreset.public_chat, and RoomVisibility.private equates to a RoomPreset.private_chat.

  • invite (list) – A list of user id to invite to the room.

  • initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediately by having a m.room.encryption event dict.

  • power_level_override (dict) – A m.room.power_levels content dict to override the default. The dict will be applied on top of the generated m.room.power_levels event before it is sent to the room.

  • predecessor (dict) – A reference to the room this room replaces, if the previous room was upgraded. Containing the event ID of the last known event in the old room. And the ID of the old room. event_id: $something:example.org, room_id: !oldroom:example.org

  • space (bool) – Create as a Space (defaults to False).

async room_delete_alias(room_alias: str) RoomDeleteAliasResponse | RoomDeleteAliasError[source]

Delete a room alias.

Calls receive_response() to update the client state if necessary.

Returns either a RoomDeleteAliasResponse if the request was successful or a `RoomDeleteAliasError if there was an error with the request.

Parameters:

room_alias (str) – The alias to delete

async room_enable_knocking(room_id: str) RoomPutStateResponse | RoomPutStateError[source]

Enables knocking for a room.

Returns either a RoomPutStateResponse if the request was successful or a RoomPutStateError if there was an error with the request.

Parameters:

room_id (str) – The room id of the room to enable knocking for.

async room_forget(room_id: str) RoomForgetResponse | RoomForgetError[source]

Forget a room.

This tells the server to forget the given room’s history for our user. If all users on a homeserver forget the room, the room will be eligible for deletion from that homeserver.

Calls receive_response() to update the client state if necessary.

Returns either a RoomForgetResponse if the request was successful or a RoomForgetError if there was an error with the request.

Parameters:

room_id (str) – The room id of the room to forget.

async room_get_event(room_id: str, event_id: str) RoomGetEventResponse | RoomGetEventError[source]

Get a single event based on roomId/eventId.

Calls receive_response() to update the client state if necessary.

Returns either a RoomGetEventResponse if the request was successful or a RoomGetEventError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room where the event is in.

  • event_id (str) – The event id to get.

async room_get_event_relations(*args, **kwargs)
async room_get_state(room_id: str) RoomGetStateResponse | RoomGetStateError[source]

Fetch state for a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomGetStateResponse if the request was successful or a RoomGetStateError if there was an error with the request.

Parameters:

room_id (str) – The room id of the room to fetch state from.

async room_get_state_event(room_id: str, event_type: str, state_key: str = '') RoomGetStateEventResponse | RoomGetStateEventError[source]

Fetch a state event from a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomGetStateEventResponse if the request was successful or a RoomGetStateEventError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room to fetch the event from.

  • event_type (str) – The type of the state to fetch.

  • state_key (str) – The key of the state event to fetch.

async room_get_threads(*args, **kwargs)
async room_get_visibility(room_id: str) RoomGetVisibilityResponse | RoomGetVisibilityError[source]

Get visibility for a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomGetVisibilityResponse if the request was successful or a `RoomGetVisibilityError if there was an error with the request.

Parameters:

room_id (str) – The room ID to get visibility for

async room_invite(room_id: str, user_id: str) RoomInviteResponse | RoomInviteError[source]

Invite a user to a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomInviteResponse if the request was successful or a RoomInviteError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that the user will be invited to.

  • user_id (str) – The user id of the user that should be invited.

async room_kick(room_id: str, user_id: str, reason: str | None = None) RoomKickResponse | RoomKickError[source]

Kick a user from a room, or withdraw their invitation.

Kicking a user adjusts their membership to “leave” with an optional reason.

Calls receive_response() to update the client state if necessary.

Returns either a RoomKickResponse if the request was successful or a RoomKickError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that the user will be kicked from.

  • user_id (str) – The user_id of the user that should be kicked.

  • reason (str, optional) – A reason for which the user is kicked.

async room_knock(room_id: str, reason: str | None = None) RoomKnockResponse | RoomKnockError[source]

Knock on a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomKnockResponse if the request was successful or a RoomKnockError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that the user is knocking on.

  • reason (str, optional) – The reason for the knock.

async room_leave(room_id: str) RoomLeaveResponse | RoomLeaveError[source]

Leave a room or reject an invite.

This tells the server to leave the given room. If the user was only invited, the invite is rejected.

Calls receive_response() to update the client state if necessary.

Returns either a RoomLeaveResponse if the request was successful or a RoomLeaveError if there was an error with the request.

Parameters:

room_id – The room id of the room to leave.

async room_messages(room_id: str, start: str | None = None, end: str | None = None, direction: MessageDirection = MessageDirection.back, limit: int = 10, message_filter: Dict[Any, Any] | None = None) RoomMessagesResponse | RoomMessagesError[source]

Fetch a list of message and state events for a room.

It uses pagination query parameters to paginate history in the room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomMessagesResponse if the request was successful or a RoomMessagesError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room for which we would like to fetch the messages.

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

  • end (str, optional) – The token to stop returning events at. 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.

  • direction (MessageDirection, optional) – The direction to return events from. Defaults to MessageDirection.back.

  • limit (int, optional) – The maximum number of events to return. Defaults to 10.

  • message_filter (Optional[Dict[Any, Any]]) – A filter dict that should be used for this room messages request.

Example

>>> response = await client.room_messages(room_id, previous_batch)
>>> next_response = await client.room_messages(room_id,
...                                            response.end)
async room_put_alias(room_alias: str, room_id: str) RoomPutAliasResponse | RoomPutAliasError[source]

Add a room alias.

Calls receive_response() to update the client state if necessary.

Returns either a RoomPutAliasResponse if the request was successful or a `RoomPutAliasError if there was an error with the request.

Parameters:
  • room_alias (str) – The alias to add

  • room_id (str) – The room ID to map to

async room_put_state(room_id: str, event_type: str, content: Dict[Any, Any], state_key: str = '') RoomPutStateResponse | RoomPutStateError[source]

Send a state event to a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomPutStateResponse if the request was successful or a RoomPutStateError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room to send the event to.

  • event_type (str) – The type of the state to send.

  • content (Dict[Any, Any]) – The content of the event to be sent.

  • state_key (str) – The key of the state event to send.

async room_read_markers(room_id: str, fully_read_event: str, read_event: str | None = None, private_read_event: str | None = None)[source]

Update the fully read marker (and optionally the read receipt and/or private read receipt) for a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomReadMarkersResponse if the request was successful or a RoomReadMarkersError if there was an error with the request.

This sets the “up to” position of the read markers.

  • fully_read_event is the latest event in the set of events that the user has either fully read or indicated they aren’t interested in. It permits the implementation of a “jump to first unread message” kind of feature. It is _private_ (not exposed to other room participants).

  • read_event is the most recent message the user has read and is also known as a _read receipt_. A read receipt being set on an event does not imply that all previous events have been seen. This happens in cases such as when a user comes back to a room after hundreds of messages have been sent and _only_ reads the most recent message. The read receipt is _public_ (exposed to other room participants).

  • private_read_event is the same as read_event, is intended to clear

notifications without advertising read-up-to status to others, and is _private_ (not exposed to other room participants) as the name implies.

Parameters:
  • room_id (str) – The room ID of the room where the read markers should be updated.

  • fully_read_event (str) – The event ID that the user has fully read up to.

  • read_event (Optional[str]) – The event ID to set the read receipt location at.

  • private_read_event (Optional[str]) – The event ID to set the private read receipt location at.

async room_redact(room_id: str, event_id: str, reason: str | None = None, tx_id: None | str | UUID = None) RoomRedactResponse | RoomRedactError[source]

Strip information out of an event.

Calls receive_response() to update the client state if necessary.

Returns either a RoomRedactResponse if the request was successful or a RoomRedactError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that contains the event that will be redacted.

  • event_id (str) – The ID of the event that will be redacted.

  • tx_id (str/UUID, optional) – A transaction ID for this event.

  • reason (str, optional) – A description explaining why the event was redacted.

async room_resolve_alias(room_alias: str) RoomResolveAliasResponse | RoomResolveAliasError[source]

Resolve a room alias to a room ID.

Calls receive_response() to update the client state if necessary.

Returns either a RoomResolveAliasResponse if the request was successful or a `RoomResolveAliasError if there was an error with the request.

Parameters:

room_alias (str) – The alias to resolve

async room_send(room_id: str, message_type: str, content: Dict[Any, Any], tx_id: str | None = None, ignore_unverified_devices: bool = False) RoomSendResponse | RoomSendError[source]

Send a message to a room.

Calls receive_response() to update the client state if necessary.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.

  • message_type (str) – A string identifying the type of the message.

  • content (Dict[Any, Any]) – A dictionary containing the content of the message.

  • tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.

  • ignore_unverified_devices (bool) – If the room is encrypted and contains unverified devices, the devices can be marked as ignored here. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

If the room where the message should be sent is encrypted the message will be encrypted before sending.

This method also makes sure that the room members are fully synced and that keys are queried before sending messages to an encrypted room.

If the method can’t sync the state fully to send out an encrypted message after a couple of retries it raises SendRetryError.

Raises LocalProtocolError if the client isn’t logged in.

async room_typing(room_id: str, typing_state: bool = True, timeout: int = 30000) RoomTypingResponse | RoomTypingError[source]

Send a typing notice to the server.

This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.

Calls receive_response() to update the client state if necessary.

Returns either a RoomTypingResponse if the request was successful or a RoomTypingError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room where the user is typing.

  • typing_state (bool) – A flag representing whether the user started or stopped typing.

  • timeout (int) – For how long should the new typing notice be valid for in milliseconds.

async room_unban(room_id: str, user_id: str) RoomBanResponse | RoomBanError[source]

Unban a user from a room.

This allows them to be invited and join the room again.

Calls receive_response() to update the client state if necessary.

Returns either a RoomUnbanResponse if the request was successful or a RoomUnbanError if there was an error with the request.

Parameters:
  • room_id (str) – The room id of the room that the user will be unbanned from.

  • user_id (str) – The user_id of the user that should be unbanned.

async room_update_aliases(room_id: str, canonical_alias: str | None = None, alt_aliases: List[str] | None = None)[source]
Update the aliases of an existing room.

This method will not transfer aliases from one room to another! Remove the old alias before trying to assign it again

Parameters:
  • room_id (str) – Room-ID of the room to assign / remove aliases from

  • canonical_alias (str, None) – The main alias of the room

  • alt_aliases (list[str], None) – List of alternative aliases for the room

  • aliases (If None is passed as canonical_alias or alt_aliases the existing) – will be removed without assigning new aliases.

async room_upgrade(old_room_id: str, new_room_version: str, copy_events: list = ['m.room.server_acl', 'm.room.encryption', 'm.room.name', 'm.room.avatar', 'm.room.topic', 'm.room.guest_access', 'm.room.history_visibility', 'm.room.join_rules', 'm.room.power_levels'], room_upgrade_message: str = 'This room has been replaced', room_power_level_overwrite: Dict[str, Any] | None = None) RoomUpgradeResponse | RoomUpgradeError[source]

Upgrade an existing room.

Parameters:
  • old_room_id (str) – Room-ID of the old room

  • new_room_version (str) – The new room version

  • copy_events (list) –

    List of state-events to copy from the old room Defaults m.room.server_acl, m.room.encryption, m.room.name,

    m.room.avatar, m.room.topic, m.room.guest_access, m.room.history_visibility, m.room.join_rules, m.room.power_levels

  • room_upgrade_message (str) – Message inside the tombstone-event

  • room_power_level_overwrite (dict) – A m.room.power_levels content dict to override the default. The dict will be applied on top of the generated m.room.power_levels event before it is sent to the room.

async run_response_callbacks(responses: List[Response | ErrorResponse])[source]

Run the configured response callbacks for the given responses.

Low-level function which is normally only used by other methods of this class. Automatically called by sync_forever() and all functions calling receive_response().

async send(method: str, path: str, data: None | str | Path | bytes | Iterable[bytes] | AsyncIterable[bytes] | BufferedIOBase | AsyncBufferedReader = None, headers: Dict[str, str] | None = None, trace_context: Any | None = None, timeout: float | None = None) ClientResponse[source]

Send a request to the homeserver.

This function does not call receive_response().

Parameters:
  • method (str) – The request method that should be used. One of get, post, put, delete.

  • path (str) – The URL path of the request.

  • data (str, optional) – Data that will be posted with the request.

  • headers (Dict[str,str] , optional) – Additional request headers that should be used with the request.

  • trace_context (Any, optional) – An object to use for the ClientSession TraceConfig context

  • timeout (int, optional) – How many seconds the request has before raising asyncio.TimeoutError. Overrides AsyncClient.config.request_timeout if not None.

async send_to_device_messages() List[ToDeviceResponse | ToDeviceError][source]

Send out outgoing to-device messages.

Automatically called by sync_forever().

async set_avatar(avatar_url: str) ProfileSetAvatarResponse | ProfileSetAvatarError[source]

Set the user’s avatar URL.

This tells the server to set the avatar of the currently logged in user to supplied matrix content URI.

Calls receive_response() to update the client state if necessary.

Returns either a ProfileSetAvatarResponse if the request was successful or a ProfileSetAvatarError if there was an error with the request.

Parameters:

avatar_url (str) – matrix content URI of the avatar to set.

async set_displayname(displayname: str) ProfileSetDisplayNameResponse | ProfileSetDisplayNameError[source]

Set user’s display name.

This tells the server to set display name of the currently logged in user to the supplied string.

Calls receive_response() to update the client state if necessary.

Returns either a ProfileSetDisplayNameResponse if the request was successful or a ProfileSetDisplayNameError if there was an error with the request.

Parameters:

displayname (str) – Display name to set.

async set_presence(presence: str, status_msg: str | None = None) PresenceSetResponse | PresenceSetError[source]

Set our user’s presence state.

This tells the server to set presence state of the currently logged in user to the supplied string.

Calls receive_response() to update the client state if necessary.

Returns either a PresenceSetResponse if the request was successful or a PresenceSetError if there was an error with the request.

Parameters:
  • presence (str) – The new presence state. One of: [“online”, “offline”, “unavailable”]

  • status_msg (str, optional) – The status message to attach to this state.

async set_pushrule(scope: str, kind: PushRuleKind, rule_id: str, before: str | None = None, after: str | None = None, actions: Sequence[PushAction] = (), conditions: Sequence[PushCondition] | None = None, pattern: str | None = None) SetPushRuleResponse | SetPushRuleError[source]

Create or modify an existing push rule.

Returns either a SetPushRuleResponse if the request was successful or a SetPushRuleError if there was an error with the request.

Parameters:
  • scope (str) – The scope of this rule, e.g. "global". Homeservers currently only process global rules for event matching, while device rules are a planned feature. It is up to clients to interpret any other scope name.

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind. For rules of room kind, this is the room ID to match for. For rules of sender kind, this is the user ID to match.

  • before (Optional[str]) – Position this rule before the one matching the given rule ID. The rule ID cannot belong to a predefined server rule. before and after cannot be both specified.

  • after (Optional[str]) – Position this rule after the one matching the given rule ID. The rule ID cannot belong to a predefined server rule. before and after cannot be both specified.

  • actions (Sequence[PushAction]) – Actions to perform when the conditions for this rule are met. The given actions replace the existing ones.

  • conditions (Sequence[PushCondition]) – Event conditions that must hold true for the rule to apply to that event. A rule with no conditions always hold true. Only applicable to underride and override rules.

  • pattern (Optional[str]) – Glob-style pattern to match against for the event’s content. Only applicable to content rules.

Example

>>> client.set_pushrule(
...     scope = "global",
...     kind = PushRuleKind.room,
...     rule_id = "!foo123:example.org",
...     actions = [PushNotify(), PushSetTweak("sound", "default")],
... )
...
... client.set_pushrule(
...     scope = "global",
...     kind = PushRuleKind.override,
...     rule_id = "silence_large_rooms",
...     actions = [],
...     conditions = [PushRoomMemberCount(10, ">")],
... )
...
... client.set_pushrule(
...     scope = "global",
...     kind = PushRuleKind.content,
...     rule_id = "highlight_messages_containing_nio_word",
...     actions = [PushNotify(), PushSetTweak("highlight", True)],
...     pattern = "nio"
... )
async set_pushrule_actions(scope: str, kind: PushRuleKind, rule_id: str, actions: Sequence[PushAction]) SetPushRuleActionsResponse | SetPushRuleActionsError[source]

Set the actions for an existing built-in or user-created push rule.

Unlike set_pushrule, this method can edit built-in server rules.

Returns the HTTP method, HTTP path and data for the request. Returns either a SetPushRuleActionsResponse if the request was successful or a SetPushRuleActionsError if there was an error with the request.

Parameters:
  • scope (str) – The scope of this rule, e.g. "global". Homeservers currently only process global rules for event matching, while device rules are a planned feature. It is up to clients to interpret any other scope name.

  • kind (PushRuleKind) – The kind of rule.

  • rule_id (str) – The identifier of the rule. Must be unique within its scope and kind.

  • actions (Sequence[PushAction]) – Actions to perform when the conditions for this rule are met. The given actions replace the existing ones.

async share_group_session(room_id: str, ignore_unverified_devices: bool = False) ShareGroupSessionResponse | ShareGroupSessionError[source]

Share a group session with a room.

This method sends a group session to members of a room.

Automatically called by room_send().

Calls receive_response() to update the client state if necessary.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.

  • ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists, the room isn’t an encrypted room or a key sharing request is already in flight for this room.

async space_get_hierarchy(space_id: str, from_page: str | None = None, limit: int | None = None, max_depth: int | None = None, suggested_only: bool = False) SpaceGetHierarchyResponse | SpaceGetHierarchyError[source]

Gets the space’s room hierarchy.

Calls receive_response() to update the client state if necessary.

Returns either a SpaceGetHierarchyResponse if the request was successful or a SpaceGetHierarchyError if there was an error with the request.

Parameters:
  • space_id (str) – The ID of the space to get the hierarchy for.

  • from_page (str, optional) – Pagination token from a previous request to this endpoint.

  • limit (int, optional) – The maximum number of rooms to return.

  • max_depth (int, optional) – The maximum depth of the returned tree.

  • suggested_only (bool, optional) – Whether or not to only return rooms that are considered suggested. Defaults to False.

async start_key_verification(device: OlmDevice, tx_id: str | None = None) ToDeviceResponse | ToDeviceError[source]

Start a interactive key verification with the given device.

Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.

Parameters:

device (OlmDevice) – An device with which we would like to start the interactive key verification process.

async sync(timeout: int | None = 0, sync_filter: None | str | Dict[Any, Any] = None, since: str | None = None, full_state: bool | None = None, set_presence: str | None = None) SyncResponse | SyncError[source]

Synchronise the client’s state with the latest state on the server.

In general you should use sync_forever() which handles additional tasks automatically (like sending encryption keys among others).

Calls receive_response() to update the client state if necessary.

Parameters:
  • timeout (int, optional) – The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If 0, no timeout is applied. If None, use AsyncClient.config.request_timeout. If a timeout is applied and the server fails to return after 15 seconds of expected timeout, the client will timeout by itself.

  • sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from AsyncClient.upload_filter() (preferred), or filter dict that should be used for this sync request.

  • full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter.

  • since (str, optional) – A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call.

  • set_presence (str, optional) – The presence state. One of: [“online”, “offline”, “unavailable”]

Returns either a SyncResponse if the request was successful or a SyncError if there was an error with the request.

async sync_forever(timeout: int | None = None, sync_filter: None | str | Dict[Any, Any] = None, since: str | None = None, full_state: bool | None = None, loop_sleep_time: int | None = None, first_sync_filter: None | str | Dict[Any, Any] = None, set_presence: str | None = None)[source]

Continuously sync with the configured homeserver.

This method calls the sync method in a loop. To react to events event callbacks should be configured.

The loop also makes sure to handle other required requests between syncs, including to_device messages and sending encryption keys if required. To react to the responses a response callback should be added.

Parameters:
  • timeout (int, optional) – The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If 0, no timeout is applied. If None, AsyncClient.config.request_timeout is used. In any case, 0 is always used for the first sync. If a timeout is applied and the server fails to return after 15 seconds of expected timeout, the client will timeout by itself.

  • sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from AsyncClient.upload_filter() (preferred), or filter dict that should be used for sync requests.

  • full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter. This argument will be used only for the first sync request.

  • since (str, optional) – A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call. This argument will be used only for the first sync request, the subsequent sync requests will use the token from the last sync response.

  • loop_sleep_time (int, optional) – The sleep time, if any, between successful sync loop iterations in milliseconds.

  • first_sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from AsyncClient.upload_filter() (preferred), or filter dict to use for the first sync request only. If None (default), the sync_filter parameter’s value is used. To have no filtering for the first sync regardless of sync_filter’s value, pass {}.

  • set_presence (str, optional) – The presence state. One of: [“online”, “offline”, “unavailable”]

async thumbnail(server_name: str, media_id: str, width: int, height: int, method: ResizingMethod = ResizingMethod.scale, allow_remote: bool = True) ThumbnailResponse | ThumbnailError[source]

Get the thumbnail of a file from the content repository.

The actual thumbnail may be larger than the size specified. This method ignores AsyncClient.config.request_timeout and uses 0.

Calls receive_response() to update the client state if necessary.

Returns either a ThumbnailResponse if the request was successful or a ThumbnailError if there was an error with the request.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.

  • media_id (str) – The media ID from the mxc:// URI.

  • width (int) – The desired width of the thumbnail.

  • height (int) – The desired height of the thumbnail.

  • method (ResizingMethod) – The desired resizing method.

  • allow_remote (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.

async to_device(message: ToDeviceMessage, tx_id: str | None = None) ToDeviceResponse | ToDeviceError[source]

Send a to-device message.

Calls receive_response() to update the client state if necessary.

Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.

Parameters:
  • message (ToDeviceMessage) – The message that should be sent out.

  • tx_id (str, optional) – The transaction ID for this message. Should be unique.

async update_device(device_id: str, content: Dict[str, str]) UpdateDeviceResponse | UpdateDeviceError[source]

Update the metadata of the given device.

Returns either a UpdateDeviceResponse if the request was successful or a UpdateDeviceError if there was an error with the request.

Parameters:
  • device_id (str) – The device for which the metadata will be updated.

  • content (Dict[str, str]) – A dictionary of metadata values that will be updated for the device.

Example

>>> device_id = "QBUAZIFURK"
>>> content = {"display_name": "My new device"}
>>> await client.update_device(device_id, content)
async update_receipt_marker(room_id: str, event_id: str, receipt_type: ReceiptType = ReceiptType.read, thread_id: str | None = 'main') UpdateReceiptMarkerResponse | UpdateReceiptMarkerError[source]

Update the marker of given the receipt_type to specified event_id.

Calls receive_response() to update the client state if necessary.

Returns either a UpdateReceiptMarkerResponse if the request was successful or a UpdateReceiptMarkerError if there was an error with the request.

Parameters:
  • room_id (str) – Room id of the room where the marker should be updated

  • event_id (str) – The event ID the read marker should be located at

  • receipt_type (ReceiptType) – The type of receipt to send.

  • thread_id (str) – The thread root’s event ID. Defaults to “main” to indicate the main timeline, and thus not in any particular thread.

async update_room_topic(room_id: str, topic: str) RoomPutStateResponse | RoomPutStateError[source]

Update the room topic

Returns either a RoomPutStateResponse if the request was successful or a RoomPutStateError if there was an error with the request.

If you wish to send a state_key along with the request, use the room_put_state method instead.

Parameters:
  • room_id (str) – The room id of the room to be updated.

  • topic (str) – The new room topic.

async upload(data_provider: Callable[[int, int], str | Path | bytes | Iterable[bytes] | AsyncIterable[bytes] | BufferedIOBase | AsyncBufferedReader] | TextIOBase | BufferedReader | BufferedRandom | BytesIO | FileIO | AsyncBufferedReader | AsyncTextIOWrapper, content_type: str = 'application/octet-stream', filename: str | None = None, encrypt: bool = False, monitor: TransferMonitor | None = None, filesize: int | None = None) Tuple[UploadResponse | UploadError, Dict[str, Any] | None][source]

Upload a file to the content repository.

This method ignores AsyncClient.config.request_timeout and uses 0.

Calls receive_response() to update the client state if necessary.

Returns a tuple containing:

  • Either a UploadResponse if the request was successful, or a UploadError if there was an error with the request

  • A dict with file decryption info if encrypt is True, else None.

Raises a TransferCancelledError if a monitor is passed and its cancelled property becomes set to True.

Parameters:
  • data_provider (Callable, SynchronousFile, AsyncFile) –

    A function returning the data to upload or a file object. File objects must be opened in binary mode (mode="r+b"). Callables returning a path string, Path, async iterable or aiofiles open binary file object allow the file data to be read in an asynchronous and lazy way (without reading the entire file into memory). Returning a synchronous iterable or standard open binary file object will still allow the data to be read lazily, but not asynchronously.

    The function will be called again if the upload fails due to a server timeout, in which case it must restart from the beginning. Callables receive two arguments: the total number of 429 “Too many request” errors that occurred, and the total number of server timeout exceptions that occurred, thus cleanup operations can be performed for retries if necessary.

  • content_type (str) – The content MIME type of the file, e.g. “image/png”. Defaults to “application/octet-stream”, corresponding to a generic binary file. Custom values are ignored if encrypt is True.

  • filename (str, optional) – The file’s original name.

  • encrypt (bool) – If the file’s content should be encrypted, necessary for files that will be sent to encrypted rooms. Defaults to False.

  • monitor (TransferMonitor, optional) – If a TransferMonitor object is passed, it will be updated by this function while uploading. From this object, statistics such as currently transferred bytes or estimated remaining time can be gathered while the upload is running as a task; it also allows for pausing and cancelling.

  • filesize (int, optional) – Size in bytes for the file to transfer. If left as None, some servers might refuse the upload.

It’s common to use this alongside room_send(). An example of uploading a plain text file follows, but the principle is the same for media, you just need to add an additional “info” key to the content. See the Matrix client-server spec for more details.

Example

>>> file_stat = await aiofiles.os.stat("sample.py")
>>> async with aiofiles.open("sample.py", "r+b") as f:
>>>    resp, maybe_keys = await client.upload(
...        f,
...        content_type="text/plain",
...        filename="hello.py",
...        filesize=file_stat.st_size()
...    )
>>>    await client.room_send(
...        room_id="!myfaveroom:example.org",
...        message_type="m.room.message",
...        content = {
...            "msgtype": "m.file",
...            "url": resp.content_uri,
...            "body": "descriptive title (like the filename)"
...        }
...    )
async upload_filter(user_id: str | None = None, event_fields: List[str] | None = None, event_format: EventFormat = EventFormat.client, presence: Dict[str, Any] | None = None, account_data: Dict[str, Any] | None = None, room: Dict[str, Any] | None = None) UploadFilterResponse | UploadFilterError[source]

Upload a new filter definition to the homeserver.

Returns either a UploadFilterResponse if the request was successful or a UploadFilterError if there was an error with the request.

The filter ID from the successful responses can be used for the AsyncClient.sync(), AsyncClient.sync_forever() and AsyncClient.room_messages() methods.

Parameters:
  • user_id (Optional[str]) – ID of the user uploading the filter. If not provider, the current logged in user’s ID is used.

  • event_fields (Optional[List[str]]) – List of event fields to include. If this list is absent then all fields are included. The entries may include ‘.’ characters to indicate sub-fields. A literal ‘.’ character in a field name may be escaped using a ‘’.

  • event_format (EventFormat) – The format to use for events.

  • presence (Dict[str, Any]) – The presence updates to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

  • account_data (Dict[str, Any]) – The user account data that isn’t associated with rooms to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

  • room (Dict[str, Any]) – Filters to be applied to room data. The dict corresponds to the RoomFilter type described in https://matrix.org/docs/spec/client_server/latest#id240

async whoami() WhoamiResponse | WhoamiError[source]

Get information about the logged-in user from the homeserver.

Returns either a WhoamiResponse if the request was successful or a WhoamiError if there was an error with the request.

On a successful response, the client’s state will be updated with the user_id and device_id returned, if different from the current state.

class nio.TransferMonitor(total_size: int, on_transferred: Callable[[int], None] | None = None, on_speed_changed: Callable[[float], None] | None = None, speed_period: float = 10, _update_loop_sleep_time: float = 1)[source]

Bases: object

Get statistics, pause or cancel a running upload.

A TransferMonitor object can be passed to the AsyncClient.upload() methods; the methods will then update the object’s statistics while the transfer is running.

The transfer can also be paused or cancelled using the object.

Parameters:
  • total_size (int) – Size in bytes of the data to transfer.

  • on_transferred (Callable[[int], None], optional) – A callback to call with the new value of transferred when it changes.

  • on_speed_changed (Callable[[float], None], optional) – A callback to call with the new value of average_speed when it changes.

  • speed_period (float, optional) – How many previous seconds are considered to calculate average_speed. Defaults to 10. Lower values makes average_speed more accurate, but less smooth and more susceptible to speed fluctuations.

average_speed

An average number of how many bytes are being transferred per second.

Type:

float

start_time

The date when the ``TransferMonitor` object was created.

Type:

datetime

end_time

The date when the transfer was completed, or None if it is still running.

Type:

datetime, optional

pause

Indicates to methods using this object if the transfer should be paused. False by default. At this time, servers don’t handle pausing uploads well and will end up dropping the connection after some time.

Type:

bool

cancel

When set to True, stop updating statistics and indicate to methods using this object that they should raise a TransferCancelledError.

Type:

bool

average_speed: float = 0.0
cancel: bool = False
property done: bool

Whether the transfer is finished.

end_time: datetime | None = None
on_speed_changed: Callable[[float], None] | None = None
on_transferred: Callable[[int], None] | None = None
pause: bool = False
property percent_done: float

Percentage of completion for the transfer.

property remaining: int

Number of remaining bytes to transfer.

property remaining_time: timedelta | None

Estimated remaining time to complete the transfer.

Returns None (for infinity) if the current transfer speed is 0 bytes/s, or the remaining time is so long it would cause an OverflowError.

speed_period: float = 10
property spent_time: timedelta

Time elapsed since the transfer started.

start_time: datetime
total_size: int
property transferred: int

Number of currently transferred bytes.

HttpClient

class nio.HttpClient(homeserver: str, user: str = '', device_id: str | None = '', store_path: str | None = '', config: ClientConfig | None = None)[source]

Bases: Client

accept_key_verification(transaction_id: str, tx_id: str | None = None) Tuple[UUID, bytes][source]

Accept a key verification start event.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

transaction_id (str) – An transaction id of a valid key verification process.

cancel_key_verification(transaction_id: str, tx_id: str | None = None) Tuple[UUID, bytes][source]

Abort an interactive key verification.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

transaction_id (str) – An transaction id of a valid key verification process.

confirm_short_auth_string(transaction_id: str, tx_id: str | None = None) Tuple[UUID, bytes][source]

Confirm a short auth string and mark it as matching.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

transaction_id (str) – An transaction id of a valid key verification process.

connect(transport_type: TransportType | None = TransportType.HTTP) bytes[source]
data_to_send() bytes[source]
delete_devices(devices: List[str], auth: Dict[str, str] | None = None) Tuple[UUID, bytes][source]
devices() Tuple[UUID, bytes][source]
disconnect() bytes[source]
download(server_name: str, media_id: str, filename: str | None = None, allow_remote: bool = True) Tuple[UUID, bytes][source]

Get the content of a file from the content repository.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.

  • media_id (str) – The media ID from the mxc:// URI.

  • filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.

  • allow_remote (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.

get_avatar(user_id: str | None = None) Tuple[UUID, bytes][source]

Get a user’s avatar URL.

This queries the avatar matrix content URI of a user from the server. The currently logged in user is queried if no user is specified.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

user_id (str) – User id of the user to get the avatar for.

get_displayname(user_id: str | None = None) Tuple[UUID, bytes][source]

Get a user’s display name.

This queries the display name of a user from the server. The currently logged in user is queried if no user is specified.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

user_id (str) – User id of the user to get the display name for.

get_profile(user_id: str | None = None) Tuple[UUID, bytes][source]

Get a user’s combined profile information.

This queries the display name and avatar matrix content URI of a user from the server. Additional profile information may be present. The currently logged in user is queried if no user is specified.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

user_id (str) – User id of the user to get the profile for.

handle_key_upload_error(response)[source]
join(room_id: str) Tuple[UUID, bytes][source]

Join a room.

This tells the server to join the given room. If the room is not public, the user must be invited.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

room_id – The room id or alias of the room to join.

joined_members(room_id: str) Tuple[UUID, bytes][source]
keys_claim(room_id)[source]
keys_query()[source]

Query the server for user keys.

This queries the server for device keys of users with which we share an encrypted room.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

keys_upload()[source]
property lag: float
login(password: str | None = None, device_name: str | None = '', token: str | None = None) Tuple[UUID, bytes][source]
login_info() Tuple[UUID, bytes][source]

Get the available login methods from the server

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

login_raw(auth_dict: Dict[str, Any]) Tuple[UUID, bytes][source]
logout(all_devices=False)[source]
next_response(max_events: int = 0) TransportResponse | Response | None[source]
parse_body(transport_response: TransportResponse) Dict[Any, Any][source]

Parse the body of the response.

Parameters:

transport_response (TransportResponse) – The transport response that contains the body of the response.

Returns a dictionary representing the response.

receive(data: bytes) None[source]

Pass received data to the client

request_room_key(event: MegolmEvent, tx_id: str | None = None) Tuple[UUID, bytes][source]

Request a missing room key.

This sends out a message to other devices requesting a room key from them.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

event (str) – An undecrypted MegolmEvent for which we would like to request the decryption key.

room_create(visibility: RoomVisibility = RoomVisibility.private, alias: str | None = None, name: str | None = None, topic: str | None = None, room_version: str | None = None, room_type: str | None = None, federate: bool = True, is_direct: bool = False, preset: RoomPreset | None = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Dict[str, Any] | None = None) Tuple[UUID, bytes][source]

Create a new room.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to RoomVisibility.private.

  • alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.

  • name (str, optional) – A name to set for the room.

  • topic (str, optional) – A topic to set for the room.

  • room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400 M_UNSUPPORTED_ROOM_VERSION error will be returned.

  • room_type (str, optional) –

    The room type to set. If not specified, the homeserver will use its default setting. In spec v1.2 the following room types are specified:

    • m.space

    Unspecified room types are permitted through the use of Namespaced Identifiers.

  • federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to True. Cannot be changed later.

  • is_direct (bool) – If this should be considered a direct messaging room. If True, the server will set the is_direct flag on m.room.member events sent to the users in invite. Defaults to False.

  • preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the visibility: RoomVisibility.public equates to RoomPreset.public_chat, and RoomVisibility.private equates to a RoomPreset.private_chat.

  • invite (list) – A list of user id to invite to the room.

  • initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediately by having a m.room.encryption event dict.

  • power_level_override (dict) – A m.room.power_levels content dict to override the default. The dict will be applied on top of the generated m.room.power_levels event before it is sent to the room.

room_forget(room_id: str) Tuple[UUID, bytes][source]

Forget a room.

This tells the server to forget the given room’s history for our user. If all users on a homeserver forget the room, the room will be eligible for deletion from that homeserver.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

room_id (str) – The room id of the room to forget.

room_invite(room_id, user_id)[source]
room_kick(room_id, user_id, reason=None)[source]
room_leave(room_id: str) Tuple[UUID, bytes][source]

Leave a room or reject an invite.

This tells the server to leave the given room. If the user was only invited, the invite is rejected.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

room_id – The room id of the room to leave.

room_messages(room_id, start, end=None, direction=MessageDirection.back, limit=10)[source]
room_put_state(room_id, event_type, body)[source]
room_read_markers(room_id: str, fully_read_event: str, read_event: str | None = None) Tuple[UUID, bytes][source]

Update the fully read marker (and optionally the read receipt) for a room.

Calls receive_response() to update the client state if necessary.

Returns either a RoomReadMarkersResponse if the request was successful or a RoomReadMarkersError if there was an error with the request.

This sets the position of the read markers.

  • fully_read_event is the latest event in the set of events that the user has either fully read or indicated they aren’t interested in. It permits the implementation of a “jump to first unread message” kind of feature. It is _private_ (not exposed to other room participants).

  • read_event is the most recent message the user has read and is also known as a _read receipt_. A read receipt being set on an event does not imply that all previous events have been seen. This happens in cases such as when a user comes back to a room after hundreds of messages have been sent and _only_ reads the most recent message. The read receipt is _public_ (exposed to other room participants).

If you want to set the read receipt, you _must_ set read_event.

Parameters:
  • room_id (str) – The room ID of the room where the read markers should be updated.

  • fully_read_event (str) – The event ID that the user has fully read up to.

  • read_event (Optional[str]) – The event ID to set the read receipt location at.

room_redact(room_id, event_id, reason=None, tx_id=None)[source]

Strip information out of an event.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • room_id (str) – The room id of the room that contains the event that will be redacted.

  • event_id (str) – The ID of the event that will be redacted.

  • tx_id (str/UUID, optional) – A transaction ID for this event.

  • reason (str, optional) – A description explaining why the event was redacted.

room_send(room_id, message_type, content, tx_id=None)[source]
room_typing(room_id: str, typing_state: bool = True, timeout: int = 30000) Tuple[UUID, bytes][source]

Send a typing notice to the server.

This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • room_id (str) – Room id of the room where the user is typing.

  • typing_state (bool) – A flag representing whether the user started or stopped typing

  • timeout (int) – For how long should the new typing notice be valid for in milliseconds.

set_avatar(avatar_url: str) Tuple[UUID, bytes][source]

Set the user’s avatar URL.

This tells the server to set avatar of the currently logged in user to supplied matrix content URI.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

avatar_url (str) – matrix content URI of the avatar to set.

set_displayname(displayname: str) Tuple[UUID, bytes][source]

Set the user’s display name.

This tells the server to set the display name of the currently logged in user to supplied string.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

displayname (str) – Display name to set.

share_group_session(room_id: str, ignore_missing_sessions: bool = False, tx_id: str | None = None, ignore_unverified_devices: bool = False) Tuple[UUID, bytes][source]

Share a group session with a room.

This method sends a group session to members of a room.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.

  • tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.

  • ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists or the room isn’t an encrypted room.

start_key_verification(device: OlmDevice, tx_id: str | None = None) Tuple[UUID, bytes][source]

Start a interactive key verification with the given device.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:

device (OlmDevice) – An device with which we would like to start the interactive key verification process.

sync(timeout: int | None = None, filter: Dict[Any, Any] | None = None, full_state: bool = False) Tuple[UUID, bytes][source]
thumbnail(server_name: str, media_id: str, width: int, height: int, method=ResizingMethod.scale, allow_remote: bool = True) Tuple[UUID, bytes][source]

Get the thumbnail of a file from the content repository.

Note: The actual thumbnail may be larger than the size specified.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.

  • media_id (str) – The media ID from the mxc:// URI.

  • width (int) – The desired width of the thumbnail.

  • height (int) – The desired height of the thumbnail.

  • method (ResizingMethod) – The desired resizing method.

  • allow_remote (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.

to_device(message: ToDeviceMessage, tx_id: str | None = None) Tuple[UUID, bytes][source]

Send a message to a specific device.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • message (ToDeviceMessage) – The message that should be sent out.

  • tx_id (str, optional) – The transaction ID for this message. Should be unique.

update_device(device_id: str, content: Dict[str, str]) Tuple[UUID, bytes][source]

Rooms

class nio.rooms.MatrixInvitedRoom(room_id: str, own_user_id: str)[source]

Bases: MatrixRoom

handle_event(event: Event) None[source]
handle_membership(event: RoomMemberEvent | InviteMemberEvent) bool[source]

Handle a membership event for the invited room.

Parameters:

event (RoomMemberEvent) – The event that should be handled that updates the room state.

Returns True if the member list of the room has changed False otherwise.

class nio.rooms.MatrixRoom(room_id: str, own_user_id: str, encrypted: bool = False)[source]

Bases: object

Represents a Matrix room.

add_member(user_id: str, display_name: str | None, avatar_url: str | None, invited: bool = False) bool[source]
avatar_url(user_id: str) str | None[source]

Get avatar url for a user.

Returns a matrix content URI, or None if the user has no avatar.

property display_name: str

Calculate display name for a room.

Prefer returning the room name if it exists, falling back to a group-style name if not.

Follows: https://matrix.org/docs/spec/client_server/r0.6.0#id342

property gen_avatar_url: str | None

Get the calculated room’s avatar url.

Either the room’s avatar if one is set, or the avatar of the first user that’s not ourselves if the room is an unnamed group or has exactly two users.

group_name() str[source]

Return the group-style name of the room.

In other words, a display name based on the names of room members. This is used for ad-hoc groups of people (usually direct chats).

group_name_structure() Tuple[bool, List[str], int][source]

Get if room is empty, ID for listed users and the N others count.

handle_account_data(event: AccountDataEvent) None[source]
handle_ephemeral_event(event: EphemeralEvent) None[source]
handle_event(event: Event) None[source]
handle_membership(event: RoomMemberEvent | InviteMemberEvent) bool[source]

Handle a membership event for the room.

Parameters:

event (RoomMemberEvent) – The event that should be handled that updates the room state.

Returns True if the member list of the room has changed False otherwise.

property invited_count: int
property is_group: bool

Determine whether a room is an ad-hoc group (often a direct chat).

A group is an unnamed room with no canonical alias.

property is_named: bool

Determine whether a room is named.

A named room is a room with either the name or a canonical alias set.

property joined_count: int
property machine_name: str

Calculate an unambiguous, unique machine name for a room.

Either use the more human-friendly canonical alias, if it exists, or the internal room ID if not.

property member_count: int
named_room_name() str | None[source]

Return the name of the room if it’s a named room, otherwise None.

remove_member(user_id: str) bool[source]
update_summary(summary: RoomSummary) None[source]
update_unread_notifications(unread: UnreadNotifications) None[source]
user_name(user_id: str) str | None[source]

Get disambiguated display name for a user.

Returns display name of a user if display name is unique or returns a display name in form “<display name> (<matrix id>)” if there is more than one user with same display name.

user_name_clashes(name: str) List[str][source]

Get a list of users that have same display name.

class nio.rooms.MatrixUser(user_id: str, display_name: str | None = None, avatar_url: str | None = None, power_level: int = 0, invited: bool = False, presence: str = 'offline', last_active_ago: int | None = None, currently_active: bool | None = None, status_msg: str | None = None)[source]

Bases: object

property disambiguated_name: str
property name: str

Events

Nio Events Module.

The model of conversation history exposed by a Matrix server can be considered as a list of events. The server ‘linearises’ the eventually-consistent event graph of events into an ‘event stream’ at any given point in time:

Nio contains clases for most known Matrix Event types.

class nio.events.misc.BadEvent(source: Dict[str, Any], event_id: str, sender: str, server_timestamp: int, type: str)[source]

Bases: object

An event that failed event schema and type validation.

This type of event will be created if the event has a valid core structure but failed validation for the given event type.

The event can still be inspected with the source attribute.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:

dict

event_id

A globally unique event identifier.

Type:

str

sender

The fully-qualified ID of the user who sent this event.

Type:

str

server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:

int

type

The claimed type of the event.

Type:

str

decrypted

A flag signaling if the event was decrypted.

Type:

bool

verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:

bool

sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:

str, optional

session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:

str, optional

transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:

str, optional

class nio.events.misc.UnknownBadEvent(source: Dict[str, Any], transaction_id: str | None = None)[source]

Bases: object

An event that doesn’t have the minimal necessary structure.

This type of event will be created if we can’t find the event_id, sender, origin server timestamp or event type.

The event can still be inspected with the source attribute.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:

dict

decrypted

A flag signaling if the event was decrypted.

Type:

bool

verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:

bool

sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:

str, optional

session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:

str, optional

transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:

str, optional

Room Events

class nio.events.room_events.CallAnswerEvent(source: Dict[str, Any], call_id: str, version: int, answer: Dict[str, Any])[source]

Bases: CallEvent

Event representing the answer to a VoIP call.

This event is sent by the callee when they wish to answer the call.

answer

The session description object. A dictionary containing the keys “type” which must be “answer” for this event and “sdp” which contains the SDP text of the session description.

Type:

dict

answer: Dict[str, Any]
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.CallCandidatesEvent(source: Dict[str, Any], call_id: str, version: int, candidates: List[Dict[str, Any]])[source]

Bases: CallEvent

Call event holding additional VoIP ICE candidates.

This event is sent by callers after sending an invite and by the callee after answering. Its purpose is to give the other party additional ICE candidates to try using to communicate.

Parameters:

candidates (list) – A list of dictionaries describing the candidates.

candidates: List[Dict[str, Any]]
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.CallEvent(source: Dict[str, Any], call_id: str, version: int)[source]

Bases: Event

Base Class for Matrix call signalling events.

call_id

The unique identifier of the call.

Type:

str

version

The version of the VoIP specification this message adheres to.

Type:

int

call_id: str
static parse_event(event_dict)[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level CallEvent object representing the parsed event.

The event structure is checked for correctness and the event fields are type checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:

event_dict (dict) – The raw matrix event dictionary.

version: int
class nio.events.room_events.CallHangupEvent(source: Dict[str, Any], call_id: str, version: int)[source]

Bases: CallEvent

An event representing the end of a VoIP call.

Sent by either party to signal their termination of the call. This can be sent either once the call has has been established or before to abort the call.

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.CallInviteEvent(source: Dict[str, Any], call_id: str, version: int, lifetime: int, offer: Dict[str, Any])[source]

Bases: CallEvent

Event representing an invitation to a VoIP call.

This event is sent by a caller when they wish to establish a call.

lifetime

The time in milliseconds that the invite is valid for.

Type:

integer

offer

The session description object. A dictionary containing the keys “type” which must be “offer” for this event and “sdp” which contains the SDP text of the session description.

Type:

dict

property expired

Property marking if the invite event expired.

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

lifetime: int
offer: Dict[str, Any]
class nio.events.room_events.DefaultLevels(ban: int = 50, invite: int = 50, kick: int = 50, redact: int = 50, state_default: int = 0, events_default: int = 0, users_default: int = 0, notifications: ~typing.Dict[str, int] = <factory>)[source]

Bases: object

Class holding information about default power levels of a room.

ban

The level required to ban a user.

Type:

int

invite

The level required to invite a user.

Type:

int

kick

The level required to kick a user.

Type:

int

redact

The level required to redact events.

Type:

int

state_default

The level required to send state events. This can be overridden by the events power level mapping.

Type:

int

events_default

The level required to send message events. This can be overridden by the events power level mapping.

Type:

int

users_default

The default power level for every user in the room. This can be overridden by the users power level mapping.

Type:

int

notifications

The level required to send different kinds of notifications. Used for sender_notification_permission conditions in push rules.

Type:

Dict[str, int]

ban: int = 50
events_default: int = 0
classmethod from_dict(parsed_dict)[source]

Create a DefaultLevels object from a dictionary.

This creates the DefaultLevels object from a dictionary containing a m.room.power_levels event. The event structure isn’t checked in this method.

This shouldn’t be used directly, the PowerLevelsEvent method will call this method to construct the DefaultLevels object.

invite: int = 50
kick: int = 50
notifications: Dict[str, int]
redact: int = 50
state_default: int = 0
users_default: int = 0
class nio.events.room_events.Event(source: Dict[str, Any])[source]

Bases: object

Matrix Event class.

This is the base event class, most events inherit from this class.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:

dict

event_id

A globally unique event identifier.

Type:

str

sender

The fully-qualified ID of the user who sent this event.

Type:

str

server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:

int

decrypted

A flag signaling if the event was decrypted.

Type:

bool

verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:

bool

sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:

str, optional

session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:

str, optional

transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:

str, optional

decrypted: bool = False
event_id: str
flattened(_prefix: str = '', _source: Dict[str, Any] | None = None, _flat: Dict[str, Any] | None = None) Dict[str, Any][source]

Return a flattened version of the source dict with dotted keys.

Example

>>> event.source
{"content": {"body": "foo"}, "m.test": {"key": "bar"}}
>>> event.source.flattened()
{"content.body": "foo", "m.test.key": "bar"}
classmethod from_dict(parsed_dict: Dict[Any, Any]) Event | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

classmethod parse_decrypted_event(event_dict: Dict[Any, Any]) Event | BadEvent | UnknownBadEvent[source]

Parse a decrypted event and create a higher level event object.

Parameters:

event_dict (dict) – The dictionary representation of the event.

classmethod parse_encrypted_event(event_dict)[source]

Parse an encrypted event.

Encrypted events may have different fields depending on the algorithm that was used to encrypt them.

This function checks the algorithm of the event and produces a higher level event from the provided dictionary.

Parameters:

event_dict (dict) – The dictionary representation of the encrypted event.

Returns None if the algorithm of the event is unknown.

classmethod parse_event(event_dict: Dict[Any, Any]) Event | BadEvent | UnknownBadEvent[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:

event_dict (dict) – The dictionary representation of the event.

sender: str
sender_key: str | None = None
server_timestamp: int
session_id: str | None = None
source: Dict[str, Any]
transaction_id: str | None = None
verified: bool = False
class nio.events.room_events.MegolmEvent(source: Dict[str, Any], device_id: str, ciphertext: str, algorithm: str, room_id: str = '')[source]

Bases: Event

An undecrypted Megolm event.

MegolmEvents are presented to library users only if the library fails to decrypt the event because of a missing session key.

MegolmEvents can be stored for later use. If a RoomKeyEvent is later on received with a session id that matches the session_id of this event decryption can be retried.

event_id

A globally unique event identifier.

Type:

str

sender

The fully-qualified ID of the user who sent this event.

Type:

str

server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:

int

sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:

str

device_id

The unique identifier of the device that was used to encrypt the event.

Type:

str

session_id

The unique identifier of the session that was used to encrypt the message.

Type:

str

ciphertext

The undecrypted ciphertext of the event.

Type:

str

algorithm

The encryption algorithm that was used to encrypt the message.

Type:

str

room_id

The unique identifier of the room in which the message was sent.

Type:

str

transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:

str, optional

algorithm: str
as_key_request(user_id: str, requesting_device_id: str, request_id: str | None = None, device_id: str | None = None) RoomKeyRequestMessage[source]

Make a to-device message for a room key request.

MegolmEvents are presented to library users only if the library fails to decrypt the event because of a missing session key.

A missing key can be requested later on by sending a key request, this method creates a ToDeviceMessage that can be sent out if such a request should be made.

Parameters:
  • user_id (str) – The user id of the user that should receive the key request.

  • requesting_device_id (str) – The device id of the user that is requesting the key.

  • request_id (str, optional) – A unique string identifying the request. Defaults to the session id of the missing megolm session.

  • device_id (str, optional) – The device id of the device that should receive the request. Defaults to all the users devices.

ciphertext: str
device_id: str
classmethod from_dict(event_dict)[source]

Create a MegolmEvent from a dictionary.

Parameters:

event_dict (Dict) – Dictionary containing the event.

Returns a MegolmEvent if the event_dict contains a valid event or a BadEvent if it’s invalid.

room_id: str = ''
class nio.events.room_events.PowerLevels(defaults: ~nio.events.room_events.DefaultLevels = <factory>, users: ~typing.Dict[str, int] = <factory>, events: ~typing.Dict[str, int] = <factory>)[source]

Bases: object

Class holding information of room power levels.

defaults

The default power levels of the room.

Type:

DefaultLevels

users

The power levels for specific users. This is a mapping from user_id to power level for that user.

Type:

dict

events

The level required to send specific event types. This is a mapping from event type to power level required.

Type:

dict

can_user_ban(user_id: str, target_user_id: str | None = None) bool[source]

Return whether a user has enough power to ban another.

If target_user_id is None, returns whether user_id has enough power to ban anyone with a lower power level than that user.

can_user_invite(user_id: str) bool[source]

Return whether a user has enough power to invite others.

can_user_kick(user_id: str, target_user_id: str | None = None) bool[source]

Return whether a user has enough power to kick another.

If target_user_id is None, returns whether user_id has enough power to kick anyone with a lower power level than that user.

can_user_notify(user_id: str, notification_type: str)[source]

Return whether user has enough power to send a type of notification.

can_user_redact(user_id: str)[source]

Return whether a user has enough power to redact other user’s events.

can_user_send_message(user_id: str, event_type: str = 'm.room.message') bool[source]

Return whether a user has enough power to send certain message events.

Parameters:
  • user_id (str) – The user to check the power of.

  • event_type (str) – The type of matrix message event to check the required power of, m.room.message by default.

can_user_send_state(user_id: str, event_type: str) bool[source]

Return whether a user has enough power to send certain state events.

Parameters:
  • user_id (str) – The user to check the power of.

  • event_type (str) – The type of matrix state event to check the required power of, e.g. m.room.encryption.

defaults: DefaultLevels
events: Dict[str, int]
get_message_event_required_level(event_type: str) int[source]

Get required power level to send a certain type of message event.

Returns an integer representing the required power level.

Parameters:

event_type (str) – The type of matrix message event we want the required level for, e.g. m.room.message.

get_notification_required_level(notification_type: str) int[source]

Get required power level to send a certain type of notification.

Returns an integer representing the required power level.

Parameters:

notification_type (str) – The type of notification to get the required level for, e.g. "room".

get_state_event_required_level(event_type: str) int[source]

Get required power level to send a certain type of state event.

Returns an integer representing the required power level.

Parameters:

event_type (str) – The type of matrix state event we want the required level for, e.g. m.room.name or m.room.topic.

get_user_level(user_id: str) int[source]

Get the power level of a user.

Returns an integer representing the user’s power level.

Parameters:

user_id (str) – The fully-qualified ID of the user for whom we would like to get the power level.

update(new_levels)[source]

Update the power levels object with new levels.

Parameters:

new_levels (PowerLevels) – A new PowerLevels object that we received from a newer PowerLevelsEvent.

users: Dict[str, int]
class nio.events.room_events.PowerLevelsEvent(source: Dict[str, Any], power_levels: PowerLevels)[source]

Bases: Event

Class representing a m.room.power_levels event.

This event specifies the minimum level a user must have in order to perform a certain action. It also specifies the levels of each user in the room.

power_levels

The PowerLevels object holding information of the power levels of the room.

Type:

PowerLevels

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

power_levels: PowerLevels
class nio.events.room_events.ReactionEvent(source: Dict[str, Any], reacts_to: str, key: str)[source]

Bases: Event

An event representing an m.reaction event.

Users sometimes wish to respond to a message using emojis. When such responses are grouped visually below the message being reacted to, this provides a (visually) lightweight way for users to react to messages.

reacts_to

The event_id of the message the reaction relates to.

Type:

str

key

The actual reaction/emoji.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

key: str
reacts_to: str
class nio.events.room_events.RedactedEvent(source: Dict[str, Any], type: str, redacter: str, reason: str | None)[source]

Bases: Event

An event that has been redacted.

type

The type of the event that has been redacted.

Type:

str

redacter

The fully-qualified ID of the user who redacted the event.

Type:

str

reason

A string describing why the event was redacted, can be None.

Type:

str, optional

property event_type

Type of the event.

classmethod from_dict(parsed_dict: Dict[Any, Any]) RedactedEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

reason: str | None
redacter: str
type: str
class nio.events.room_events.RedactionEvent(source: Dict[str, Any], redacts: str, reason: str | None = None)[source]

Bases: Event

An event signaling that another event has been redacted.

Events can be redacted by either room or server administrators. Redacting an event means that all keys not required by the protocol are stripped off.

redacts

The event id of the event that has been redacted.

Type:

str

reason

A string describing why the event was redacted, can be None.

Type:

str, optional

classmethod from_dict(parsed_dict: Dict[Any, Any]) RedactionEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

reason: str | None = None
redacts: str
class nio.events.room_events.RoomAliasEvent(source: Dict[str, Any], canonical_alias: str | None)[source]

Bases: Event

An event informing us about which alias should be preferred.

canonical_alias

The alias that is considered canonical.

Type:

str

canonical_alias: str | None
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomAliasEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.RoomAvatarEvent(source: Dict[str, Any], avatar_url: str | None)[source]

Bases: Event

Event holding a picture that is associated with the room.

avatar_url

The URL to the picture.

Type:

str

avatar_url: str | None
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomAvatarEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.RoomCreateEvent(source: Dict[str, Any], creator: str, federate: bool = True, room_version: str = '1', room_type: str = '')[source]

Bases: Event

The first event in a room, signaling that the room was created.

creator

The fully-qualified ID of the user who created the room.

Type:

str

federate

A boolean flag telling us whether users on other homeservers are able to join this room.

Type:

bool

room_version

The version of the room. Different room versions will have different event formats. Clients shouldn’t worry about this too much unless they want to perform room upgrades.

Type:

str

room_type

The type of the room. In spec v1.2 the following room types are specified:

  • m.space

Unspecified room types are permitted through the use of Namespaced Identifiers.

Type:

str

creator: str
federate: bool = True
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomCreateEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

room_type: str = ''
room_version: str = '1'
class nio.events.room_events.RoomEncryptedAudio(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, mimetype: str, thumbnail_url: str | None = None, thumbnail_key: Dict | None = None, thumbnail_hashes: Dict | None = None, thumbnail_iv: str | None = None)[source]

Bases: RoomEncryptedMedia

A room message containing an audio clip where the file is encrypted.

class nio.events.room_events.RoomEncryptedFile(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, mimetype: str, thumbnail_url: str | None = None, thumbnail_key: Dict | None = None, thumbnail_hashes: Dict | None = None, thumbnail_iv: str | None = None)[source]

Bases: RoomEncryptedMedia

A room message containing a generic encrypted file.

class nio.events.room_events.RoomEncryptedImage(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, mimetype: str, thumbnail_url: str | None = None, thumbnail_key: Dict | None = None, thumbnail_hashes: Dict | None = None, thumbnail_iv: str | None = None)[source]

Bases: RoomEncryptedMedia

A room message containing an image where the file is encrypted.

class nio.events.room_events.RoomEncryptedMedia(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, mimetype: str, thumbnail_url: str | None = None, thumbnail_key: Dict | None = None, thumbnail_hashes: Dict | None = None, thumbnail_iv: str | None = None)[source]

Bases: RoomMessage

Base class for encrypted room messages containing an URI.

url

The URL of the file.

Type:

str

body

The description of the message.

Type:

str

key

The key that can be used to decrypt the file.

Type:

dict

hashes

A mapping from an algorithm name to a hash of the ciphertext encoded as base64.

Type:

dict

iv

The initialisation vector that was used to encrypt the file.

Type:

str

mimetype

The mimetype of the message.

Type:

str, optional

thumbnail_url

The URL of the thumbnail file.

Type:

str, optional

thumbnail_key

The key that can be used to decrypt the thumbnail file.

Type:

dict, optional

thumbnail_hashes

A mapping from an algorithm name to a hash of the thumbnail ciphertext encoded as base64.

Type:

dict, optional

thumbnail_iv

The initialisation vector that was used to encrypt the thumbnail file.

Type:

str, optional

body: str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

hashes: Dict[str, Any]
iv: str
key: Dict[str, Any]
mimetype: str
thumbnail_hashes: Dict | None = None
thumbnail_iv: str | None = None
thumbnail_key: Dict | None = None
thumbnail_url: str | None = None
url: str
class nio.events.room_events.RoomEncryptedVideo(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, mimetype: str, thumbnail_url: str | None = None, thumbnail_key: Dict | None = None, thumbnail_hashes: Dict | None = None, thumbnail_iv: str | None = None)[source]

Bases: RoomEncryptedMedia

A room message containing a video clip where the file is encrypted.

class nio.events.room_events.RoomEncryptionEvent(source: Dict[str, Any])[source]

Bases: Event

An event signaling that encryption has been enabled in a room.

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.RoomGuestAccessEvent(source: Dict[str, Any], guest_access: str = 'forbidden')[source]

Bases: Event

Event signaling whether guest users are allowed to join rooms.

guest_access

A string describing the guest access policy of the room. Can be one of “can_join” or “forbidden”.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomGuestAccessEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

guest_access: str = 'forbidden'
class nio.events.room_events.RoomHistoryVisibilityEvent(source: Dict[str, Any], history_visibility: str = 'shared')[source]

Bases: Event

An event telling whether users can read the room history.

Room history visibility can be set up in multiple ways in Matrix:

  • world_readable

    All events value may be shared by any participating homeserver with anyone, regardless of whether they have ever joined the room.

  • shared

    Previous events are always accessible to newly joined members. All events in the room are accessible, even those sent when the member was not a part of the room.

  • invited

    Events are accessible to newly joined members from the point they were invited onwards. Events stop being accessible when the member’s state changes to something other than invite or join.

  • joined

    Events are only accessible to members from the point on they joined to the room and stop being accessible when they aren’t joined anymore.

history_visibility

A string describing who can read the room history. One of “invited”, “joined”, “shared”, “world_readable”.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomHistoryVisibilityEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

history_visibility: str = 'shared'
class nio.events.room_events.RoomJoinRulesEvent(source: Dict[str, Any], join_rule: str = 'invite')[source]

Bases: Event

An event telling us how users can join the room.

join_rule

A string telling us how users may join the room, can be one of “public” meaning anyone can join the room without any restrictions or “invite” meaning users can only join if they have been previously invited.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomJoinRulesEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

join_rule: str = 'invite'
class nio.events.room_events.RoomMemberEvent(source: Dict[str, Any], state_key: str, membership: str, prev_membership: str | None, content: Dict[str, Any], prev_content: Dict[str, Any] | None = None)[source]

Bases: Event

Class representing to an m.room.member event.

state_key

The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.

Type:

str

membership

The membership state of the user. One of “invite”, “join”, “leave”, “ban”, “knock”.

Type:

str

prev_membership

The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.

Type:

str, optional

content

The content of the of the membership event.

Type:

dict

prev_content

The content of a previous membership event that this one is overwriting.

Type:

dict, optional

content: Dict[str, Any]
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomMemberEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

membership: str
prev_content: Dict[str, Any] | None = None
prev_membership: str | None
state_key: str
class nio.events.room_events.RoomMessage(source: Dict[str, Any])[source]

Bases: Event

Abstract room message class.

This class corespondents to a Matrix event of the m.room.message type. It is used when messages are sent to the room.

The class has one child class per msgtype.

classmethod parse_decrypted_event(parsed_dict: Dict[Any, Any]) RoomMessage | BadEvent | UnknownBadEvent[source]

Parse a decrypted event and create a higher level event object.

Parameters:

event_dict (dict) – The dictionary representation of the event.

classmethod parse_event(parsed_dict: Dict[Any, Any]) RoomMessage | BadEvent | UnknownBadEvent[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:

event_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.RoomMessageAudio(source: Dict[str, Any], url: str, body: str)[source]

Bases: RoomMessageMedia

A room message containing an audio clip.

class nio.events.room_events.RoomMessageEmote(source: Dict[str, Any], body: str, formatted_body: str | None, format: str | None)[source]

Bases: RoomMessageFormatted

A room message corresponding to the m.emote msgtype.

This message is similar to m.text except that the sender is ‘performing’ the action contained in the body key, similar to /me in IRC.

body

The textual body of the message.

Type:

str

formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:

str, optional

format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:

str, optional

class nio.events.room_events.RoomMessageFile(source: Dict[str, Any], url: str, body: str)[source]

Bases: RoomMessageMedia

A room message containing a generic file.

class nio.events.room_events.RoomMessageFormatted(source: Dict[str, Any], body: str, formatted_body: str | None, format: str | None)[source]

Bases: RoomMessage

Base abstract class for room messages that can have formatted bodies.

body

The textual body of the message.

Type:

str

formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:

str, optional

format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:

str, optional

body: str
format: str | None
formatted_body: str | None
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomMessage | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.room_events.RoomMessageImage(source: Dict[str, Any], url: str, body: str)[source]

Bases: RoomMessageMedia

A room message containing an image.

class nio.events.room_events.RoomMessageMedia(source: Dict[str, Any], url: str, body: str)[source]

Bases: RoomMessage

Base class for room messages containing a URI.

url

The URL of the file.

Type:

str

body

The description of the message.

Type:

str

body: str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

url: str
class nio.events.room_events.RoomMessageNotice(source: Dict[str, Any], body: str, formatted_body: str | None, format: str | None)[source]

Bases: RoomMessageFormatted

A room message corresponding to the m.notice msgtype.

Room notices are primarily intended for responses from automated clients.

body

The textual body of the notice.

Type:

str

formatted_body

The formatted version of the notice body. Can be None if the message doesn’t contain a formatted version of the body.

Type:

str, optional

format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:

str, optional

class nio.events.room_events.RoomMessageText(source: Dict[str, Any], body: str, formatted_body: str | None, format: str | None)[source]

Bases: RoomMessageFormatted

A room message corresponding to the m.text msgtype.

This message is the most basic message and is used to represent text.

body

The textual body of the message.

Type:

str

formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:

str, optional

format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:

str, optional

class nio.events.room_events.RoomMessageUnknown(source: Dict[str, Any], msgtype: str, content: Dict[str, Any])[source]

Bases: RoomMessage

A m.room.message which we do not understand.

This event is created every time nio tries to parse a room message of an unknown msgtype. Since custom and extensible events are a feature of Matrix this allows clients to use custom messages but care should be taken that the clients will be responsible to validate and type check the content of the message.

msgtype

The msgtype of the room message.

Type:

str

content

The dictionary holding the content of the room message. The keys and values of this dictionary will differ depending on the msgtype.

Type:

dict

content: Dict[str, Any]
classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomMessage[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

msgtype: str
property type

Get the msgtype of the room message.

class nio.events.room_events.RoomMessageVideo(source: Dict[str, Any], url: str, body: str)[source]

Bases: RoomMessageMedia

A room message containing a video clip.

class nio.events.room_events.RoomNameEvent(source: Dict[str, Any], name: str)[source]

Bases: Event

Event holding the name of the room.

The room name is a human-friendly string designed to be displayed to the end-user. The room name is not unique, as multiple rooms can have the same room name set.

name

The name of the room.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomNameEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

name: str
class nio.events.room_events.RoomSpaceChildEvent(source: Dict[str, Any], state_key: str, suggested: bool = False)[source]

Bases: Event

Event holding the child rooms of a space.

state_key

The child room of a space

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

state_key: str
suggested: bool = False
class nio.events.room_events.RoomSpaceParentEvent(source: Dict[str, Any], state_key: str, canonical: bool = False)[source]

Bases: Event

Event holding the parent space of a room.

state_key

The parent space’s room

Type:

str

canonical: bool = False
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

state_key: str
class nio.events.room_events.RoomTopicEvent(source: Dict[str, Any], topic: str)[source]

Bases: Event

Event holding the topic of a room.

A topic is a short message detailing what is currently being discussed in the room. It can also be used as a way to display extra information about the room, which may not be suitable for the room name.

topic

The topic of the room.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomTopicEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

topic: str
class nio.events.room_events.RoomUpgradeEvent(source: Dict[str, Any], body: str, replacement_room: str)[source]

Bases: Event

Class representing to an m.room.tombstone event.

A state event signifying that a room has been upgraded to a different room version, and that clients should go there.

body

A server-defined message.

Type:

str

replacement_room

The new room the client should be visiting.

Type:

str

body: str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

replacement_room: str
class nio.events.room_events.StickerEvent(source: Dict[str, Any], body: str, url: str, content: Dict[str, Any])[source]

Bases: Event

An event indicating the use of a sticker

Sticker messages are specialised image messages that are displayed without controls. Sticker messages are intended to provide simple “reaction” events in the message timeline.

body

A textual representation or associated description of

Type:

str

the sticker image. This could be the alt text of the original image,
or a message to accompany and further describe the sticker.
url

The URL to the sticker image.

Type:

str

content

The content of the of the redaction event.

Type:

dict

body: str
content: Dict[str, Any]
classmethod from_dict(parsed_dict: Dict[Any, Any]) StickerEvent | BadEvent | UnknownBadEvent[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

url: str
class nio.events.room_events.UnknownEncryptedEvent(source: Dict[str, Any], type: str, algorithm: str)[source]

Bases: Event

An encrypted event which we don’t know how to decrypt.

This event is created every time nio tries to parse an event encrypted event that was encrypted using an unknown algorithm.

type

The type of the event.

Type:

str

algorithm

The algorithm of the event.

Type:

str

algorithm: str
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

type: str
class nio.events.room_events.UnknownEvent(source: Dict[str, Any], type: str)[source]

Bases: Event

An Event which we do not understand.

This event is created every time nio tries to parse an event of an unknown type. Since custom and extensible events are a feature of Matrix this allows clients to use custom events but care should be taken that the clients will be responsible to validate and type check the event.

type

The type of the event.

Type:

str

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

type: str

Invite Room Events

Matrix Invite Events.

Events for invited rooms will have a stripped down version of their counterparts for joined rooms.

Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.

These events help set up the state of an invited room so more information can be displayed to users if they are invited to a room.

class nio.events.invite_events.InviteAliasEvent(source: Dict, sender: str, canonical_alias: str)[source]

Bases: InviteEvent

An event informing us about which alias should be preferred.

This is the RoomAliasEvent equivalent for invited rooms.

canonical_alias

The alias that is considered canonical.

Type:

str

canonical_alias: str
classmethod from_dict(parsed_dict: Dict[Any, Any]) InviteAliasEvent | BadEvent | UnknownBadEvent[source]

Create an InviteEvent from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.invite_events.InviteEvent(source: Dict, sender: str)[source]

Bases: object

Matrix Event class for events in invited rooms.

Events for invited rooms will have a stripped down version of their counterparts for joined rooms.

Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:

dict

sender

The fully-qualified ID of the user who sent this event.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

classmethod parse_event(event_dict: Dict[Any, Any]) InviteEvent | BadEvent | UnknownBadEvent | None[source]

Parse a Matrix invite event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

Parameters:

event_dict (dict) – The dictionary representation of the event.

sender: str
source: Dict
class nio.events.invite_events.InviteMemberEvent(source: ~typing.Dict, sender: str, state_key: str, membership: str, prev_membership: str, content: dict, prev_content: dict = <factory>)[source]

Bases: InviteEvent

Class representing to an m.room.member event in an invited room.

state_key

The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.

Type:

str

membership

The membership state of the user. One of “invite”, “join”, “leave”, “ban”.

Type:

str

prev_membership

The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.

Type:

str, optional

content

The content of the of the membership event.

Type:

dict

prev_content

The content of a previous membership event that this one is overwriting.

Type:

dict, optional

content: dict
classmethod from_dict(parsed_dict: Dict[Any, Any]) InviteMemberEvent | BadEvent | UnknownBadEvent[source]

Create an InviteEvent from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

membership: str
prev_content: dict
prev_membership: str
state_key: str
class nio.events.invite_events.InviteNameEvent(source: Dict, sender: str, name: str)[source]

Bases: InviteEvent

Event holding the name of the invited room.

This is the RoomNameEvent equivalent for invited rooms.

The room name is a human-friendly string designed to be displayed to the end-user. The room name is not unique, as multiple rooms can have the same room name set.

name

The name of the room.

Type:

str

classmethod from_dict(parsed_dict: Dict[Any, Any]) InviteNameEvent | BadEvent | UnknownBadEvent[source]

Create an InviteEvent from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

name: str

To-device Events

nio to-device events.

To-device events are events that are sent directly between two devices instead of normally sending events in a room.

To-device events can be sent to a specific device of a user or to all devices of a user.

class nio.events.to_device.BaseRoomKeyRequest(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str)[source]

Bases: ToDeviceEvent

Base class for room key requests. requesting_device_id (str): The id of the device that is requesting the

key.

request_id (str): A unique identifier for the request.

classmethod parse_event(event_dict)[source]

Parse a to-device event and create a higher level event object.

This function parses the type of the to-device event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

Parameters:

event_dict (dict) – The dictionary representation of the event.

request_id: str
requesting_device_id: str
class nio.events.to_device.DummyEvent(source: Dict[str, Any], sender: str, sender_key: str, sender_device: str)[source]

Bases: ToDeviceEvent

Event containing a dummy message.

This event type is used start a new Olm session with a device. The event has no content.

sender

The sender of the event.

Type:

str

sender_key

The key of the sender that sent the event.

Type:

str

classmethod from_dict(event_dict, sender, sender_key)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

sender_device: str
sender_key: str
class nio.events.to_device.EncryptedToDeviceEvent(source: 'Dict[str, Any]', sender: 'str')[source]

Bases: ToDeviceEvent

class nio.events.to_device.ForwardedRoomKeyEvent(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]

Bases: RoomKeyEvent

Event containing a room key that got forwarded to us.

sender

The sender of the event.

Type:

str

sender_key

The key of the sender that sent the event.

Type:

str

room_id

The room ID of the room to which the session key belongs to.

Type:

str

session_id

The session id of the session key.

Type:

str

algorithm

The algorithm of the session key.

Type:

str

classmethod from_dict(event_dict, sender, sender_key)[source]

Create a ForwardedRoomKeyEvent from a event dictionary.

Parameters:
  • event_dict (Dict) – The dictionary containing the event.

  • sender (str) – The sender of the event.

  • sender_key (str) – The key of the sender that sent the event.

class nio.events.to_device.KeyVerificationAccept(source: Dict[str, Any], sender: str, transaction_id: str, commitment: str, key_agreement_protocol: str, hash: str, message_authentication_code: str, short_authentication_string: List[str])[source]

Bases: KeyVerificationAcceptMixin, KeyVerificationEvent

Event signaling that the SAS verification start has been accepted.

commitment

The commitment value of the verification process.

Type:

str

key_agreement_protocol

The key agreement protocol the device is choosing to use

Type:

str

hash

A list of strings specifying the hash methods the sending device understands.

Type:

str

message_authentication_code

The message authentication code the device is choosing to use.

Type:

str

short_authentication_string

A list of strings specifying the SAS methods that can be used in the verification process.

Type:

list

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.KeyVerificationCancel(source: Dict[str, Any], sender: str, transaction_id: str, code: str, reason: str)[source]

Bases: KeyVerificationCancelMixin, KeyVerificationEvent

Event signaling that a key verification process has been canceled.

code

The error code for why the process/request was canceled by the user.

Type:

str

reason

A human readable description of the cancellation code.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.KeyVerificationEvent(source: Dict[str, Any], sender: str, transaction_id: str)[source]

Bases: KeyVerificationEventMixin, ToDeviceEvent

Base class for key verification events.

transaction_id

An opaque identifier for the verification process. Must be unique with respect to the devices involved.

Type:

str

class nio.events.to_device.KeyVerificationKey(source: Dict[str, Any], sender: str, transaction_id: str, key: str)[source]

Bases: KeyVerificationKeyMixin, KeyVerificationEvent

Event carrying a key verification key.

After this event is received the short authentication string can be shown to the user.

key

The device’s ephemeral public key, encoded as unpadded base64.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.KeyVerificationMac(source: Dict[str, Any], sender: str, transaction_id: str, mac: Dict[str, str], keys: str)[source]

Bases: KeyVerificationMacMixin, KeyVerificationEvent

Event holding a message authentication code of the verification process.

After this event is received the device that we are verifying will be marked as verified given that we have accepted the short authentication string as well.

mac

A map of the key ID to the MAC of the key, using the algorithm in the verification process. The MAC is encoded as unpadded base64.

Type:

dict

keys

The MAC of the comma-separated, sorted, list of key IDs given in the mac property, encoded as unpadded base64.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.KeyVerificationStart(source: Dict[str, Any], sender: str, transaction_id: str, from_device: str, method: str, key_agreement_protocols: List[str], hashes: List[str], message_authentication_codes: List[str], short_authentication_string: List[str])[source]

Bases: KeyVerificationStartMixin, KeyVerificationEvent

Event signaling the start of a SAS key verification process.

from_device

The device ID which is initiating the process.

Type:

str

method

The verification method to use.

Type:

str

key_agreement_protocols

A list of strings specifying the key agreement protocols the sending device understands.

Type:

list

hashes

A list of strings specifying the hash methods the sending device understands.

Type:

list

message_authentication_codes

A list of strings specifying the message authentication codes that the sending device understands.

Type:

list

short_authentication_string

A list of strings specifying the SAS methods the sending device (and the sending device’s user) understands.

Type:

list

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.OlmEvent(source: Dict[str, Any], sender: str, sender_key: str, ciphertext: Dict[str, Any], transaction_id: str | None = None)[source]

Bases: EncryptedToDeviceEvent

An Olm encrypted event.

Olm events are used to exchange end to end encrypted messages between two devices. They will mostly contain encryption keys to establish a Megolm session for a room.

nio users will never see such an event under normal circumstances since decrypting this event will produce an event of another type.

sender

The fully-qualified ID of the user who sent this event.

Type:

str

sender_key

The public key of the sender that was used to establish the encrypted session.

Type:

str, optional

ciphertext

The undecrypted ciphertext of the event.

Type:

Dict[str, Any]

transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:

str, optional

ciphertext: Dict[str, Any]
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

sender_key: str
transaction_id: str | None = None
class nio.events.to_device.RoomKeyEvent(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]

Bases: ToDeviceEvent

Event containing a megolm room key that got sent to us.

sender

The sender of the event.

Type:

str

sender_key

The key of the sender that sent the event.

Type:

str

room_id

The room ID of the room to which the session key belongs to.

Type:

str

session_id

The session id of the session key.

Type:

str

algorithm

The algorithm of the session key.

Type:

str

algorithm: str
classmethod from_dict(event_dict, sender, sender_key)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

room_id: str
sender_key: str
session_id: str
class nio.events.to_device.RoomKeyRequest(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str, algorithm: str, room_id: str, sender_key: str, session_id: str)[source]

Bases: BaseRoomKeyRequest

Event signaling that a room key was requested from us.

algorithm

The encryption algorithm the requested key in this event is to be used with. Will be set only if the action is ‘request’.

Type:

str, optional

room_id

The id of the room that the key is used in. Will be set only if the action is ‘request’.

Type:

str, optional

sender_key

The key of the device that initiated the session. Will be set only if the action is ‘request’.

Type:

str, optional

session_id

The id of the session the key is for. Will

Type:

str, optional

be set only if the action is 'request'.
algorithm: str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

room_id: str
sender_key: str
session_id: str
class nio.events.to_device.RoomKeyRequestCancellation(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str)[source]

Bases: BaseRoomKeyRequest

Event signaling that a previous room key request was canceled.

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

class nio.events.to_device.ToDeviceEvent(source: Dict[str, Any], sender: str)[source]

Bases: object

Base Event class for events that are sent using the to-device endpoint.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:

dict

sender

The fully-qualified ID of the user who sent this event.

Type:

str

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

classmethod parse_encrypted_event(event_dict)[source]

Parse an encrypted to-device event.

Encrypted events may have different fields depending on the algorithm that was used to encrypt them.

This function checks the algorithm of the event and produces a higher level event from the provided dictionary.

Parameters:

event_dict (dict) – The dictionary representation of the encrypted event.

Returns None if the algorithm of the event is unknown.

classmethod parse_event(event_dict: Dict) ToDeviceEvent | BadEvent | UnknownBadEvent | None[source]

Parse a to-device event and create a higher level event object.

This function parses the type of the to-device event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

Parameters:

event_dict (dict) – The dictionary representation of the event.

sender: str
source: Dict[str, Any]
class nio.events.to_device.UnknownToDeviceEvent(source: Dict[str, Any], sender: str, type: str)[source]

Bases: ToDeviceEvent

A ToDeviceEvent which we do not understand.

This event is created every time nio tries to parse an event of an unknown type. Since custom and extensible events are a feature of Matrix this allows clients to use custom events but care should be taken that the clients will be responsible to validate and type check the event.

type

The type of the event.

Type:

str

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

type: str

Ephemeral Events

nio Ephemeral events.

Ephemeral events are a special type of events that are not recorded in the room history.

Ephemeral events are used for typing notifications and read receipts.

class nio.events.ephemeral.EphemeralEvent[source]

Bases: object

Base class for ephemeral events.

classmethod from_dict(parsed_dict)[source]

Create an Ephemeral event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

classmethod parse_event(event_dict)[source]

Parse an ephemeral event and create a higher level event object.

This function parses the type of the ephemeral event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

If the event has an unknown type None is returned as well.

Parameters:

event_dict (dict) – The dictionary representation of the event.

class nio.events.ephemeral.Receipt(event_id: str, receipt_type: ReceiptType, user_id: str, timestamp: int, thread_id: str | None = None)[source]

Bases: object

Receipt of a user acknowledging an event.

If receipt_type is “m.read”, then it is a read receipt and shows the last event that a user has read.

event_id

the ID of the event being acknowledged

Type:

str

receipt_type

the type of receipt being received.

Type:

ReceiptType

user_id

the ID of the user who is acknowledging the event.

Type:

str

timestamp

The timestamp the receipt was sent at.

Type:

int

thread_id

the ID of the thread the receipt is for. Set to None if the receipt is unthreaded, or “main” if explicitly not in any particular thread.

Type:

str, optional

event_id: str
receipt_type: ReceiptType
thread_id: str | None = None
timestamp: int
user_id: str
class nio.events.ephemeral.ReceiptEvent(receipts: List[Receipt])[source]

Bases: EphemeralEvent

Informs the client of changes in the newest events seen by users.

A ReceiptEvent can contain multiple event_ids seen by many different users.

receipts

The list of `Receipt`s in this event.

Type:

List[Receipt]

classmethod from_dict(parsed_dict) ReceiptEvent[source]

Create an Ephemeral event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

receipts: List[Receipt]
class nio.events.ephemeral.TypingNoticeEvent(users: List)[source]

Bases: EphemeralEvent

Informs the client of the list of users currently typing in a room.

users

The list of user IDs typing in this room, if any.

Type:

List

classmethod from_dict(parsed_dict)[source]

Create an Ephemeral event from a dictionary.

Parameters:

parsed_dict (dict) – The dictionary representation of the event.

users: List

Account Data

nio Account data events.

Clients can store custom config data for their account on their homeserver.

This account data will be synced between different devices and can persist across installations on a particular device.

class nio.events.account_data.AccountDataEvent[source]

Bases: object

Abstract class for account data events.

classmethod parse_event(event_dict: Dict[Any, Any])[source]
class nio.events.account_data.FullyReadEvent(event_id: str)[source]

Bases: AccountDataEvent

Read marker location event.

The current location of the user’s read marker in a room. This event appears in the user’s room account data for the room the marker is applicable for.

event_id

The event id the user’s read marker is located at in the room.

Type:

str

event_id: str
classmethod from_dict(event_dict)[source]

Construct a FullyReadEvent from a dictionary.

class nio.events.account_data.PushAction[source]

Bases: object

An action to apply for a push rule when matching.

property as_value: str | Dict[str, Any]
classmethod from_dict(action: str | Dict[str, Any]) PushAction[source]
class nio.events.account_data.PushCoalesce[source]

Bases: PushAction

Causes multiple matching events to be joined into a single notification.

The behavior is homeserver-dependent. Homeservers not supporting this action should treat it as a PushNotify action.

property as_value: str
class nio.events.account_data.PushCondition[source]

Bases: object

A condition for a push rule to match an event.

property as_value: Dict[str, Any]
classmethod from_dict(condition: Dict[str, Any]) PushCondition[source]
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this condition holds true for a room event.

Parameters:
  • event (Event) – The room event to check the condition for.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

class nio.events.account_data.PushContainsDisplayName[source]

Bases: PushCondition

Require a message’s content.body to contain our display name.

This rule can only match unencrypted messages.

property as_value: Dict[str, Any]
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this condition holds true for a room event.

Parameters:
  • event (Event) – The room event to check the condition for.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

class nio.events.account_data.PushDontNotify[source]

Bases: PushAction

Prevents the matching event from generating a notification.

property as_value: str
class nio.events.account_data.PushEventMatch(key: str, pattern: str)[source]

Bases: PushCondition

Require a field of the event to match a glob-style pattern.

key

The dot-separated field of the event to match, e.g. "type" or "content.body".

Type:

str

pattern

Glob-style pattern to match the field’s value against. Patterns with no special glob characters should be treated as starting and ending with an asterisk.

Type:

str

property as_value: Dict[str, Any]
key: str
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this condition holds true for a room event.

Parameters:
  • event (Event) – The room event to check the condition for.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

pattern: str
class nio.events.account_data.PushNotify[source]

Bases: PushAction

Cause the matching event to generate a notification.

property as_value: str
class nio.events.account_data.PushRoomMemberCount(count: int, operator: str = '==')[source]

Bases: PushCondition

Require a certain member count for the room the event is posted in.

count

A number of members

Type:

int

operator

Whether the room’s member count should be equal ("==") to count, inferior ("<"), superior (">"), inferior or equal ("<="), or superior or equal (">=").

Type:

str

property as_value: Dict[str, Any]
count: int
classmethod from_dict(condition: Dict[str, Any]) PushRoomMemberCount[source]
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this condition holds true for a room event.

Parameters:
  • event (Event) – The room event to check the condition for.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

operator: str = '=='
class nio.events.account_data.PushRule(kind: ~nio.api.PushRuleKind, id: str, default: bool, enabled: bool = True, pattern: str = '', conditions: ~typing.List[~nio.events.account_data.PushCondition] = <factory>, actions: ~typing.List[~nio.events.account_data.PushAction] = <factory>)[source]

Bases: object

Rule stating how to notify the user for events matching some conditions.

kind

The kind of rule this is.

Type:

PushRuleKind

id

A unique (within its ruleset) string identifying this rule. The id for default rules set by the server starts with a .. For rules of room kind, this will be the room ID to match for. For rules of sender kind, this will be the user ID to match.

Type:

str

default

Whether this is a default rule set by the server, or one that the user created explicitly.

Type:

bool

enabled

Whether this rule is currently enabled, or disabled and to be ignored.

Type:

bool

pattern

Only applies to content rules. The glob-style pattern to match message text against.

Type:

str

conditions

Only applies to override and underride rules. The conditions that must be true for an event in order for this rule to be applied to it. A rule with no condition always matches.

Type:

List[PushCondition]

actions

The actions to perform when this rule matches.

Type:

List[PushAction]

actions: List[PushAction]
conditions: List[PushCondition]
default: bool
enabled: bool = True
classmethod from_dict(rule: Dict[str, Any], kind: PushRuleKind) PushRule[source]
id: str
kind: PushRuleKind
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this push rule matches a room event.

Parameters:
  • event (Event) – The room event to match.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

pattern: str = ''
class nio.events.account_data.PushRulesEvent(global_rules: ~nio.events.account_data.PushRuleset = <factory>, device_rules: ~nio.events.account_data.PushRuleset = <factory>)[source]

Bases: AccountDataEvent

Configured push rule sets for an account. Each set belongs to a scope.

global_rules

Rulesets applying to all devices

Type:

PushRuleset

device_rules

Rulesets applying to current device only

Type:

PushRuleset

device_rules: PushRuleset
classmethod from_dict(event: Dict[str, Any]) PushRulesEvent[source]
global_rules: PushRuleset
class nio.events.account_data.PushRuleset(override: ~typing.List[~nio.events.account_data.PushRule] = <factory>, content: ~typing.List[~nio.events.account_data.PushRule] = <factory>, room: ~typing.List[~nio.events.account_data.PushRule] = <factory>, sender: ~typing.List[~nio.events.account_data.PushRule] = <factory>, underride: ~typing.List[~nio.events.account_data.PushRule] = <factory>)[source]

Bases: object

A set of different kinds of push rules under a same scope.

override

Highest priority rules

Type:

List[PushRule]

content

Rules that configure behaviors for messages with text matching certain patterns.

Type:

List[PushRule]

room

Rules that configure behaviors for all messages in a certain room. Their id is the room’s ID.

Type:

List[PushRule]

sender

Rules that configure behaviors for all messages sent by a specific user. Their id is the user’s ID.

Type:

List[PushRule]

underride

Identical the override rules, but have a lower priority than content, room and sender rules.

Type:

List[PushRule]

content: List[PushRule]
classmethod from_dict(ruleset: Dict[str, Any]) PushRuleset[source]
matching_rule(event: Event, room: MatrixRoom, display_name: str) PushRule | None[source]

Return the push rule in this set that matches a room event, if any.

Parameters:
  • event (Event) – The room event to match.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

override: List[PushRule]
room: List[PushRule]
sender: List[PushRule]
underride: List[PushRule]
class nio.events.account_data.PushSenderNotificationPermission(key: str)[source]

Bases: PushCondition

Require the event’s sender to have a high enough power level.

key

Which key from the notifications dict in

Type:

str

power levels event
(https

//matrix.org/docs/spec/client_server/latest#m-room-power-levels)

should be referred to as the required level for the event's sender,
e.g. ``room``.
property as_value: Dict[str, Any]
key: str
matches(event: Event, room: MatrixRoom, display_name: str) bool[source]

Return whether this condition holds true for a room event.

Parameters:
  • event (Event) – The room event to check the condition for.

  • room (MatrixRoom) – The room that this event is part of.

  • display_name (str) – The display name of our own user in the room.

class nio.events.account_data.PushSetTweak(tweak: str, value: Any = None)[source]

Bases: PushAction

Set a particular tweak for the notification.

These tweaks are defined by the Matrix specification:

  • sound: The sound to be played when the notification arrives, e.g. a file path. A value of "default" means to play the client’s default sound. A device may choose to alert the user by some other means if appropriate, e.g. vibration.

  • highlight: Whether this message should be highlighted in the UI. This typically takes the form of presenting the message with a different color or style. The UI might also be adjusted to draw particular attention to the room in which the event occurred.

tweak

The name of the tweak to set

Type:

str

value

The tweak’s value.

Type:

Any

property as_value: Dict[str, Any]
tweak: str
value: Any = None
class nio.events.account_data.PushUnknownAction(action: str | Dict[str, Any])[source]

Bases: PushAction

An unknown kind of push rule action.

action

The action as a string or dict from the source event.

Type:

Union[str, Dict[str, Any]]

action: str | Dict[str, Any]
property as_value: str | Dict[str, Any]
class nio.events.account_data.PushUnknownCondition(condition: Dict[str, Any])[source]

Bases: PushCondition

An unknown kind of push rule condition.

condition

The condition as a dict from the source event.

Type:

Dict[str, Any]

property as_value: Dict[str, Any]
condition: Dict[str, Any]
class nio.events.account_data.TagEvent(tags: Dict[str, Dict[str, float] | None])[source]

Bases: AccountDataEvent

Event representing the tags of a room.

Room tags may include:

  • m.favourite for favourite rooms

  • m.lowpriority for low priority room

A tag may have an order between 0 and 1, indicating the room’s position towards other rooms with the same tag.

tags

The tags of the room

Type:

Dict[str, Optional[Dict[str, float]]]

and their contents.
classmethod from_dict(event_dict)[source]

Construct a TagEvent from a dictionary.

tags: Dict[str, Dict[str, float] | None]
class nio.events.account_data.UnknownAccountDataEvent(type: str, content: Dict[str, Any])[source]

Bases: AccountDataEvent

Account data event of an unknown type.

type

The type of the event.

Type:

str

content

The content of the event.

Type:

Dict

content: Dict[str, Any]
classmethod from_dict(event_dict)[source]

Construct an UnknownAccountDataEvent from a dictionary.

type: str

Building events

Nio Event Builders Module.

This module provides classes to easily create event dictionaries that can be used with the clients’s room_send() method, or room_create()’s initial_state argument. It also provides classes for some direct events such as to-device messages.

class nio.event_builders.EventBuilder[source]

Bases: object

The base class for event builders, should not be instantiated.

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

Direct messages

Matrix direct messages module.

This module contains classes that can be used to send direct events to a Matrix homeserver.

class nio.event_builders.direct_messages.DummyMessage(type: str, recipient: str, recipient_device: str, content: Dict)[source]

Bases: ToDeviceMessage

A dummy to-device mssage that is sent to restart a Olm session.

class nio.event_builders.direct_messages.RoomKeyRequestMessage(type: str, recipient: str, recipient_device: str, content: Dict, request_id: str, session_id: str, room_id: str, algorithm: str)[source]

Bases: ToDeviceMessage

A to-device message that requests room keys from other devices.

request_id

The unique request id that identifies this key request.

Type:

str

session_id

The session id that uniquely identifies the room key.

Type:

str

room_id

The room id of the room that the key belongs to.

Type:

str

algorithm

The algorithm of the room key.

Type:

str

class nio.event_builders.direct_messages.ToDeviceMessage(type: str, recipient: str, recipient_device: str, content: Dict)[source]

Bases: EventBuilder

A to-device message that can be sent to the homeserver.

type

The type of the message.

Type:

str

recipient

The user to whom we should sent this message.

Type:

str

recipient_device

The device id of the device that the message should be sent to.

Type:

str

content

The content that should be sent to the user.

Type:

Dict[Any, Any]

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

State events

Matrix state events module.

This module contains classes that can be used to easily create room state event dicts.

For example, to turn on encryption in a room with the HttpClient or AsyncClient, the EnableEncryptionBuilder class can be used:

>>> event_dict = EnableEncryptionBuilder().as_dict()
>>> client.room_send(
...     room_id      = "!test:example.com",
...     message_type = event_dict["type"],
...     content      = event_dict["content"],
... )
class nio.event_builders.state_events.ChangeGuestAccessBuilder(access: str)[source]

Bases: EventBuilder

A state event sent to allow or forbid guest accounts in a room.

access

Whether guests can join the room. Can be can_join or forbidden.

Type:

str

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

class nio.event_builders.state_events.ChangeHistoryVisibilityBuilder(visibility: str)[source]

Bases: EventBuilder

A state event sent to set what can users see from the room history.

visibility

Can be: - invited: users can’t see events that happened before they

were invited to the room

  • joined: users can’t see events that happened before they

    joined or accepted an invitation to the room.

  • shared: users that joined the room can see the entire

    room’s history

  • world_readable: anyone can see the entire room’s history,

    including users that aren’t part of the room.

Type:

str

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

class nio.event_builders.state_events.ChangeJoinRulesBuilder(rule: str)[source]

Bases: EventBuilder

A state event sent to change who can join a room.

rule

Can be public, meaning any user can join; or invite, meaning users must be invited to join the room. The matrix specification also reserves knock and private rules, which are currently not implemented.

Type:

str

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

class nio.event_builders.state_events.ChangeNameBuilder(name: str)[source]

Bases: EventBuilder

A state event sent to change a room’s name.

name

The name to set. Must not exceed 255 characters. Can be empty to remove the room’s name.

Type:

str

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

class nio.event_builders.state_events.ChangeTopicBuilder(topic: str)[source]

Bases: EventBuilder

A state event sent to change a room’s topic.

topic

The topic to set. Can be empty to remove the room’s topic.

Type:

str

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

class nio.event_builders.state_events.EnableEncryptionBuilder(algorithm: str = 'm.megolm.v1.aes-sha2', rotation_ms: int = 604800000, rotation_msgs: int = 100)[source]

Bases: EventBuilder

A state event sent to enable encryption in a room.

algorithm

The algorithm to use for encrypting messages. The default m.megolm.v1.aes-sha2 should not be changed.

Type:

str

rotation_ms

How long in milliseconds an encrypted session should be used before changing it. The default 604800000 (a week) is recommended.

Type:

int

rotation_msgs

How many messages can be received in a room before changing the encrypted session. The default 100 is recommended.

Type:

int

as_dict()[source]

Format the event as a dictionary, to be sent to the server.

Exceptions

exception nio.exceptions.EncryptionError[source]

Bases: Exception

exception nio.exceptions.GroupEncryptionError[source]

Bases: Exception

exception nio.exceptions.LocalProtocolError[source]

Bases: ProtocolError

exception nio.exceptions.LocalTransportError[source]

Bases: ProtocolError

exception nio.exceptions.MembersSyncError[source]

Bases: LocalProtocolError

exception nio.exceptions.OlmTrustError[source]

Bases: Exception

exception nio.exceptions.OlmUnverifiedDeviceError(unverified_device, *args)[source]

Bases: OlmTrustError

exception nio.exceptions.ProtocolError[source]

Bases: Exception

exception nio.exceptions.RemoteProtocolError[source]

Bases: ProtocolError

exception nio.exceptions.RemoteTransportError[source]

Bases: ProtocolError

exception nio.exceptions.SendRetryError[source]

Bases: LocalProtocolError

exception nio.exceptions.TransferCancelledError[source]

Bases: Exception

exception nio.exceptions.VerificationError[source]

Bases: Exception

Responses

class nio.responses.ContentRepositoryConfigError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response for a unsuccessful content repository config request.

class nio.responses.ContentRepositoryConfigResponse(upload_size: int | None = None)[source]

A response for a successful content repository config request.

upload_size

The maximum file size in bytes for an upload. If None, the limit is unknown.

Type:

Optional[int]

classmethod from_dict(parsed_dict: dict) ContentRepositoryConfigResponse | ErrorResponse[source]
upload_size: int | None = None
class nio.responses.DeleteDevicesAuthResponse(session: 'str', flows: 'Dict', params: 'Dict')[source]
flows: Dict
classmethod from_dict(parsed_dict: Dict[Any, Any]) DeleteDevicesAuthResponse | ErrorResponse[source]
params: Dict
session: str
class nio.responses.DeleteDevicesError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.DeleteDevicesResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.DeletePushRuleError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.DeletePushRuleResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.Device(id: 'str', display_name: 'str', last_seen_ip: 'str', last_seen_date: 'datetime')[source]
display_name: str
classmethod from_dict(parsed_dict)[source]
id: str
last_seen_date: datetime
last_seen_ip: str
class nio.responses.DeviceList(changed: 'List[str]', left: 'List[str]')[source]
changed: List[str]
left: List[str]
class nio.responses.DeviceOneTimeKeyCount(curve25519: 'Optional[int]', signed_curve25519: 'Optional[int]')[source]
curve25519: int | None
signed_curve25519: int | None
class nio.responses.DevicesError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.DevicesResponse(devices: 'List[Device]')[source]
devices: List[Device]
classmethod from_dict(parsed_dict: Dict[Any, Any]) DevicesResponse | ErrorResponse[source]
class nio.responses.DirectRoomsErrorResponse(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.DirectRoomsResponse(rooms: Dict[str, List[str]])[source]

A response containing a list of direct rooms.

rooms

The rooms joined by the account.

Type:

List[str]

classmethod from_dict(parsed_dict: Dict[Any, Any]) DirectRoomsResponse | DirectRoomsErrorResponse[source]
rooms: Dict[str, List[str]]
class nio.responses.DiscoveryInfoError(message: 'str', status_code: 'Optional[str]' = None, retry_after_ms: 'Optional[int]' = None, soft_logout: 'bool' = False)[source]
class nio.responses.DiscoveryInfoResponse(homeserver_url: str, identity_server_url: str | None = None)[source]

A response for a successful discovery info request.

homeserver_url

The base URL of the homeserver corresponding to the requested domain.

Type:

str

identity_server_url

The base URL of the identity server corresponding to the requested domain, if any.

Type:

str, optional

classmethod from_dict(parsed_dict: Dict[str, Any]) DiscoveryInfoResponse | DiscoveryInfoError[source]
homeserver_url: str
identity_server_url: str | None = None
class nio.responses.DiskDownloadResponse(body: PathLike, content_type: str, filename: str | None)[source]

A response representing a successful download request with the download content stored on disk.

body

The path to the downloaded file.

Type:

os.PathLike

content_type

The content type of the download.

Type:

str

filename

The filename of the download.

Type:

Optional[str]

body: PathLike
class nio.responses.DownloadError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing a unsuccessful download request.

class nio.responses.DownloadResponse(body: bytes | PathLike, content_type: str, filename: str | None)[source]

A response representing a successful download request.

classmethod from_data(data: PathLike | bytes, content_type: str, filename: str | None = None) DownloadResponse | DownloadError[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes, os.PathLike) – The file’s content in bytes.

  • content_type (str) – The content MIME type of the file, e.g. “image/png”.

  • filename (str, optional) – The file’s name returned by the server.

class nio.responses.EnablePushRuleError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.EnablePushRuleResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.ErrorResponse(message: 'str', status_code: 'Optional[str]' = None, retry_after_ms: 'Optional[int]' = None, soft_logout: 'bool' = False)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any]) ErrorResponse[source]
message: str
retry_after_ms: int | None = None
soft_logout: bool = False
status_code: str | None = None
class nio.responses.FileResponse(body: bytes | PathLike, content_type: str, filename: str | None)[source]

A response representing a successful file content request.

body

The file’s content in bytes, or location on disk if provided.

Type:

bytes, os.PathLike

content_type

The content MIME type of the file, e.g. “image/png”.

Type:

str

filename

The file’s name returned by the server.

Type:

str, optional

body: bytes | PathLike
content_type: str
filename: str | None
classmethod from_data(data: bytes | PathLike | dict, content_type, filename=None)[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes, os.PathLike) – The file’s content in bytes.

  • content_type (str) – The content MIME type of the file, e.g. “image/png”.

  • filename (str, optional) – The file’s name returned by the server.

class nio.responses.GetOpenIDTokenError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.GetOpenIDTokenResponse(access_token: 'str', expires_in: 'int', matrix_server_name: 'str', token_type: 'str')[source]
access_token: str
expires_in: int
classmethod from_dict(parsed_dict: Dict[Any, Any]) GetOpenIDTokenResponse | ErrorResponse[source]
matrix_server_name: str
token_type: str
class nio.responses.InviteInfo(invite_state: 'List')[source]
invite_state: List
class nio.responses.JoinError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.JoinResponse(room_id: str)[source]
static create_error(parsed_dict)[source]
class nio.responses.JoinedMembersError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.JoinedMembersResponse(members: 'List[RoomMember]', room_id: 'str')[source]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) JoinedMembersResponse | ErrorResponse[source]
members: List[RoomMember]
room_id: str
class nio.responses.JoinedRoomsError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing an unsuccessful joined rooms query.

class nio.responses.JoinedRoomsResponse(rooms: List[str])[source]

A response containing a list of joined rooms.

rooms

The rooms joined by the account.

Type:

List[str]

classmethod from_dict(parsed_dict: Dict[Any, Any]) JoinedRoomsResponse | ErrorResponse[source]
rooms: List[str]
class nio.responses.KeysClaimError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.KeysClaimResponse(one_time_keys: 'Dict[Any, Any]', failures: 'Dict[Any, Any]', room_id: 'str' = '')[source]
failures: Dict[Any, Any]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str = '') KeysClaimResponse | ErrorResponse[source]
one_time_keys: Dict[Any, Any]
room_id: str = ''
class nio.responses.KeysQueryError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.KeysQueryResponse(device_keys: 'Dict', failures: 'Dict')[source]
changed: Dict[str, Dict[str, Any]]
device_keys: Dict
failures: Dict
classmethod from_dict(parsed_dict: Dict[Any, Any]) KeysQueryResponse | ErrorResponse[source]
class nio.responses.KeysUploadError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.KeysUploadResponse(curve25519_count: 'int', signed_curve25519_count: 'int')[source]
curve25519_count: int
classmethod from_dict(parsed_dict: Dict[Any, Any]) KeysUploadResponse | ErrorResponse[source]
signed_curve25519_count: int
class nio.responses.LoginError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.LoginInfoError(message: 'str', status_code: 'Optional[str]' = None, retry_after_ms: 'Optional[int]' = None, soft_logout: 'bool' = False)[source]
class nio.responses.LoginInfoResponse(flows: 'List[str]')[source]
flows: List[str]
classmethod from_dict(parsed_dict: Dict[Any, Any]) LoginInfoResponse | ErrorResponse[source]
class nio.responses.LoginResponse(user_id: 'str', device_id: 'str', access_token: 'str')[source]
access_token: str
device_id: str
classmethod from_dict(parsed_dict: Dict[Any, Any]) LoginResponse | ErrorResponse[source]
user_id: str
class nio.responses.LogoutError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.LogoutResponse[source]
classmethod from_dict(parsed_dict: Dict[Any, Any]) LogoutResponse | ErrorResponse[source]

Create a response for logout response from server.

class nio.responses.MemoryDownloadResponse(body: bytes | PathLike, content_type: str, filename: str | None)[source]

A response representing a successful download request with the download content stored in-memory.

body

The content of the download.

Type:

bytes

content_type

The content type of the download.

Type:

str

filename

The filename of the download.

Type:

Optional[str]

class nio.responses.PresenceGetError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

Response representing a unsuccessful get presence request.

class nio.responses.PresenceGetResponse(user_id: str, presence: str, last_active_ago: int | None, currently_active: bool | None, status_msg: str | None)[source]

Response representing a successful get presence request.

user_id

The user´s id

Type:

str

presence

The user’s presence state. One of: [“online”, “offline”, “unavailable”]

Type:

str

last_active_ago

The length of time in milliseconds since an action was performed by this user. None if not set.

Type:

int, optional

currently_active

Whether the user is currently active. None if not set.

Type:

bool, optional

status_msg

The state message for this user. None if not set.

Type:

str, optional

currently_active: bool | None
classmethod from_dict(parsed_dict: Dict[Any, Any], user_id: str) PresenceGetResponse | PresenceGetError[source]
last_active_ago: int | None
presence: str
status_msg: str | None
user_id: str
class nio.responses.PresenceSetError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

Response representing a unsuccessful set presence request.

class nio.responses.PresenceSetResponse[source]

Response representing a successful set presence request.

static create_error(parsed_dict)[source]
class nio.responses.ProfileGetAvatarError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetAvatarResponse(avatar_url: str | None = None)[source]

Response representing a successful get avatar request.

avatar_url

The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.

Type:

str, optional

avatar_url: str | None = None
classmethod from_dict(parsed_dict: Dict[Any, Any]) ProfileGetAvatarResponse | ErrorResponse[source]
class nio.responses.ProfileGetDisplayNameError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetDisplayNameResponse(displayname: str | None = None)[source]

Response representing a successful get display name request.

displayname

The display name of the user. None if the user doesn’t have a display name.

Type:

str, optional

displayname: str | None = None
classmethod from_dict(parsed_dict: Dict[Any, Any]) ProfileGetDisplayNameResponse | ErrorResponse[source]
class nio.responses.ProfileGetError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetResponse(displayname: str | None = None, avatar_url: str | None = None, other_info: ~typing.Dict[~typing.Any, ~typing.Any] = <factory>)[source]

Response representing a successful get profile request.

displayname

The display name of the user. None if the user doesn’t have a display name.

Type:

str, optional

avatar_url

The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.

Type:

str, optional

other_info

Contains any other information returned for the user’s profile.

Type:

dict

avatar_url: str | None = None
displayname: str | None = None
classmethod from_dict(parsed_dict: Dict[Any, Any]) ProfileGetResponse | ErrorResponse[source]
other_info: Dict[Any, Any]
class nio.responses.ProfileSetAvatarError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetAvatarResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.ProfileSetDisplayNameError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetDisplayNameResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RegisterResponse(user_id: 'str', device_id: 'str', access_token: 'str')[source]
access_token: str
device_id: str
classmethod from_dict(parsed_dict)[source]
user_id: str
class nio.responses.Response[source]
property elapsed
end_time: float | None = None
start_time: float | None = None
timeout: int = 0
transport_response: TransportResponse | None = None
uuid: str = ''
class nio.responses.RoomBanError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.RoomBanResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomContextError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

Response representing a unsuccessful room context request.

class nio.responses.RoomContextResponse(room_id: str, start: str | None, end: str | None, event: Event | BadEvent | UnknownBadEvent | None, events_before: List[Event | BadEvent | UnknownBadEvent], events_after: List[Event | BadEvent | UnknownBadEvent], state: List[Event | BadEvent | UnknownBadEvent])[source]

Room event context response.

This Response holds a number of events that happened just before and after a specified event.

room_id

The room id of the room which the events belong to.

Type:

str

start

A token that can be used to paginate backwards with.

Type:

str

end

A token that can be used to paginate forwards with.

Type:

str

events_before

A list of room events that happened just before the requested event, in reverse-chronological order.

Type:

List[Event]

event

Details of the requested event.

Type:

Event

events_after

A list of room events that happened just after the requested event, in chronological order.

Type:

List[Event]

state

The state of the room at the last event returned.

Type:

List[Event]

end: str | None
event: Event | BadEvent | UnknownBadEvent | None
events_after: List[Event | BadEvent | UnknownBadEvent]
events_before: List[Event | BadEvent | UnknownBadEvent]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) RoomContextResponse | ErrorResponse[source]
room_id: str
start: str | None
state: List[Event | BadEvent | UnknownBadEvent]
class nio.responses.RoomCreateError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing a unsuccessful create room request.

class nio.responses.RoomCreateResponse(room_id: str)[source]

Response representing a successful create room request.

classmethod from_dict(parsed_dict: Dict[Any, Any]) RoomCreateResponse | RoomCreateError[source]
room_id: str
class nio.responses.RoomDeleteAliasError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room alias delete request.

class nio.responses.RoomDeleteAliasResponse(room_alias: str)[source]

A response containing the result of deleting an alias.

classmethod from_dict(parsed_dict: Dict[Any, Any], room_alias: str) RoomDeleteAliasResponse | ErrorResponse[source]
room_alias: str
class nio.responses.RoomForgetError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomForgetResponse(room_id: str)[source]

Response representing a successful forget room request.

static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomGetEventError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room get event request.

class nio.responses.RoomGetEventResponse[source]

A response indicating successful room get event request.

event

The requested event.

Type:

Event

event: Event = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
classmethod from_dict(parsed_dict: Dict[str, Any]) RoomGetEventResponse | RoomGetEventError[source]
class nio.responses.RoomGetStateError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state query.

class nio.responses.RoomGetStateEventError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state query.

class nio.responses.RoomGetStateEventResponse(content: Dict, event_type: str, state_key: str, room_id: str)[source]

A response containing the content of a specific bit of room state.

content

The content of the state event.

Type:

Dict

event_type

The type of the state event.

Type:

str

state_key

The key of the state event.

Type:

str

room_id

The ID of the room that the state event comes from.

Type:

str

content: Dict
static create_error(parsed_dict, room_id)[source]
event_type: str
classmethod from_dict(parsed_dict: Dict[str, Any], event_type: str, state_key: str, room_id: str) RoomGetStateEventResponse | RoomGetStateEventError[source]
room_id: str
state_key: str
class nio.responses.RoomGetStateResponse(events: List, room_id: str)[source]

A response containing the state of a room.

events

The events making up the room state.

Type:

List

room_id

The ID of the room.

Type:

str

static create_error(parsed_dict, room_id)[source]
events: List
classmethod from_dict(parsed_dict: List[Dict[Any, Any]], room_id: str) RoomGetStateResponse | RoomGetStateError[source]
room_id: str
class nio.responses.RoomGetVisibilityError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room get visibility request.

class nio.responses.RoomGetVisibilityResponse(room_id: str, visibility: str)[source]

A response containing the result of a get visibility request.

classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) RoomGetVisibilityResponse | ErrorResponse[source]
room_id: str
visibility: str
class nio.responses.RoomInfo(timeline: 'Timeline', state: 'List', ephemeral: 'List', account_data: 'List', summary: 'Optional[RoomSummary]' = None, unread_notifications: 'Optional[UnreadNotifications]' = None)[source]
account_data: List
ephemeral: List
static parse_account_data(event_dict)[source]

Parse the account data dictionary and produce a list of events.

state: List
summary: RoomSummary | None = None
timeline: Timeline
unread_notifications: UnreadNotifications | None = None
class nio.responses.RoomInviteError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.RoomInviteResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomKeyRequestError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

Response representing a failed room key request.

class nio.responses.RoomKeyRequestResponse(request_id: str, session_id: str, room_id: str, algorithm: str)[source]

Response representing a successful room key request.

request_id

The id of the that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.

Type:

str

session_id

The id of the session that we requested.

Type:

str

room_id

The id of the room that the session belongs to.

Type:

str

algorithm

The encryption algorithm of the session.

Type:

str

algorithm: str
classmethod from_dict(_, request_id, session_id, room_id, algorithm)[source]

Create a RoomKeyRequestResponse from a json response.

Parameters:
  • parsed_dict (Dict) – The dictionary containing the json response.

  • request_id (str) – The id of that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.

  • session_id (str) – The id of the session that we requested.

  • room_id (str) – The id of the room that the session belongs to.

  • algorithm (str) – The encryption algorithm of the session.

request_id: str
room_id: str
session_id: str
class nio.responses.RoomKickError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.RoomKickResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomKnockError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing a unsuccessful room knock request.

class nio.responses.RoomKnockResponse(room_id: str)[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomLeaveError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.RoomLeaveResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomMember(user_id: 'str', display_name: 'str', avatar_url: 'str')[source]
avatar_url: str
display_name: str
user_id: str
class nio.responses.RoomMessagesError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomMessagesResponse(room_id: 'str', chunk: 'List[Union[Event, BadEventType]]', start: 'str', end: 'str' = None)[source]
chunk: List[Event | BadEvent | UnknownBadEvent]
end: str = None
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) RoomMessagesResponse | ErrorResponse[source]
room_id: str
start: str
class nio.responses.RoomPutAliasResponse(room_alias: str, room_id: str)[source]

A response containing the result of adding an alias.

classmethod from_dict(parsed_dict: Dict[Any, Any], room_alias: str, room_id: str) RoomPutAliasResponse | ErrorResponse[source]
room_alias: str
room_id: str
class nio.responses.RoomPutStateError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state sending request.

class nio.responses.RoomPutStateResponse(event_id: str, room_id: str)[source]

A response indicating successful sending of room state.

static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomReadMarkersError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing a unsuccessful room read markers request.

class nio.responses.RoomReadMarkersResponse(room_id: str)[source]

A response representing a successful room read markers request.

static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomRedactError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomRedactResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomResolveAliasError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room alias query.

class nio.responses.RoomResolveAliasResponse(room_alias: str, room_id: str, servers: List[str])[source]

A response containing the result of resolving an alias.

room_alias

The alias of the room.

Type:

str

room_id

The resolved id of the room.

Type:

str

servers

Servers participating in the room.

Type:

List[str]

classmethod from_dict(parsed_dict: Dict[Any, Any], room_alias: str) RoomResolveAliasResponse | ErrorResponse[source]
room_alias: str
room_id: str
servers: List[str]
class nio.responses.RoomSendError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomSendResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomSummary(invited_member_count: 'Optional[int]' = None, joined_member_count: 'Optional[int]' = None, heroes: 'Optional[List[str]]' = None)[source]
heroes: List[str] | None = None
invited_member_count: int | None = None
joined_member_count: int | None = None
class nio.responses.RoomTypingError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room typing request.

class nio.responses.RoomTypingResponse(room_id: str)[source]

A response representing a successful room typing request.

static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomUnbanError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.RoomUnbanResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.Rooms(invite: 'Dict[str, InviteInfo]', join: 'Dict[str, RoomInfo]', leave: 'Dict[str, RoomInfo]')[source]
invite: Dict[str, InviteInfo]
join: Dict[str, RoomInfo]
leave: Dict[str, RoomInfo]
class nio.responses.SetPushRuleActionsError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.SetPushRuleActionsResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.SetPushRuleError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.SetPushRuleResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.ShareGroupSessionError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, room_id: str = '', users_shared_with: ~typing.Set[~typing.Tuple[str, str]] = <factory>)[source]

Response representing unsuccessful group sessions sharing request.

classmethod from_dict(parsed_dict, room_id, users_shared_with)[source]
users_shared_with: Set[Tuple[str, str]]
class nio.responses.ShareGroupSessionResponse(room_id: str, users_shared_with: set)[source]

Response representing a successful group sessions sharing request.

room_id

The room id of the group session.

Type:

str

users_shared_with

A set containing a tuple of user id device id pairs with whom we shared the group session in this request.

Type:

Set[Tuple[str, str]]

classmethod from_dict(_: Dict[Any, Any], room_id: str, users_shared_with: Set[Tuple[str, str]]) ShareGroupSessionResponse | ErrorResponse[source]

Create a response from the json dict the server returns.

Parameters:
  • parsed_dict (Dict) – The dict containing the raw json response.

  • room_id (str) – The room id of the room to which the group session belongs to.

  • users_shared_with (Set[Tuple[str, str]]) – A set containing a tuple of user id device id pairs with whom we shared the group session in this request.

room_id: str
users_shared_with: set
class nio.responses.SpaceGetHierarchyError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.SpaceGetHierarchyResponse(next_batch: str, rooms: List)[source]

A response indicating successful space get hierarchy request.

next_batch

The token to supply in the from parameter of the next call.

Type:

str

rooms

The rooms in the space.

Type:

List

classmethod from_dict(parsed_dict: Dict[str, Any]) SpaceGetHierarchyResponse | SpaceGetHierarchyError[source]
next_batch: str
rooms: List
class nio.responses.SyncError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.SyncResponse(next_batch: 'str', rooms: 'Rooms', device_key_count: 'DeviceOneTimeKeyCount', device_list: 'DeviceList', to_device_events: 'List[ToDeviceEvent]', presence_events: 'List[PresenceEvent]', account_data_events: 'List[AccountDataEvent]' = <factory>)[source]
account_data_events: List[AccountDataEvent]
device_key_count: DeviceOneTimeKeyCount
device_list: DeviceList
classmethod from_dict(parsed_dict: Dict[Any, Any]) SyncResponse | ErrorResponse[source]
next_batch: str
presence_events: List[PresenceEvent]
rooms: Rooms
to_device_events: List[ToDeviceEvent]
class nio.responses.ThumbnailError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing a unsuccessful thumbnail request.

class nio.responses.ThumbnailResponse(body: bytes | PathLike, content_type: str, filename: str | None)[source]

A response representing a successful thumbnail request.

classmethod from_data(data: bytes, content_type: str, filename: str | None = None) ThumbnailResponse | ThumbnailError[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes, os.PathLike) – The file’s content in bytes.

  • content_type (str) – The content MIME type of the file, e.g. “image/png”.

  • filename (str, optional) – The file’s name returned by the server.

class nio.responses.Timeline(events: 'List', limited: 'bool', prev_batch: 'Optional[str]')[source]
events: List
limited: bool
prev_batch: str | None
class nio.responses.ToDeviceError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False, to_device_message: ToDeviceMessage | None = None)[source]

Response representing a unsuccessful room key request.

classmethod from_dict(parsed_dict, message)[source]
to_device_message: ToDeviceMessage | None = None
class nio.responses.ToDeviceResponse(to_device_message: ToDeviceMessage)[source]

Response representing a successful room key request.

classmethod from_dict(parsed_dict, message)[source]

Create a ToDeviceResponse from a json response.

to_device_message: ToDeviceMessage
class nio.responses.UpdateDeviceError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.UpdateDeviceResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.UpdateReceiptMarkerError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.UpdateReceiptMarkerResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.UploadError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]

A response representing a unsuccessful upload request.

class nio.responses.UploadFilterError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.UploadFilterResponse(filter_id: str)[source]

Response representing a successful filter upload request.

filter_id

A filter ID that may be used in future requests to restrict which events are returned to the client.

Type:

str

filter_id: str
classmethod from_dict(parsed_dict: Dict[Any, Any]) UploadFilterResponse | UploadFilterError[source]
class nio.responses.UploadResponse(content_uri: str)[source]

A response representing a successful upload request.

content_uri: str
classmethod from_dict(parsed_dict: Dict[Any, Any]) UploadResponse | ErrorResponse[source]
class nio.responses.WhoamiError(message: str, status_code: str | None = None, retry_after_ms: int | None = None, soft_logout: bool = False)[source]
class nio.responses.WhoamiResponse(user_id: 'str', device_id: 'Optional[str]', is_guest: 'Optional[bool]')[source]
device_id: str | None
classmethod from_dict(parsed_dict: Dict[Any, Any]) WhoamiResponse | WhoamiError[source]
is_guest: bool | None
user_id: str

Storage

Nio storage module.

This module contains storage classes that are used to store encryption devices, encryption keys and the trust state of devices.

The module contains three store implementations one using a Sqlite database and plaintext files to store keys and the truststate of devices, one that uses a pure Sqlite database and one that stores the Sqlite database in memory.

User provided store types can be implemented by overriding the methods provided in the MatrixStore base class.

isort:skip_file

class nio.store.MatrixStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Storage class for matrix state.

add_outgoing_key_request(key_request: OutgoingKeyRequest) None[source]

Add an outgoing key request to the store.

blacklist_device(device: OlmDevice) bool[source]

Mark a device as blacklisted.

Parameters:

device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was blacklisted, False otherwise, e.g. if the device was already blacklisted.

delete_encrypted_room(room: str) None[source]

Delete an encrypted room from the store.

ignore_device(device: OlmDevice) bool[source]

Mark a device as ignored.

Parameters:

device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was ignored, False otherwise, e.g. if the device was already ignored.

ignore_devices(devices: List[OlmDevice]) None[source]

Mark a list of devices as ignored.

This is a more efficient way to mark multiple devices as ignored.

Parameters:

devices (list[OlmDevice]) – A list of OlmDevices that will be marked as ignored.

is_device_blacklisted(device: OlmDevice) bool[source]

Check if a device is blacklisted.

Parameters:

device (OlmDevice) – The device that will be checked if it’s blacklisted.

is_device_ignored(device: OlmDevice) bool[source]

Check if a device is ignored.

Parameters:

device (OlmDevice) – The device that will be checked if it’s ignored.

is_device_verified(device: OlmDevice) bool[source]

Check if a device is verified.

Parameters:

device (OlmDevice) – The device that will be checked if it’s verified.

load_account() OlmAccount | None[source]

Load the Olm account from the database.

Returns:

OlmAccount object, or None if it wasn’t found for the

current device_id.

load_device_keys() DeviceStore[source]

Load all the device keys from the database.

Returns DeviceStore containing the OlmDevices with the device keys.

load_encrypted_rooms()[source]

Load the set of encrypted rooms for this account.

Returns:

Set containing room ids of encrypted rooms.

load_inbound_group_sessions() GroupSessionStore[source]

Load all Olm sessions from the database.

Returns:

GroupSessionStore object, containing all the loaded sessions.

load_outgoing_key_requests()[source]

Load the set of outgoing key requests for this account.

Returns:

Set containing request ids of key requests.

load_sessions() SessionStore[source]

Load all Olm sessions from the database.

Returns:

SessionStore object, containing all the loaded sessions.

remove_outgoing_key_request(key_request: OutgoingKeyRequest) None[source]

Remove an active outgoing key request from the store.

save_account(account)[source]

Save the provided Olm account to the database.

Parameters:

account (OlmAccount) – The olm account that will be pickled and saved in the database.

save_device_keys(device_keys)[source]

Save the provided device keys to the database.

Parameters:

device_keys (Dict[str, Dict[str, OlmDevice]]) – A dictionary containing a mapping from a user id to a dictionary containing a mapping of a device id to a OlmDevice.

save_encrypted_rooms(rooms)[source]

Save the set of room ids for this account.

save_inbound_group_session(session)[source]

Save the provided Megolm inbound group session to the database.

Parameters:

session (InboundGroupSession) – The session to save.

save_session(curve_key, session)[source]

Save the provided Olm session to the database.

Parameters:
  • curve_key (str) – The curve key that owns the Olm session.

  • session (Session) – The Olm session that will be pickled and saved in the database.

save_sync_token(token: str) None[source]

Save the given token

unblacklist_device(device: OlmDevice) bool[source]

Unmark a device as blacklisted.

Parameters:

device (OlmDevice) – The device that will be unmarked as blacklisted

unignore_device(device: OlmDevice) bool[source]

Unmark a device as ignored.

Parameters:

device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was unignored, False otherwise, e.g. if the device wasn’t ignored in the first place.

unverify_device(device: OlmDevice) bool[source]

Unmark a device as verified.

Parameters:

device (OlmDevice) – The device that will be unmarked as verified

Returns True if the device was unverified, False otherwise, e.g. if the device wasn’t verified.

verify_device(device: OlmDevice) bool[source]

Mark a device as verified.

Parameters:

device (OlmDevice) – The device that will be marked as verified

Returns True if the device was verified, False otherwise, e.g. if the device was already verified.

class nio.store.DefaultStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Bases: MatrixStore

The default nio Matrix Store.

This store uses an Sqlite database as the main storage format while device trust state is stored in plaintext files using a format similar to the ssh known_hosts file format. The files will be created in the same directory as the main Sqlite database.

One such file is created for each of the 3 valid states (verified, blacklisted, ignored). If a device isn’t found in any of those files the verification state is considered to be unset.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.

  • device_id (str) – The device id of the user’s device.

  • store_path (str) – The path where the store should be stored.

  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.

  • database_name (str, optional) – The file-name of the database that should be used.

class nio.store.SqliteStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Bases: MatrixStore

The Sqlite only nio Matrix Store.

This store uses an Sqlite database as the main storage format as well as the store format for the trust state.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.

  • device_id (str) – The device id of the user’s device.

  • store_path (str) – The path where the store should be stored.

  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.

  • database_name (str, optional) – The file-name of the database that should be used.

class nio.store.SqliteMemoryStore(user_id, device_id, pickle_key='')[source]

Bases: SqliteStore

The Sqlite only nio Matrix Store.

This store uses a Sqlite database as the main storage format as well as the store format for the trust state. The Sqlite database will be stored only in memory and all the data will be lost after the object is deleted.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.

  • device_id (str) – The device id of the user’s device.

  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.

Encryption

nio encryption module.

Encryption is handled mostly transparently to the user.

The main thing users need to worry about is device verification.

While device verification is handled in the Client classes of nio the classes that are used to introspect OlmDevices or device authentication sessions are documented here.

class nio.crypto.DeviceStore[source]

A store that holds olm devices in memory.

The DeviceStore class implements the iter method, devices can be iterated over normally using:

>>> for device in device_store:
...    print(device.user_id, device.device_id)

To get only non-deleted devices of a user the active_user_devices method can be used:

>>> for device in device_store.active_user_devices("@bob:example.org"):
...    print(device.user_id, device.device_id)
active_user_devices(user_id: str) Iterator[OlmDevice][source]

Get all the non-deleted devices of a user.

Parameters:

user_id (str) – The user for which we would like to get the devices for.

This returns an iterator over all the non-deleted devices of the given user.

add(device: OlmDevice) bool[source]

Add the given device to the store.

Parameters:

device (OlmDevice) – The device that should be added to the store.

Returns True if the device was added to the store, False if it already was in the store.

device_from_sender_key(user_id: str, sender_key: str) OlmDevice | None[source]

Get a non-deleted device of a user with the matching sender key.

Parameters:
  • user_id (str) – The user id of the device owner.

  • sender_key (str) – The encryption key that is owned by the device,

  • key. (usually a curve25519 public) –

items()[source]

List of tuples in the form (user id, dict(device_id, OlmDevice).

property users: KeysView[str]

Get the list of users that the device store knows about.

values()[source]

List of devices in the form of a dict(device_id, OlmDevice).

class nio.crypto.OlmDevice(user_id: str, device_id: str, keys: Dict[str, str], display_name: str = '', deleted: bool = False, trust_state: TrustState = TrustState.unset)[source]

Class holding info about users Olm devices.

OlmDevices represent user devices with which we can communicate in an encrypted manner. To do so an OlmDevice needs to have its trust state set. The trust state can be set to one of “verified”, “ignored”, or “blacklisted”.

Note that the trust state should never be moddified directly on an OlmDevice, all the attributes here are read only.

The trust state can be changed by passing the OlmDevice to a nio Client or a MatrixStore class.

user_id

The id of the user that the device belongs to.

Type:

str

device_id

The device id that combined with the user id uniquely identifies the device.

Type:

str

keys

A dictionary containing the type and the public part of this devices encryption keys.

Type:

Dict

display_name

The human readable name of this device.

Type:

str

deleted

A boolean signaling if this device has been deleted by its owner.

Type:

bool

trust_state

The trust state of this device.

Type:

TrustState

as_dict()[source]

Convert the OlmDevice into a dictionary.

property blacklisted: bool

Is the device blacklisted.

property curve25519: str

The curve25519 key of the device.

property ed25519: str

The ed25519 fingerprint key of the device.

property id: str

The device id.

Same as the device_id attribute.

property ignored: bool

Is the device ignored.

property verified: bool

Is the device verified.

class nio.crypto.TrustState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

The device trust state.

An Enum holding differing values that a device trust state can be in.

class nio.crypto.Sas(*args: Any, **kwargs: Any)[source]

Matrix Short Authentication String class.

This class implements a state machine to handle device verification using short authentication strings.

we_started_it

Is true if the verification process was started by us, otherwise false.

Type:

bool

sas_accepted

Is true if we accepted that the short authentication string matches on both devices.

Type:

bool

verified_devices

The list of device ids that were verified during the verification process.

Type:

List[str]

Parameters:
  • own_user (str) – The user id of our own user.

  • own_device (str) – The device id of our own user.

  • own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.

  • other_olm_device (OlmDevice) – The OlmDevice which we would like to verify.

  • transaction_id (str, optional) – A string that will uniquely identify this verification process. A random and unique string will be generated if one isn’t provided.

  • short_auth_string (List[str], optional) – A list of valid short authentication methods that the client would like to allow for this authentication session. By default the ‘emoji’ and ‘decimal’ methods are allowed.

accept_sas()[source]

Accept the short authentication string.

accept_verification() ToDeviceMessage[source]

Create a content dictionary to accept the verification offer.

cancel()[source]

Cancel the authentication process.

property canceled: bool

Is the verification request canceled.

classmethod from_key_verification_start(own_user: str, own_device: str, own_fp_key: str, other_olm_device: OlmDevice, event: KeyVerificationStart) Sas[source]

Create a SAS object from a KeyVerificationStart event.

Parameters:
  • own_user (str) – The user id of our own user.

  • own_device (str) – The device id of our own user.

  • own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.

  • other_olm_device (OlmDevice) – The Olm device of the other user that should be verified.

  • event (KeyVerificationStart) – The event that we received from the other device to start the key verification process.

get_cancellation() ToDeviceMessage[source]

Create a dictionary containing our verification cancellation.

get_decimals() Tuple[int, ...][source]

Get the decimal short authentication string.

Returns a tuple that contains three 4 digit integer numbers that represent the short authentication string.

get_emoji() List[Tuple[str, str]][source]

Get the emoji short authentication string.

Returns a list of tuples that contain the emoji and the description of the emoji of the short authentication string.

get_mac() ToDeviceMessage[source]

Create a dictionary containing our MAC.

receive_accept_event(event)[source]

Receive a KeyVerificationAccept event.

receive_key_event(event)[source]

Receive a KeyVerificationKey event.

receive_mac_event(event)[source]

Receive a KeyVerificationMac event.

Parameters:

event (KeyVerificationMac) – The MAC event that was received for this SAS session.

reject_sas()[source]

Reject the authentication string.

share_key() ToDeviceMessage[source]

Create a dictionary containing our public key.

start_verification() ToDeviceMessage[source]

Create a content dictionary to start the verification.

property timed_out: bool

Did the verification process time out.

property verified: bool

Is the device verified and the request done.