API

This document details the API of nio.

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, devices, auth_dict=None)[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: nio.api.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 devices(access_token)[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 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, media_id, filename=None, allow_remote=True)[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.
static enable_pushrule(access_token: str, scope: str, kind: nio.api.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, hash, iv, homeserver=None, mimetype=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_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, room_id)[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, room_id)[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)[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, user_set)[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, user_set, token=None)[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, key_dict)[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, password=None, device_name='', device_id='', token=None)[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.
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)[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, all_devices=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)[source]

Turn a mimetype into a matrix message type.

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

Convert a matrix content URI to a HTTP URI.

static profile_get(user_id: str, access_token: str = 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 perfomed.
static profile_get_avatar(user_id, access_token: str = None)[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 perfomed.
static profile_get_displayname(user_id, access_token: str = None)[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 perfomed.
static profile_set_avatar(access_token, user_id, avatar_url)[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, user_id, display_name)[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 register(user, password=None, device_name='', device_id='')[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.
static room_ban(access_token: str, room_id: str, user_id: str, reason: Optional[str] = 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, room_id, event_id, limit=None)[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, visibility=<RoomVisibility.private: 'private'>, alias=None, name=None, topic=None, room_version=None, federate=True, is_direct=False, preset=None, invite=(), initial_state=(), power_level_override=None)[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.
  • 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 immediatly 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.
static room_forget(access_token, room_id)[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_state(access_token, room_id)[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, event_type, state_key='')[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_invite(access_token, room_id, user_id)[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, room_id, user_id, reason=None)[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_leave(access_token, room_id)[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, end: Optional[str] = None, direction: nio.api.MessageDirection = <MessageDirection.back: 0>, limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None)[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_state(access_token, room_id, event_type, body, state_key='')[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, room_id, fully_read_event, read_event=None)[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 read receipt’s location.

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.
static room_redact(access_token, room_id, event_id, tx_id, reason=None)[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)[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, room_id, event_type, body, tx_id)[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, room_id, user_id, typing_state=True, timeout=30000)[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)[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: nio.api.PushRuleKind, rule_id: str, before: Optional[str] = None, after: Optional[str] = None, actions: Sequence[PushAction] = (), conditions: Optional[Sequence[PushCondition]] = None, pattern: Optional[str] = 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: nio.api.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 sync(access_token: str, since: Optional[str] = None, timeout: Optional[int] = None, filter: Union[None, str, Dict[Any, Any]] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None)[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, optinal) – 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, media_id, width, height, method=<ResizingMethod.scale: 'scale'>, allow_remote=True)[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)[source]

Turn a dictionary into a canonical json string.

static to_device(access_token, event_type, content, tx_id)[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)[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: str = 'm.read') → Tuple[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 (str) – The type of receipt to send. Currently, only m.read is supported by the Matrix specification.
static upload(access_token, filename=None)[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: Optional[List[str]] = None, event_format: nio.api.EventFormat = <EventFormat.client: 'client'>, presence: Optional[Dict[str, Any]] = None, account_data: Optional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = 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)[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: Optional[Type[MatrixStore]] = <class 'nio.store.database.DefaultStore'>, encryption_enabled: bool = True, store_name: str = '', pickle_key: str = 'DEFAULT_KEY', store_sync_tokens: bool = False)[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

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

store

alias of nio.store.database.DefaultStore

Client

class nio.Client(user: str, device_id: Optional[str] = None, store_path: Optional[str] = '', config: Optional[nio.client.base_client.ClientConfig] = 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 storeage.
  • config (ClientConfig, optional) – Configuration for the client.
add_ephemeral_callback(callback: Callable[[nio.rooms.MatrixRoom, nio.events.ephemeral.EphemeralEvent], None], filter: Union[Type[nio.events.ephemeral.EphemeralEvent], Tuple[Type[nio.events.ephemeral.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
  • Tuple[Type[EphemeralEvent], ..]]) ((Union[Type[EphemeralEvent],) – The event type or a tuple containing multiple types for which the function will be called.
add_event_callback(callback: Callable[[nio.rooms.MatrixRoom, nio.events.room_events.Event], None], filter: Union[Type[nio.events.room_events.Event], Tuple[Type[nio.events.room_events.Event], ...]]) → 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], 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[[nio.events.account_data.AccountDataEvent], None], filter: Union[Type[nio.events.account_data.AccountDataEvent], Tuple[Type[nio.events.account_data.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
  • Tuple[Type[AccountDataEvent, ..]]) ((Union[Type[AccountDataEvent],) – The event type or a tuple containing multiple types for which the function will be called.
add_presence_callback(callback: Callable[[nio.events.presence.PresenceEvent], None], filter: Union[Type[CT_co], Tuple[Type[CT_co]]])[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 a 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[[nio.rooms.MatrixRoom, nio.events.account_data.AccountDataEvent], None], filter: Union[Type[nio.events.account_data.AccountDataEvent], Tuple[Type[nio.events.account_data.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
  • Tuple[Type[AccountDataEvent, ..]]) ((Union[Type[AccountDataEvent],) – The event type or a tuple containing multiple types for which the function will be called.
add_to_device_callback(callback: Callable[[nio.events.to_device.ToDeviceEvent], None], filter: Union[Type[nio.events.to_device.ToDeviceEvent], Tuple[Type[nio.events.to_device.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 a the to-device part of the sync response.
  • filter
  • Tuple[Type[ToDeviceEvent], ..]]) ((Union[Type[ToDeviceEvent],) – The event type or a tuple containing multiple types for which the function will be called.
blacklist_device(device: nio.crypto.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: nio.events.to_device.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) → nio.event_builders.direct_messages.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 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: nio.events.to_device.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: nio.crypto.device.OlmDevice) → nio.event_builders.direct_messages.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: nio.events.room_events.MegolmEvent) → Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.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.

device_store

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[nio.events.to_device.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, device_id)[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 wich 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: nio.crypto.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]

Explicitely remove encryption keys for a room.

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

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.
logged_in

Check if we are logged in.

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

olm_account_shared

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

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

outgoing_key_requests

Our active key requests that we made.

outgoing_to_device_messages

To-device messages that we need to send out.

receive_response(response: nio.responses.Response) → Union[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, nio.crypto.device.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.

should_claim_keys

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.

should_query_keys

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

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

should_upload_keys

Check if the client should upload encryption keys.

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

unblacklist_device(device: nio.crypto.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: nio.crypto.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: nio.crypto.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.

users_for_key_query

Users for whom we should make a key query.

verify_device(device: nio.crypto.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: Optional[str] = '', store_path: Optional[str] = '', config: Optional[nio.client.async_client.AsyncClientConfig] = None, ssl: Optional[bool] = None, proxy: Optional[str] = None)[source]

Bases: nio.client.base_client.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))
accept_key_verification(transaction_id: str, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.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, nio.responses.Response], cb_filter: Union[Tuple[Type[CT_co]], Type[CT_co], 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 succesfully 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)
cancel_key_verification(transaction_id: str, reject: bool = False, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.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.

close()[source]

Close the underlying http session.

confirm_short_auth_string(transaction_id: str, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.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.
content_repository_config() → Union[nio.responses.ContentRepositoryConfigResponse, nio.responses.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.

create_matrix_response(response_class: Type[CT_co], transport_response: aiohttp.client_reqrep.ClientResponse, data: Tuple[Any, ...] = None) → nio.responses.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.

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

delete_devices(devices: List[str], auth: Optional[Dict[str, str]] = None) → Union[nio.responses.DeleteDevicesResponse, nio.responses.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)
delete_pushrule(scope: str, kind: nio.api.PushRuleKind, rule_id: str) → Union[nio.responses.DeletePushRuleResponse, nio.responses.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.
devices() → Union[nio.responses.DevicesResponse, nio.responses.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.

discovery_info() → Union[nio.responses.DiscoveryInfoResponse, nio.responses.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
download(server_name: str, media_id: str, filename: Optional[str] = None, allow_remote: bool = True) → Union[nio.responses.DownloadResponse, nio.responses.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 DownloadResponse if the request was successful or a DownloadError 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.
  • 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.
enable_pushrule(scope: str, kind: nio.api.PushRuleKind, rule_id: str, enable: bool) → Union[nio.responses.EnablePushRuleResponse, nio.responses.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.
get_avatar(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetAvatarResponse, nio.responses.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.
get_displayname(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetDisplayNameResponse, nio.responses.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.
get_presence(user_id: str) → Union[nio.responses.PresenceGetResponse, nio.responses.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.
get_profile(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetResponse, nio.responses.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.
get_timeout_retry_wait_time(got_timeouts: int) → float[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.

join(room_id: str) → Union[nio.responses.JoinResponse, nio.responses.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.
joined_members(room_id: str) → Union[nio.responses.JoinedMembersResponse, nio.responses.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.
joined_rooms() → Union[nio.responses.JoinedRoomsResponse, nio.responses.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.

keys_claim(user_set: Dict[str, Iterable[str]]) → Union[nio.responses.KeysClaimResponse, nio.responses.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 maping 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.

keys_query() → Union[nio.responses.KeysQueryResponse, nio.responses.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.

keys_upload() → Union[nio.responses.KeysUploadResponse, nio.responses.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.

login(password: Optional[str] = None, device_name: Optional[str] = '', token: Optional[str] = None) → Union[nio.responses.LoginResponse, nio.responses.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.

login_info() → Union[nio.responses.LoginInfoResponse, nio.responses.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.

login_raw(auth_dict: Dict[str, Any]) → Union[nio.responses.LoginResponse, nio.responses.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.

logout(all_devices: bool = False) → Union[nio.responses.LogoutResponse, nio.responses.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.

mxc_to_http(mxc: str, homeserver: Optional[str] = None) → Optional[str][source]

Convert a matrix content URI to a HTTP URI.

parse_body(transport_response: aiohttp.client_reqrep.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.

receive_response(response: nio.responses.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
register(username, password, device_name='')[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) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.

Returns a ‘RegisterResponse’ if successful.

request_room_key(event: nio.events.room_events.MegolmEvent, tx_id: Optional[str] = None) → Union[nio.responses.RoomKeyRequestResponse, nio.responses.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.
room_ban(room_id: str, user_id: str, reason: Optional[str] = None) → Union[nio.responses.RoomBanResponse, nio.responses.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.
room_context(room_id: str, event_id: str, limit: Optional[int] = None) → Union[nio.responses.RoomContextResponse, nio.responses.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.
room_create(visibility: nio.api.RoomVisibility = <RoomVisibility.private: 'private'>, alias: Optional[str] = None, name: Optional[str] = None, topic: Optional[str] = None, room_version: Optional[str] = None, federate: bool = True, is_direct: bool = False, preset: Optional[nio.api.RoomPreset] = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Optional[Dict[str, Any]] = None) → Union[nio.responses.RoomCreateResponse, nio.responses.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.
  • 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 immediatly 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) → Union[nio.responses.RoomForgetResponse, nio.responses.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.
room_get_event(room_id: str, event_id: str) → Union[nio.responses.RoomGetEventResponse, nio.responses.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.
room_get_state(room_id: str) → Union[nio.responses.RoomGetStateResponse, nio.responses.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.
room_get_state_event(room_id: str, event_type: str, state_key: str = '') → Union[nio.responses.RoomGetStateEventResponse, nio.responses.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.
room_invite(room_id: str, user_id: str) → Union[nio.responses.RoomInviteResponse, nio.responses.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.
room_kick(room_id: str, user_id: str, reason: Optional[str] = None) → Union[nio.responses.RoomKickResponse, nio.responses.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.
room_leave(room_id: str) → Union[nio.responses.RoomLeaveResponse, nio.responses.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.
room_messages(room_id: str, start: str, end: Optional[str] = None, direction: nio.api.MessageDirection = <MessageDirection.back: 0>, limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None) → Union[nio.responses.RoomMessagesResponse, nio.responses.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 RoomMessagesResponse 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)
room_put_state(room_id: str, event_type: str, content: Dict[Any, Any], state_key: str = '') → Union[nio.responses.RoomPutStateResponse, nio.responses.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.
room_read_markers(room_id: str, fully_read_event: str, read_event: Optional[str] = None)[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: str, event_id: str, reason: Optional[str] = None, tx_id: Union[None, str, uuid.UUID] = None) → Union[nio.responses.RoomRedactResponse, nio.responses.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.
room_resolve_alias(room_alias: str) → Union[nio.responses.RoomResolveAliasResponse, nio.responses.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
room_send(room_id: str, message_type: str, content: Dict[Any, Any], tx_id: Optional[str] = None, ignore_unverified_devices: bool = False)[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.

room_typing(room_id: str, typing_state: bool = True, timeout: int = 30000) → Union[nio.responses.RoomTypingResponse, nio.responses.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.
room_unban(room_id: str, user_id: str) → Union[nio.responses.RoomBanResponse, nio.responses.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.
run_response_callbacks(responses: List[Union[nio.responses.Response, nio.responses.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().

send(method: str, path: str, data: Union[None, str, pathlib.Path, bytes, Iterable[bytes], AsyncIterable[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None) → aiohttp.client_reqrep.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.
send_to_device_messages() → List[Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError]][source]

Send out outgoing to-device messages.

Automatically called by sync_forever().

set_avatar(avatar_url: str) → Union[nio.responses.ProfileSetAvatarResponse, nio.responses.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.
set_displayname(displayname: str) → Union[nio.responses.ProfileSetDisplayNameResponse, nio.responses.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.
set_presence(presence: str, status_msg: str = None) → Union[nio.responses.PresenceSetResponse, nio.responses.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.
set_pushrule(scope: str, kind: nio.api.PushRuleKind, rule_id: str, before: Optional[str] = None, after: Optional[str] = None, actions: Sequence[nio.events.account_data.PushAction] = (), conditions: Optional[Sequence[nio.events.account_data.PushCondition]] = None, pattern: Optional[str] = None) → Union[nio.responses.SetPushRuleResponse, nio.responses.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"
... )
set_pushrule_actions(scope: str, kind: nio.api.PushRuleKind, rule_id: str, actions: Sequence[nio.events.account_data.PushAction]) → Union[nio.responses.SetPushRuleActionsResponse, nio.responses.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.
share_group_session(room_id: str, ignore_unverified_devices: bool = False) → Union[nio.responses.ShareGroupSessionResponse, nio.responses.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.

start_key_verification(device: nio.crypto.device.OlmDevice, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.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.
sync(timeout: Optional[int] = 0, sync_filter: Union[None, str, Dict[Any, Any]] = None, since: Optional[str] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None) → Union[nio.responses.SyncResponse, nio.responses.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.

sync_forever(timeout: Optional[int] = None, sync_filter: Union[None, str, Dict[Any, Any]] = None, since: Optional[str] = None, full_state: Optional[bool] = None, loop_sleep_time: Optional[int] = None, first_sync_filter: Union[None, str, Dict[Any, Any]] = None, set_presence: Optional[str] = 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”]
thumbnail(server_name: str, media_id: str, width: int, height: int, method: nio.api.ResizingMethod = <ResizingMethod.scale: 'scale'>, allow_remote: bool = True) → Union[nio.responses.ThumbnailResponse, nio.responses.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.
to_device(message: nio.event_builders.direct_messages.ToDeviceMessage, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.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.
update_device(device_id: str, content: Dict[str, str]) → Union[nio.responses.UpdateDeviceResponse, nio.responses.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)
update_receipt_marker(room_id: str, event_id: str, receipt_type: str = 'm.read') → None[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 (str) – The type of receipt to send. Currently, only m.read is supported by the Matrix specification.
upload(data_provider: Callable[[int, int], Union[str, pathlib.Path, bytes, Iterable[bytes], AsyncIterable[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader]], content_type: str = 'application/octet-stream', filename: Optional[str] = None, encrypt: bool = False, monitor: Optional[nio.monitors.TransferMonitor] = None, filesize: Optional[int] = None) → Tuple[Union[nio.responses.UploadResponse, nio.responses.UploadError], Optional[Dict[str, Any]]][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 occured, and the total number of server timeout exceptions that occured, 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.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)"
...        }
...    )
upload_filter(user_id: Optional[str] = None, event_fields: Optional[List[str]] = None, event_format: nio.api.EventFormat = <EventFormat.client: 'client'>, presence: Optional[Dict[str, Any]] = None, account_data: Optional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = None) → Union[nio.responses.UploadFilterResponse, nio.responses.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
whoami()[source]
class nio.TransferMonitor(total_size: int, on_transferred: Optional[Callable[[int], None]] = None, on_speed_changed: Optional[Callable[[float], 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 = 0.0
cancel = False
done

Whether the transfer is finished.

end_time = None
on_speed_changed = None
on_transferred = None
pause = False
percent_done

Percentage of completion for the transfer.

remaining

Number of remaining bytes to transfer.

remaining_time

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 = 10
spent_time

Time elapsed since the transfer started.

transferred

Number of currently transferred bytes.

HttpClient

class nio.HttpClient(homeserver, user='', device_id='', store_path='', config=None)[source]

Bases: nio.client.base_client.Client

accept_key_verification(transaction_id, tx_id=None)[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, tx_id=None)[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, tx_id=None)[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.HTTP: 0>)[source]
data_to_send()[source]
delete_devices(devices, auth=None)[source]
devices()[source]
disconnect()[source]
download(server_name, media_id, filename=None, allow_remote=True)[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=None)[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=None)[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=None)[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)[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)[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]
lag
login(password=None, device_name='', token=None)[source]
login_info()[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)[source]
logout(all_devices=False)[source]
next_response(max_events=0)[source]
parse_body(transport_response)[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)[source]

Pass received data to the client

request_room_key(event, tx_id=None)[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.private: 'private'>, alias=None, name=None, topic=None, room_version=None, federate=True, is_direct=False, preset=None, invite=(), initial_state=(), power_level_override=None)[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.
  • 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 immediatly 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)[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)[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: 0>, limit=10)[source]
room_put_state(room_id, event_type, body)[source]
room_read_markers(room_id, fully_read_event, read_event=None)[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, typing_state=True, timeout=30000)[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)[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)[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, ignore_missing_sessions=False, tx_id=None, ignore_unverified_devices=False)[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, tx_id=None)[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=None, filter=None, full_state=False)[source]
thumbnail(server_name, media_id, width, height, method=<ResizingMethod.scale: 'scale'>, allow_remote=True)[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, tx_id=None)[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, content)[source]

Rooms

class nio.rooms.MatrixRoom(room_id, own_user_id, encrypted=False)[source]

Bases: object

Represents a Matrix room.

add_member(user_id: str, display_name: Optional[str], avatar_url: Optional[str], invited: bool = False) → bool[source]
avatar_url(user_id: str) → Optional[str][source]

Get avatar url for a user.

Returns a matrix content URI, or None if the user has no avatar.

display_name

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

gen_avatar_url

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: nio.events.account_data.AccountDataEvent) → None[source]
handle_ephemeral_event(event: nio.events.ephemeral.EphemeralEvent) → None[source]
handle_event(event: nio.events.room_events.Event) → None[source]
handle_membership(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.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.

invited_count
is_group

Determine whether a room is an ad-hoc group (often a direct chat).

A group is an unnamed room with no canonical alias.

is_named

Determine whether a room is named.

A named room is a room with either the name or a canonical alias set.

joined_count
machine_name

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.

member_count
named_room_name() → Optional[str][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: nio.responses.RoomSummary) → None[source]
update_unread_notifications(unread: nio.responses.UnreadNotifications) → None[source]
user_name(user_id: str) → Optional[str][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.MatrixInvitedRoom(room_id: str, own_user_id: str)[source]

Bases: nio.rooms.MatrixRoom

handle_event(event: nio.events.room_events.Event) → None[source]
handle_membership(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.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.MatrixUser(user_id: str, display_name: Optional[str] = None, avatar_url: Optional[str] = None, power_level: int = 0, invited: bool = False, presence: str = 'offline', last_active_ago: Optional[int] = None, currently_active: Optional[bool] = None, status_msg: Optional[str] = None)[source]

Bases: object

disambiguated_name
name

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: Optional[str] = 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: nio.events.room_events.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
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: nio.events.room_events.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.
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: nio.events.room_events.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
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.
class nio.events.room_events.CallHangupEvent(source: Dict[str, Any], call_id: str, version: int)[source]

Bases: nio.events.room_events.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: nio.events.room_events.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
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.
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: 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 = 50
events_default = 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 = 50
kick = 50
redact = 50
state_default = 0
users_default = 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 = False
flattened(_prefix: str = '', _source: Optional[Dict[str, Any]] = None, _flat: Optional[Dict[str, Any]] = 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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
classmethod parse_decrypted_event(event_dict)[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)[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_key = None
session_id = None
transaction_id = None
verified = False
class nio.events.room_events.MegolmEvent(source: Dict[str, Any], device_id: str, ciphertext: str, algorithm: str, room_id: str = '')[source]

Bases: nio.events.room_events.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
as_key_request(user_id: str, requesting_device_id: str, request_id: Optional[str] = None, device_id: Optional[str] = None) → nio.event_builders.direct_messages.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.
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 = ''
class nio.events.room_events.PowerLevels(defaults: nio.events.room_events.DefaultLevels = <factory>, users: Dict[str, int] = <factory>, events: 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: Optional[str] = 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)[source]

Return whether a user has enough power to invite others.

can_user_kick(user_id: str, target_user_id: Optional[str] = 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, event_type='m.room.message')[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, event_type)[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.
get_message_event_required_level(event_type)[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)[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)[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.
class nio.events.room_events.PowerLevelsEvent(source: Dict[str, Any], power_levels: nio.events.room_events.PowerLevels)[source]

Bases: nio.events.room_events.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.
class nio.events.room_events.RedactedEvent(source: Dict[str, Any], type: str, redacter: str, reason: Optional[str])[source]

Bases: nio.events.room_events.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
event_type

Type of the event.

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.RedactionEvent(source: Dict[str, Any], redacts: str, reason: Optional[str] = None)[source]

Bases: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
reason = None
class nio.events.room_events.RoomAliasEvent(source: Dict[str, Any], canonical_alias: str)[source]

Bases: nio.events.room_events.Event

An event informing us about which alias should be preferred.

canonical_alias

The alias that is considered canonical.

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.room_events.RoomAvatarEvent(source: Dict[str, Any], avatar_url: str)[source]

Bases: nio.events.room_events.Event

Event holding a picture that is associated with the room.

avatar_url

The URL to the picture.

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.room_events.RoomCreateEvent(source: Dict[str, Any], creator: str, federate: bool = True, room_version: str = '1')[source]

Bases: nio.events.room_events.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
federate = True
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
room_version = '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: Optional[str] = None, thumbnail_key: Optional[Dict[KT, VT]] = None, thumbnail_hashes: Optional[Dict[KT, VT]] = None, thumbnail_iv: Optional[str] = None)[source]

Bases: nio.events.room_events.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: Optional[str] = None, thumbnail_key: Optional[Dict[KT, VT]] = None, thumbnail_hashes: Optional[Dict[KT, VT]] = None, thumbnail_iv: Optional[str] = None)[source]

Bases: nio.events.room_events.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: Optional[str] = None, thumbnail_key: Optional[Dict[KT, VT]] = None, thumbnail_hashes: Optional[Dict[KT, VT]] = None, thumbnail_iv: Optional[str] = None)[source]

Bases: nio.events.room_events.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: Optional[str] = None, thumbnail_key: Optional[Dict[KT, VT]] = None, thumbnail_hashes: Optional[Dict[KT, VT]] = None, thumbnail_iv: Optional[str] = None)[source]

Bases: nio.events.room_events.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
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
thumbnail_hashes = None
thumbnail_iv = None
thumbnail_key = None
thumbnail_url = None
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: Optional[str] = None, thumbnail_key: Optional[Dict[KT, VT]] = None, thumbnail_hashes: Optional[Dict[KT, VT]] = None, thumbnail_iv: Optional[str] = None)[source]

Bases: nio.events.room_events.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: nio.events.room_events.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: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
guest_access = 'forbidden'
class nio.events.room_events.RoomHistoryVisibilityEvent(source: Dict[str, Any], history_visibility: str = 'shared')[source]

Bases: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
history_visibility = 'shared'
class nio.events.room_events.RoomJoinRulesEvent(source: Dict[str, Any], join_rule: str = 'invite')[source]

Bases: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
join_rule = 'invite'
class nio.events.room_events.RoomMemberEvent(source: Dict[str, Any], state_key: str, membership: str, prev_membership: Optional[str], content: Dict[str, Any], prev_content: Optional[Dict[str, Any]] = None)[source]

Bases: nio.events.room_events.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”.

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
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
prev_content = None
class nio.events.room_events.RoomMessage(source: Dict[str, Any])[source]

Bases: nio.events.room_events.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)[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)[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: nio.events.room_events.RoomMessageMedia

A room message containing an audio clip.

class nio.events.room_events.RoomMessageEmote(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]

Bases: nio.events.room_events.RoomMessageFormatted

A room message coresponding 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: nio.events.room_events.RoomMessageMedia

A room message containing a generic file.

class nio.events.room_events.RoomMessageFormatted(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]

Bases: nio.events.room_events.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
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.RoomMessageImage(source: Dict[str, Any], url: str, body: str)[source]

Bases: nio.events.room_events.RoomMessageMedia

A room message containing an image.

class nio.events.room_events.RoomMessageMedia(source: Dict[str, Any], url: str, body: str)[source]

Bases: nio.events.room_events.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
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.RoomMessageNotice(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]

Bases: nio.events.room_events.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: Optional[str], format: Optional[str])[source]

Bases: nio.events.room_events.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: nio.events.room_events.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
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
type

Get the msgtype of the room message.

class nio.events.room_events.RoomMessageVideo(source: Dict[str, Any], url: str, body: str)[source]

Bases: nio.events.room_events.RoomMessageMedia

A room message containing a video clip.

class nio.events.room_events.RoomNameEvent(source: Dict[str, Any], name: str)[source]

Bases: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomTopicEvent(source: Dict[str, Any], topic: str)[source]

Bases: nio.events.room_events.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)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.StickerEvent(source: Dict[str, Any], body: str, url: str, content: Dict[str, Any])[source]

Bases: nio.events.room_events.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
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.UnknownEncryptedEvent(source: Dict[str, Any], type: str, algorithm: str)[source]

Bases: nio.events.room_events.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
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.UnknownEvent(source: Dict[str, Any], type: str)[source]

Bases: nio.events.room_events.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.

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[KT, VT], sender: str, canonical_alias: str)[source]

Bases: nio.events.invite_events.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
classmethod from_dict(parsed_dict)[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[KT, VT], 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)[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.
class nio.events.invite_events.InviteMemberEvent(source: Dict[KT, VT], sender: str, state_key: str, membership: str, prev_membership: str, content: dict, prev_content: dict = <factory>)[source]

Bases: nio.events.invite_events.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
classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.invite_events.InviteNameEvent(source: Dict[KT, VT], sender: str, name: str)[source]

Bases: nio.events.invite_events.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)[source]

Create an InviteEvent from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.

To-device Events

nio to-device events.

To-device events are events that are sent dirrectly 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: nio.events.to_device.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.
class nio.events.to_device.DummyEvent(source: Dict[str, Any], sender: str, sender_key: str, sender_device: str)[source]

Bases: nio.events.to_device.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.
class nio.events.to_device.EncryptedToDeviceEvent(source: Dict[str, Any], sender: str)[source]

Bases: nio.events.to_device.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: nio.events.to_device.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: nio.events.common.KeyVerificationAcceptMixin, nio.events.to_device.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: nio.events.common.KeyVerificationCancelMixin, nio.events.to_device.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: nio.events.common.KeyVerificationEventMixin, nio.events.to_device.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: nio.events.common.KeyVerificationKeyMixin, nio.events.to_device.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: nio.events.common.KeyVerificationMacMixin, nio.events.to_device.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: nio.events.common.KeyVerificationStartMixin, nio.events.to_device.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: Optional[str] = None)[source]

Bases: nio.events.to_device.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
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
transaction_id = 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: nio.events.to_device.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
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.
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: nio.events.to_device.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'.
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.RoomKeyRequestCancellation(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str)[source]

Bases: nio.events.to_device.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)[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.

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: str, user_id: str, timestamp: int)[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 acknowleged

Type:str
receipt_type

the type of receipt being received; this is commonly “m.read” for read receipts.

Type:str
user_id

the ID of the user who is acknowledging the event.

Type:str
timestamp

The timestamp the receipt was sent at.

Type:int
class nio.events.ephemeral.ReceiptEvent(receipts: List[nio.events.ephemeral.Receipt])[source]

Bases: nio.events.ephemeral.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. At the time of writing, all Receipts have a receipt_type of “m.read” and are read receipts, but this may change in the future.

receipts

The list of `Receipt`s in this event.

Type:List[Receipt]
classmethod from_dict(parsed_dict)[source]

Create an Ephemeral event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.ephemeral.TypingNoticeEvent(users: List[T])[source]

Bases: nio.events.ephemeral.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.

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)[source]
class nio.events.account_data.FullyReadEvent(event_id: str)[source]

Bases: nio.events.account_data.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
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.

as_value
classmethod from_dict(action: Union[str, Dict[str, Any]]) → nio.events.account_data.PushAction[source]
class nio.events.account_data.PushCoalesce[source]

Bases: nio.events.account_data.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.

as_value
class nio.events.account_data.PushCondition[source]

Bases: object

A condition for a push rule to match an event.

as_value
classmethod from_dict(condition: Dict[str, Any]) → nio.events.account_data.PushCondition[source]
matches(event: nio.events.room_events.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: nio.events.account_data.PushCondition

Require a message’s content.body to contain our display name.

This rule can only match unencrypted messages.

as_value
matches(event: nio.events.room_events.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: nio.events.account_data.PushAction

Prevents the matching event from generating a notification.

as_value
class nio.events.account_data.PushEventMatch(key: str, pattern: str)[source]

Bases: nio.events.account_data.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
as_value
matches(event: nio.events.room_events.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.PushNotify[source]

Bases: nio.events.account_data.PushAction

Cause the matching event to generate a notification.

as_value
class nio.events.account_data.PushRoomMemberCount(count: int, operator: str = '==')[source]

Bases: nio.events.account_data.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
as_value
classmethod from_dict(condition: Dict[str, Any]) → nio.events.account_data.PushRoomMemberCount[source]
matches(event: nio.events.room_events.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 = '=='
class nio.events.account_data.PushRule(kind: nio.api.PushRuleKind, id: str, default: bool, enabled: bool = True, pattern: str = '', conditions: List[nio.events.account_data.PushCondition] = <factory>, actions: 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 explicitely.

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]
enabled = True
classmethod from_dict(rule: Dict[str, Any], kind: nio.api.PushRuleKind) → nio.events.account_data.PushRule[source]
matches(event: nio.events.room_events.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 = ''
class nio.events.account_data.PushRulesEvent(global_rules: nio.events.account_data.PushRuleset = <factory>, device_rules: nio.events.account_data.PushRuleset = <factory>)[source]

Bases: nio.events.account_data.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
classmethod from_dict(event: Dict[str, Any]) → nio.events.account_data.PushRulesEvent[source]
class nio.events.account_data.PushRuleset(override: List[nio.events.account_data.PushRule] = <factory>, content: List[nio.events.account_data.PushRule] = <factory>, room: List[nio.events.account_data.PushRule] = <factory>, sender: List[nio.events.account_data.PushRule] = <factory>, underride: 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]
classmethod from_dict(ruleset: Dict[str, Any]) → nio.events.account_data.PushRuleset[source]
matching_rule(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → Optional[nio.events.account_data.PushRule][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.
class nio.events.account_data.PushSenderNotificationPermission(key: str)[source]

Bases: nio.events.account_data.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 refered to as the required level for the event's sender,
e.g. ``room``.
as_value
matches(event: nio.events.room_events.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: nio.events.account_data.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
valeu

The tweak’s value.

Type:Any
as_value
value = None
class nio.events.account_data.PushUnknownAction(action: Union[str, Dict[str, Any]])[source]

Bases: nio.events.account_data.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]]
as_value
class nio.events.account_data.PushUnknownCondition(condition: Dict[str, Any])[source]

Bases: nio.events.account_data.PushCondition

An unknown kind of push rule condition.

condition

The condition as a dict from the source event.

Type:Dict[str, Any]
as_value
class nio.events.account_data.TagEvent(tags: Dict[str, Optional[Dict[str, float]]])[source]

Bases: nio.events.account_data.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.

class nio.events.account_data.UnknownAccountDataEvent(type: str, content: Dict[str, Any])[source]

Bases: nio.events.account_data.AccountDataEvent

Account data event of an unknown type.

type

The type of the event.

Type:str
content

The content of the event.

Type:Dict
classmethod from_dict(event_dict)[source]

Construct an UnknownAccountDataEvent from a dictionary.

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 inital_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 instancied.

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[KT, VT])[source]

Bases: nio.event_builders.direct_messages.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[KT, VT], request_id: str, session_id: str, room_id: str, algorithm: str)[source]

Bases: nio.event_builders.direct_messages.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[KT, VT])[source]

Bases: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.event_builders.event_builder.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: nio.exceptions.ProtocolError

exception nio.exceptions.LocalTransportError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.MembersSyncError[source]

Bases: nio.exceptions.LocalProtocolError

exception nio.exceptions.OlmTrustError[source]

Bases: Exception

exception nio.exceptions.OlmUnverifiedDeviceError(unverified_device, *args)[source]

Bases: nio.exceptions.OlmTrustError

exception nio.exceptions.ProtocolError[source]

Bases: Exception

exception nio.exceptions.RemoteProtocolError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.RemoteTransportError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.SendRetryError[source]

Bases: nio.exceptions.LocalProtocolError

exception nio.exceptions.TransferCancelledError[source]

Bases: Exception

exception nio.exceptions.VerificationError[source]

Bases: Exception

Responses

class nio.responses.ContentRepositoryConfigResponse(upload_size: Optional[int] = 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) → Union[nio.responses.ContentRepositoryConfigResponse, nio.responses.ErrorResponse][source]
upload_size = None
class nio.responses.ContentRepositoryConfigError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response for a unsuccessful content repository config request.

class nio.responses.FileResponse(body: bytes, content_type: str, filename: Optional[str])[source]

A response representing a successful file content request.

body

The file’s content in bytes.

Type:bytes
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
classmethod from_data(data, content_type, filename=None)[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes) – The file’s content in bytes.
  • content_type (str) – The content MIME type of the file, e.g. “image/png”.
class nio.responses.DeleteDevicesAuthResponse(session: str, flows: Dict, params: Dict)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.DeleteDevicesResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.DeleteDevicesError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.DeletePushRuleError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = 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.datetime)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.DeviceList(changed: List[str], left: List[str])[source]
class nio.responses.DevicesResponse(devices: List[nio.responses.Device])[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.DevicesError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.DeviceOneTimeKeyCount(curve25519: Union[int, NoneType], signed_curve25519: Union[int, NoneType])[source]
class nio.responses.DiscoveryInfoError(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False)[source]
class nio.responses.DiscoveryInfoResponse(homeserver_url: str, identity_server_url: Optional[str] = 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]) → Union[nio.responses.DiscoveryInfoResponse, nio.responses.DiscoveryInfoError][source]
identity_server_url = None
class nio.responses.DownloadResponse(body: bytes, content_type: str, filename: Optional[str])[source]

A response representing a successful download request.

classmethod from_data(data: bytes, content_type: str, filename: Optional[str] = None)[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes) – The file’s content in bytes.
  • content_type (str) – The content MIME type of the file, e.g. “image/png”.
class nio.responses.DownloadError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing a unsuccessful download request.

class nio.responses.EnablePushRuleResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.EnablePushRuleError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ErrorResponse(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
retry_after_ms = None
soft_logout = False
status_code = None
class nio.responses.InviteInfo(invite_state: List)[source]
class nio.responses.JoinResponse(room_id: str)[source]
static create_error(parsed_dict)[source]
class nio.responses.JoinError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.JoinedMembersResponse(members: List[nio.responses.RoomMember], room_id: str)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str)[source]
class nio.responses.JoinedMembersError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
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])[source]
class nio.responses.JoinedRoomsError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing an unsuccessful joined rooms query.

class nio.responses.KeysClaimResponse(one_time_keys: Dict[Any, Any], failures: Dict[Any, Any], room_id: str = '')[source]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str = '')[source]
room_id = ''
class nio.responses.KeysClaimError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.KeysQueryResponse(device_keys: Dict, failures: Dict)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.KeysQueryError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.KeysUploadResponse(curve25519_count: int, signed_curve25519_count: int)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.KeysUploadError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RegisterResponse(user_id: str, device_id: str, access_token: str)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.LoginResponse(user_id: str, device_id: str, access_token: str)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.LoginError(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]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.LoginInfoError(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False)[source]
class nio.responses.LogoutResponse[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]

Create a response for logout response from server.

class nio.responses.LogoutError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Response[source]
elapsed
end_time = None
start_time = None
timeout = 0
transport_response = None
uuid = ''
class nio.responses.RoomBanResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomBanError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RoomCreateResponse(room_id: str)[source]

Response representing a successful create room request.

classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.RoomCreateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing a unsuccessful create room request.

class nio.responses.RoomInfo(timeline: nio.responses.Timeline, state: List, ephemeral: List, account_data: List, summary: Union[nio.responses.RoomSummary, NoneType] = None, unread_notifications: Union[nio.responses.UnreadNotifications, NoneType] = None)[source]
static parse_account_data(event_dict)[source]

Parse the account data dictionary and produce a list of events.

summary = None
unread_notifications = None
class nio.responses.RoomInviteResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomInviteError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RoomKickResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomKickError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RoomLeaveResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomLeaveError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[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.RoomForgetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomMember(user_id: str, display_name: str, avatar_url: str)[source]
class nio.responses.RoomMessagesResponse(room_id: str, chunk: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], start: str, end: str)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str)[source]
class nio.responses.RoomMessagesError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomGetStateResponse(events: List[T], 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]
classmethod from_dict(parsed_dict: List[Dict[Any, Any]], room_id: str)[source]
class nio.responses.RoomGetStateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state query.

class nio.responses.RoomGetStateEventResponse(content: Dict[KT, VT], 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
static create_error(parsed_dict, room_id)[source]
classmethod from_dict(parsed_dict: Dict[str, Any], event_type: str, state_key: str, room_id: str) → Union[nio.responses.RoomGetStateEventResponse, nio.responses.RoomGetStateEventError][source]
class nio.responses.RoomGetStateEventError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state query.

class nio.responses.RoomGetEventResponse[source]

A response indicating successful room get event request.

event

The requested event.

Type: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({}),_field_type=None)
classmethod from_dict(parsed_dict: Dict[str, Any]) → Union[nio.responses.RoomGetEventResponse, nio.responses.RoomGetEventError][source]
class nio.responses.RoomGetEventError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room get event 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.RoomPutStateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing an unsuccessful room state sending request.

class nio.responses.RoomRedactResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomRedactError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
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)[source]
class nio.responses.RoomResolveAliasError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing an unsuccessful room alias query.

class nio.responses.RoomSendResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomSendError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomSummary(invited_member_count: Union[int, NoneType] = None, joined_member_count: Union[int, NoneType] = None, heroes: Union[List[str], NoneType] = None)[source]
heroes = None
invited_member_count = None
joined_member_count = None
class nio.responses.RoomUnbanResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.RoomUnbanError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Rooms(invite: Dict[str, ForwardRef('InviteInfo')], join: Dict[str, ForwardRef('RoomInfo')], leave: Dict[str, ForwardRef('RoomInfo')])[source]
class nio.responses.SetPushRuleError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.SetPushRuleResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
class nio.responses.SetPushRuleActionsError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.SetPushRuleActionsResponse[source]
static create_error(parsed_dict: Dict[str, Any])[source]
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]])[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.
class nio.responses.ShareGroupSessionError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '', users_shared_with: Set[Tuple[str, str]] = <factory>)[source]

Response representing unsuccessful group sessions sharing request.

classmethod from_dict(parsed_dict, room_id, users_shared_with)[source]
class nio.responses.SyncResponse(next_batch: str, rooms: nio.responses.Rooms, device_key_count: nio.responses.DeviceOneTimeKeyCount, device_list: nio.responses.DeviceList, to_device_events: List[nio.events.to_device.ToDeviceEvent], presence_events: List[nio.events.presence.PresenceEvent], account_data_events: List[nio.events.account_data.AccountDataEvent] = <factory>)[source]
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.SyncError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Timeline(events: List, limited: bool, prev_batch: str)[source]
class nio.responses.UpdateDeviceResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.UpdateDeviceError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
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.RoomTypingError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing a unsuccessful room typing 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.RoomReadMarkersError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

A response representing a unsuccessful room read markers request.

class nio.responses.UploadResponse(content_uri: str)[source]

A response representing a successful upload request.

classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.UploadError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing a unsuccessful upload request.

class nio.responses.ProfileGetResponse(displayname: Optional[str] = None, avatar_url: Optional[str] = None, other_info: Dict[Any, 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 = None
displayname = None
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.ProfileGetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetDisplayNameResponse(displayname: Optional[str] = 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 = None
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.ProfileGetDisplayNameError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetDisplayNameResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.ProfileSetDisplayNameError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetAvatarResponse(avatar_url: Optional[str] = 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 = None
classmethod from_dict(parsed_dict: Dict[Any, Any])[source]
class nio.responses.ProfileGetAvatarError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetAvatarResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.ProfileSetAvatarError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.PresenceGetResponse(user_id: str, presence: str, last_active_ago: Optional[int], currently_active: Optional[bool], status_msg: Optional[str])[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
classmethod from_dict(parsed_dict: Dict[Any, Any], user_id: str) → Union[nio.responses.PresenceGetResponse, nio.responses.PresenceGetError][source]
class nio.responses.PresenceGetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

Response representing a unsuccessful get presence request.

class nio.responses.PresenceSetResponse[source]

Response representing a successful set presence request.

static create_error(parsed_dict)[source]
class nio.responses.PresenceSetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

Response representing a unsuccessful set presence 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
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.
class nio.responses.RoomKeyRequestError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

Response representing a failed room key request.

class nio.responses.ThumbnailResponse(body: bytes, content_type: str, filename: Optional[str])[source]

A response representing a successful thumbnail request.

classmethod from_data(data: bytes, content_type: str, filename: Optional[str] = None)[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes) – The file’s content in bytes.
  • content_type (str) – The content MIME type of the file, e.g. “image/png”.
class nio.responses.ThumbnailError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

A response representing a unsuccessful thumbnail request.

class nio.responses.ToDeviceResponse(to_device_message: nio.event_builders.direct_messages.ToDeviceMessage)[source]

Response representing a successful room key request.

classmethod from_dict(parsed_dict, message)[source]

Create a ToDeviceResponse from a json response.

class nio.responses.ToDeviceError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, to_device_message: Optional[nio.event_builders.direct_messages.ToDeviceMessage] = None)[source]

Response representing a unsuccessful room key request.

classmethod from_dict(parsed_dict, message)[source]
to_device_message = None
class nio.responses.RoomContextResponse(room_id: str, start: str, end: str, event: Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent, None], events_before: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], events_after: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], state: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.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]
classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str)[source]
class nio.responses.RoomContextError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

Response representing a unsuccessful room context request.

class nio.responses.UploadFilterError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = 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
classmethod from_dict(parsed_dict: Dict[Any, Any]) → Union[nio.responses.UploadFilterResponse, nio.responses.UploadFilterError][source]
class nio.responses.UpdateReceiptMarkerError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.UpdateReceiptMarkerResponse[source]
static create_error(parsed_dict)[source]

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.

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)[source]

Add an outgoing key request to the store.

blacklist_device(device)[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)[source]

Delete the a encrypted room from the store.

ignore_device(device)[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)[source]

Mark a list of devices as ignored.

This is a more efficient way to mark multiple devices as ignored.

Parameters:device (list[OlmDevice]) – A list of OlmDevices that will be marked as ignored.
is_device_blacklisted(device)[source]

Check if a device is blacklisted.

Parameters:device (OlmDevice) – The device that will be checked if it’s blacklisted.
is_device_ignored(device)[source]

Check if a device is ignored.

Parameters:device (OlmDevice) – The device that will be checked if it’s ignored.
is_device_verified(device)[source]

Check if a device is verified.

Parameters:device (OlmDevice) – The device that will be checked if it’s verified.
load_account()[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()[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()[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()[source]

Load all Olm sessions from the database.

Returns:SessionStore object, containing all the loaded sessions.
remove_outgoing_key_request(key_request)[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(sender_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)[source]

Save the given token

unblacklist_device(device)[source]

Unmark a device as blacklisted.

Parameters:device (OlmDevice) – The device that will be unmarked as blacklisted
unignore_device(device)[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)[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)[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: nio.store.database.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: nio.store.database.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: nio.store.database.SqliteStore

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. 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 normaly 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[nio.crypto.device.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: nio.crypto.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) → Optional[nio.crypto.device.OlmDevice][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,
  • a curve25519 public key. (usually) –
items()[source]

List of tuples in the form (user id, dict(device_id, OlmDevice).

users

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: nio.crypto.device.TrustState = <TrustState.unset: 0>)[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 pasing 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.

blacklisted

Is the device blacklisted.

curve25519

The curve25519 key of the device.

ed25519

The ed25519 fingerprint key of the device.

id

The device id.

Same as the device_id attribute.

ignored

Is the device ignored.

verified

Is the device verified.

class nio.crypto.TrustState[source]

The device trust state.

An Enum holding differing values that a device trust state can be in.

class nio.crypto.Sas(own_user: str, own_device: str, own_fp_key: str, other_olm_device: nio.crypto.device.OlmDevice, transaction_id: str = None, short_auth_string: Optional[List[str]] = None, mac_methods: Optional[List[str]] = None)[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() → nio.event_builders.direct_messages.ToDeviceMessage[source]

Create a content dictionary to accept the verification offer.

cancel()[source]

Cancel the authentication process.

canceled

Is the verification request canceled.

classmethod from_key_verification_start(own_user, own_device, own_fp_key, other_olm_device, event)[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() → nio.event_builders.direct_messages.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() → nio.event_builders.direct_messages.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() → nio.event_builders.direct_messages.ToDeviceMessage[source]

Create a dictionary containing our public key.

start_verification() → nio.event_builders.direct_messages.ToDeviceMessage[source]

Create a content dictionary to start the verification.

timed_out

Did the verification process time out.

verified

Is the device verified and the request done.