<<

nio Documentation Release 0.18.6

Damir Jelic´

Sep 17, 2021

Contents

1 Documentation 3

2 Features 5

3 Installation 7

4 Examples 9

5 Api Documentation 11 5.1 API...... 11 5.2 Examples...... 124 5.3 Contributing...... 145

6 Indices and tables 147

Python Module Index 149

Index 151

i ii nio Documentation, Release 0.18.6

nio is a multilayered Matrix client library. The underlying base layer doesn’t do any network IO on its own, but on top of that is a full fledged batteries-included asyncio layer using aiohttp. File IO is only done if you enable end-to-end encryption (E2EE).

Contents 1 nio Documentation, Release 0.18.6

2 Contents CHAPTER 1

Documentation

The full API documentation for nio can be found at https://matrix-nio.readthedocs.io

3 nio Documentation, Release 0.18.6

4 Chapter 1. Documentation CHAPTER 2

Features

nio has most of the features you’d expect in a Matrix library, but it’s still a work in progress. • transparent end-to-end encryption (EE2E) • encrypted file uploads & downloads • manual and emoji verification • custom authentication types • well-integrated type system • kick, ban and unban • typing notifications • message redaction • token based login • user registration • read receipts • live syncing • m.tags • python 2.7 support • cross-signing support • user deactivation (#112) • in-room emoji verification • room upgrades and m.room.tombstone events (#47)

5 nio Documentation, Release 0.18.6

6 Chapter 2. Features CHAPTER 3

Installation

To install nio, simply use pip:

$ pip install matrix-nio

Note that this installs nio without end-to-end encryption support. For e2ee support, python-olm is needed which requires the libolm C library (version 3.x). On Debian and Ubuntu one can use apt-get to install package libolm-dev. On Fedora one can use dnf to install package libolm-devel. On MacOS one can use brew to install package libolm. Make sure version 3 is installed. After libolm has been installed, the e2ee enabled version of nio can be installed using pip:

$ pip install "matrix-nio[e2e]"

Additionally, a docker image with the e2ee enabled version of nio is provided in the docker/ directory.

7 nio Documentation, Release 0.18.6

8 Chapter 3. Installation CHAPTER 4

Examples

For examples of how to use nio, and how others are using it, read the docs

9 nio Documentation, Release 0.18.6

10 Chapter 4. Examples CHAPTER 5

Api Documentation

5.1 API

This document details the API of nio.

5.1.1 Api class nio.Api Matrix API class. Static methods reflecting the Matrix REST API. static content_repository_config(access_token: str) → Tuple[str, str] 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) 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 au- thentication API.

11 nio Documentation, Release 0.18.6

static delete_pushrule(access_token: str, scope: str, kind: nio.api.PushRuleKind, rule_id: str) → Tuple[str, str] 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) 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] 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) 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] 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) Convert a matrix content URI to a encrypted mxc URI.

12 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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 decryp- tion 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] 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) 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) 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) 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) Claim one-time keys for use in Olm pre-key . Returns the HTTP method, HTTP path and data for the request.

5.1. API 13 nio Documentation, Release 0.18.6

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) 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) 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) 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 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] Get the homeserver’s supported login types Returns the HTTP method and HTTP path for the request. static login_raw(auth_dict) 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 https://matrix.org/docs/spec/client_server/r0.6.0#authentication-types

14 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

for detailed documentation

Example

>>> auth_dict={ >>> "type":"m.login.password", >>> "identifier":{ >>> "type":"m.id.thirdparty", >>> "medium":"email", >>> "address":"[email protected]" >>> }, >>> "password":"PASSWORDABCD", >>> "initial_device_display_name":"Test user" >>> }

static logout(access_token, all_devices=False) 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) Turn a mimetype into a matrix message type. static mxc_to_http(mxc, homeserver=None) Convert a matrix content URI to a HTTP URI. static profile_get(user_id: str, access_token: str = None) → Tuple[str, str] 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) 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) Get display name. Returns the HTTP method and HTTP path for the request. Parameters • user_id (str) – User id to get display name for.

5.1. API 15 nio Documentation, Release 0.18.6

• 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) 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) 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=”) 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] 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) 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.

16 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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=, alias=None, name=None, topic=None, room_version=None, feder- ate=True, is_direct=False, preset=None, invite=(), initial_state=(), power_level_override=None) 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 cre- ated. 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) 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.

5.1. API 17 nio Documentation, Release 0.18.6

static room_get_event(access_token: str, room_id: str, event_id: str) → Tuple[str, str] 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) 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=”) 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) 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) 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.

18 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

static room_leave(access_token, room_id) 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, di- rection: nio.api.MessageDirection = , limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None) 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=”) 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) 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.

5.1. API 19 nio Documentation, Release 0.18.6

static room_redact(access_token, room_id, event_id, tx_id, reason=None) 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) 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) 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) 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] 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.

20 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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) 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: Se- quence[PushAction] = (), conditions: Optional[Sequence[PushCondition]] = None, pattern: Optional[str] = None) → Tuple[str, str, str] 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 con- tent. 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] Set the actions for an existing built-in or user-created push rule. Unlike set_pushrule, this method can edit built-in server rules.

5.1. API 21 nio Documentation, Release 0.18.6

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, fil- ter: Union[None, str, Dict[Any, Any]] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None) 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 au- tomatically 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”, “unavail- able”] static thumbnail(server_name, media_id, width, height, method=, allow_remote=True) 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.

22 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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) Turn a dictionary into a canonical json string. static to_device(access_token, event_type, content, tx_id) 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) Turn a dictionary into a json string. static update_device(access_token: str, device_id: str, content: Dict[str, str]) → Tuple[str, str, str] 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] 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) 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.

5.1. API 23 nio Documentation, Release 0.18.6

• 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 = , presence: Optional[Dict[str, Any]] = None, account_data: Op- tional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = None) → Tuple[str, str, str] 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 cor- responds 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) 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.

5.1.2 nio Clients class nio.ClientConfig(store: Optional[Type[MatrixStore]] = , encryption_enabled: bool = True, store_name: str = ”, pickle_key: str = ’DEFAULT_KEY’, store_sync_tokens: bool = False) 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

24 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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 in- stance. 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.

5.1. API 25 nio Documentation, Release 0.18.6

add_ephemeral_callback(callback: Callable[[nio.rooms.MatrixRoom, nio.events.ephemeral.EphemeralEvent], None], filter: Union[Type[nio.events.ephemeral.EphemeralEvent], Tu- ple[Type[nio.events.ephemeral.EphemeralEvent], ...]]) → None 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], Tu- ple[Type[nio.events.room_events.Event], ...]]) → None 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 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]]]) 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.

26 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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 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], Tu- ple[Type[nio.events.to_device.ToDeviceEvent], ...]]) → None 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 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 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 Confirm that the short auth string of a key verification matches.

5.1. API 27 nio Documentation, Release 0.18.6

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

28 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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 recom- mended 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] 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) 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.

5.1. API 29 nio Documentation, Release 0.18.6

• 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]] 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 en- crypted.

get_users_for_key_claiming() → Dict[str, List[str]] 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 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) 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) 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() 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.

30 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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]] 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) 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 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]] 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.

5.1. API 31 nio Documentation, Release 0.18.6

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 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 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 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 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: Op- tional[str] = ”, config: Optional[nio.client.async_client.AsyncClientConfig] = None, ssl: Optional[bool] = None, proxy: Optional[str] = None) 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 in- stance. If not set the server will provide one after log in.

32 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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 con- nection. Supports SOCKS4(a), SOCKS5, HTTP (tunneling) via an URL like e.g. ‘socks5://user:[email protected]: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] Accept a key verification start event.

5.1. API 33 nio Documentation, Release 0.18.6

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) 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 argu- ment. • 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: Op- tional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError] 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() Close the underlying http session. confirm_short_auth_string(transaction_id: str, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError] 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] Get the content repository configuration, such as upload limits.

34 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

Calls receive_response() to update the client state if necessary. Returns either a ContentRepositoryConfigResponse if the request was successful or a ContentReposito- ryConfigError if there was an error with the request. create_matrix_response(response_class: Type[CT_co], transport_response: aio- http.client_reqrep.ClientResponse, data: Tuple[Any, ...] = None) → nio.responses.Response 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] 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 authentica- tion 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] 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

5.1. API 35 nio Documentation, Release 0.18.6

• 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] 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] 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] 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.

36 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

enable_pushrule(scope: str, kind: nio.api.PushRuleKind, rule_id: str, en- able: bool) → Union[nio.responses.EnablePushRuleResponse, nio.responses.EnablePushRuleError] 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) 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 recom- mended to specify it unless absolutely sure of the consequences. get_avatar(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetAvatarResponse, nio.responses.ProfileGetAvatarError] 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] 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 ProfileGetDisplay- NameError 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] Get a user’s presence state.

5.1. API 37 nio Documentation, Release 0.18.6

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] 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 import_keys(infile: str, passphrase: str) 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] 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] 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.

38 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

joined_rooms() → Union[nio.responses.JoinedRoomsResponse, nio.responses.JoinedRoomsError] 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] 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] 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] 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] 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.

5.1. API 39 nio Documentation, Release 0.18.6

login_info() → Union[nio.responses.LoginInfoResponse, nio.responses.LoginInfoError] 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] 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 https://matrix.org/docs/spec/client_server/r0.6.0#authentication-types for detailed documentation

Example

>>> auth_dict={ >>> "type":"m.login.password", >>> "identifier":{ >>> "type":"m.id.thirdparty", >>> "medium":"email", >>> "address":"[email protected]" >>> }, >>> "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] 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] Convert a matrix content URI to a HTTP URI. parse_body(transport_response: aiohttp.client_reqrep.ClientResponse) → Dict[Any, Any] 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 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).

40 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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=”) 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] 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] 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] 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.

5.1. API 41 nio Documentation, Release 0.18.6

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 = , alias: Op- tional[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: Se- quence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Optional[Dict[str, Any]] = None) → Union[nio.responses.RoomCreateResponse, nio.responses.RoomCreateError] 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 cre- ated. 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.

42 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

room_forget(room_id: str) → Union[nio.responses.RoomForgetResponse, nio.responses.RoomForgetError] 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] 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] 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] 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] 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.

5.1. API 43 nio Documentation, Release 0.18.6

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] 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] 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 = , limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None) → Union[nio.responses.RoomMessagesResponse, nio.responses.RoomMessagesError] 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.

44 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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] 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) 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] Strip information out of an event. Calls receive_response() to update the client state if necessary.

5.1. API 45 nio Documentation, Release 0.18.6

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] 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) 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 un- verified 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] 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

46 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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] 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]]) 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], AsyncIter- able[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader] = None, head- ers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None) → aiohttp.client_reqrep.ClientResponse 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 Trace- Config context • timeout (int, optional) – How many seconds the request has before raising asyn- cio.TimeoutError. Overrides AsyncClient.config.request_timeout if not None. send_to_device_messages() → List[Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError]] Send out outgoing to-device messages. Automatically called by sync_forever(). set_avatar(avatar_url: str) → Union[nio.responses.ProfileSetAvatarResponse, nio.responses.ProfileSetAvatarError] 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.

5.1. API 47 nio Documentation, Release 0.18.6

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] 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 ProfileSetDisplay- NameError 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] 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] 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.

48 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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 con- tent. 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] 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 SetPushRuleActionsRe- sponse 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.

5.1. API 49 nio Documentation, Release 0.18.6

• 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] 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. Ig- nored 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] 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 interac- tive key verification process. sync(timeout: Optional[int] = 0, sync_filter: Union[None, str, Dict[Any, Any]] = None, since: Op- tional[str] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None) → Union[nio.responses.SyncResponse, nio.responses.SyncError] 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 en- cryption 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.

50 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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) 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 = , allow_remote: bool = True) → Union[nio.responses.ThumbnailResponse, nio.responses.ThumbnailError] Get the thumbnail of a file from the content repository. The actual thumbnail may be larger than the size specified. This method ignores Async- Client.config.request_timeout and uses 0.

5.1. API 51 nio Documentation, Release 0.18.6

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] 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] 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 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 UpdateReceiptMarker- Error if there was an error with the request.

52 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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], AsyncIt- erable[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader]], con- tent_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], Op- tional[Dict[str, Any]]] 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.

5.1. API 53 nio Documentation, Release 0.18.6

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 = , presence: Optional[Dict[str, Any]] = None, account_data: Op- tional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = None) → Union[nio.responses.UploadFilterResponse, nio.responses.UploadFilterError] 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 cor- responds 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

54 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

whoami() 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) 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

5.1. API 55 nio Documentation, Release 0.18.6

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) Bases: nio.client.base_client.Client accept_key_verification(transaction_id, tx_id=None) 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) 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) 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=) data_to_send() delete_devices(devices, auth=None) devices() disconnect() download(server_name, media_id, filename=None, allow_remote=True) 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.

56 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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) 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) 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) 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) join(room_id) 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) keys_claim(room_id) keys_query() 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() lag login(password=None, device_name=”, token=None)

5.1. API 57 nio Documentation, Release 0.18.6

login_info() 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) logout(all_devices=False) next_response(max_events=0) parse_body(transport_response) 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) Pass received data to the client request_room_key(event, tx_id=None) 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=, alias=None, name=None, topic=None, room_version=None, federate=True, is_direct=False, preset=None, invite=(), ini- tial_state=(), power_level_override=None) 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:

58 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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 cre- ated. 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) 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) room_kick(room_id, user_id, reason=None) room_leave(room_id) 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=, limit=10) room_put_state(room_id, event_type, body) room_read_markers(room_id, fully_read_event, read_event=None) 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.

5.1. API 59 nio Documentation, Release 0.18.6

• 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) 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) room_typing(room_id, typing_state=True, timeout=30000) 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) 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) 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, ig- nore_unverified_devices=False) 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. Ig- nored devices will still receive encryption keys for messages but they won’t be marked as verified.

60 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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 interac- tive key verification process. sync(timeout=None, filter=None, full_state=False) thumbnail(server_name, media_id, width, height, method=, al- low_remote=True) 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) 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)

5.1.3 Rooms class nio.rooms.MatrixRoom(room_id, own_user_id, encrypted=False) Bases: object Represents a Matrix room. add_member(user_id: str, display_name: Optional[str], avatar_url: Optional[str], invited: bool = False) → bool avatar_url(user_id: str) → Optional[str] Get avatar url for a user. Returns a matrix content URI, or None if the user has no avatar.

5.1. API 61 nio Documentation, Release 0.18.6

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 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] Get if room is empty, ID for listed users and the N others count. handle_account_data(event: nio.events.account_data.AccountDataEvent) → None handle_ephemeral_event(event: nio.events.ephemeral.EphemeralEvent) → None handle_event(event: nio.events.room_events.Event) → None handle_membership(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.InviteMemberEvent]) → bool 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] Return the name of the room if it’s a named room, otherwise None. remove_member(user_id: str) → bool update_summary(summary: nio.responses.RoomSummary) → None update_unread_notifications(unread: nio.responses.UnreadNotifications) → None

62 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

user_name(user_id: str) → Optional[str] 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 “ ()” if there is more than one user with same display name. user_name_clashes(name: str) → List[str] Get a list of users that have same display name. class nio.rooms.MatrixInvitedRoom(room_id: str, own_user_id: str) Bases: nio.rooms.MatrixRoom handle_event(event: nio.events.room_events.Event) → None handle_membership(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.InviteMemberEvent]) → bool 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: Op- tional[str] = None, power_level: int = 0, invited: bool = False, pres- ence: str = ’offline’, last_active_ago: Optional[int] = None, cur- rently_active: Optional[bool] = None, status_msg: Optional[str] = None) Bases: object disambiguated_name name

5.1.4 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) 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

5.1. API 63 nio Documentation, Release 0.18.6

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) 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

64 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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]) 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) 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]]) 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) 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) Bases: nio.events.room_events.Event Base Class for Matrix call signalling events. call_id The unique identifier of the call.

5.1. API 65 nio Documentation, Release 0.18.6

Type str version The version of the VoIP specification this message adheres to. Type int static parse_event(event_dict) 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) Bases: nio.events.room_events.CallEvent An event representing the end of a VoIP call. Sent by either party to 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) 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]) 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) 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] = ) Bases: object

66 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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 De- faultLevels object. invite = 50 kick = 50 redact = 50 state_default = 0 users_default = 0

5.1. API 67 nio Documentation, Release 0.18.6 class nio.events.room_events.Event(source: Dict[str, Any]) 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] Return a flattened version of the source dict with dotted keys.

68 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) Create an Event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. classmethod parse_decrypted_event(event_dict) 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) 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) 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 = ”) 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

5.1. API 69 nio Documentation, Release 0.18.6

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: Op- tional[str] = None, device_id: Optional[str] = None) → nio.event_builders.direct_messages.RoomKeyRequestMessage 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.

70 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

• 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) 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 = , users: Dict[str, int] = , events: Dict[str, int] = ) 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 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) Return whether a user has enough power to invite others. can_user_kick(user_id: str, target_user_id: Optional[str] = None) → bool 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) Return whether user has enough power to send a type of notification. can_user_redact(user_id: str) Return whether a user has enough power to redact other user’s events. can_user_send_message(user_id, event_type=’m.room.message’) 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.

5.1. API 71 nio Documentation, Release 0.18.6

can_user_send_state(user_id, event_type) 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) 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 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) 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) 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) 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) 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) Create an Event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event.

72 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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

5.1. API 73 nio Documentation, Release 0.18.6

Parameters parsed_dict (dict) – The dictionary representation of the event. class nio.events.room_events.RoomAvatarEvent(source: Dict[str, Any], avatar_url: str) 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) 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, feder- ate: bool = True, room_version: str = ’1’) 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) 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) Bases: nio.events.room_events.RoomEncryptedMedia A room message containing an audio clip where the file is encrypted.

74 Chapter 5. Api Documentation nio Documentation, Release 0.18.6 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) 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) 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) 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

5.1. API 75 nio Documentation, Release 0.18.6

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) 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) 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]) Bases: nio.events.room_events.Event An event signaling that encryption has been enabled in a room. classmethod from_dict(parsed_dict) 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’) Bases: nio.events.room_events.Event Event signaling whether guest users are allowed to join rooms.

76 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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’) 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 acces- sible, 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) 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’) 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) Create an Event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. join_rule = 'invite'

5.1. API 77 nio Documentation, Release 0.18.6

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) 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) 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]) 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) 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) 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.

78 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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, for- matted_body: Optional[str], format: Op- tional[str]) 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) 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], for- mat: Optional[str]) 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) Create an Event from a dictionary.

5.1. API 79 nio Documentation, Release 0.18.6

Parameters parsed_dict (dict) – The dictionary representation of the event. class nio.events.room_events.RoomMessageImage(source: Dict[str, Any], url: str, body: str) 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) 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) 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, format- ted_body: Optional[str], format: Op- tional[str]) 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, for- matted_body: Optional[str], format: Op- tional[str]) 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

80 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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

5.1. API 81 nio Documentation, Release 0.18.6

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) 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, con- tent: Dict[str, Any]) 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) 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) 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

82 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

classmethod from_dict(event_dict) 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) 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) 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) 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) 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) 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.

5.1. API 83 nio Documentation, Release 0.18.6

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) Create an InviteEvent from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. classmethod parse_event(event_dict) 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 = ) 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) Create an InviteEvent from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event.

84 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

class nio.events.invite_events.InviteNameEvent(source: Dict[KT, VT], sender: str, name: str) 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) 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, re- questing_device_id: str, request_id: str) 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) 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) 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.

5.1. API 85 nio Documentation, Release 0.18.6

Type str classmethod from_dict(event_dict, sender, sender_key) 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) Bases: nio.events.to_device.ToDeviceEvent class nio.events.to_device.ForwardedRoomKeyEvent(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, ses- sion_id: str, algorithm: str) 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) 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]) 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.

86 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) 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) 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) 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) 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, trans- action_id: str, key: str) Bases: nio.events.common.KeyVerificationKeyMixin, nio.events.to_device. KeyVerificationEvent

5.1. API 87 nio Documentation, Release 0.18.6

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) 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, trans- action_id: str, mac: Dict[str, str], keys: str) 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) 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]) 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

88 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) under- stands. Type list classmethod from_dict(parsed_dict) 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, ci- phertext: Dict[str, Any], transaction_id: Optional[str] = None) 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) Create an Event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. transaction_id = None

5.1. API 89 nio Documentation, Release 0.18.6

class nio.events.to_device.RoomKeyEvent(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, session_id: str, algorithm: str) 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) 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, request- ing_device_id: str, request_id: str, algorithm: str, room_id: str, sender_key: str, session_id: str) 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'.

90 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

classmethod from_dict(parsed_dict) 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, request- ing_device_id: str, re- quest_id: str) Bases: nio.events.to_device.BaseRoomKeyRequest Event signaling that a previous room key request was canceled. classmethod from_dict(parsed_dict) 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) 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) Create an Event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. classmethod parse_encrypted_event(event_dict) 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) 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.

5.1. API 91 nio Documentation, Release 0.18.6

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 Bases: object Base class for ephemeral events. classmethod from_dict(parsed_dict) Create an Ephemeral event from a dictionary. Parameters parsed_dict (dict) – The dictionary representation of the event. classmethod parse_event(event_dict) 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) 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]) 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]

92 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

classmethod from_dict(parsed_dict) 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]) 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) 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 Bases: object Abstract class for account data events. classmethod parse_event(event_dict) class nio.events.account_data.FullyReadEvent(event_id: str) 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) Construct a FullyReadEvent from a dictionary. class nio.events.account_data.PushAction 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 class nio.events.account_data.PushCoalesce Bases: nio.events.account_data.PushAction Causes multiple matching events to be joined into a single notification.

5.1. API 93 nio Documentation, Release 0.18.6

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 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 matches(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → bool 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 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 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 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) 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

94 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

as_value matches(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → bool 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 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 = ’==’) 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 matches(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → bool 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] = , actions: List[nio.events.account_data.PushAction] = ) Bases: object Rule stating how to notify the user for events matching some conditions. kind The kind of rule this is. Type PushRuleKind

5.1. API 95 nio Documentation, Release 0.18.6

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 matches(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → bool 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 = , device_rules: nio.events.account_data.PushRuleset = ) 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

96 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

device_rules Rulesets applying to current device only Type PushRuleset classmethod from_dict(event: Dict[str, Any]) → nio.events.account_data.PushRulesEvent class nio.events.account_data.PushRuleset(override: List[nio.events.account_data.PushRule] = , content: List[nio.events.account_data.PushRule] = , room: List[nio.events.account_data.PushRule] = , sender: List[nio.events.account_data.PushRule] = , underride: List[nio.events.account_data.PushRule] = ) 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 matching_rule(event: nio.events.room_events.Event, room: MatrixRoom, display_name: str) → Optional[nio.events.account_data.PushRule] 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) Bases: nio.events.account_data.PushCondition Require the event’s sender to have a high enough power level.

5.1. API 97 nio Documentation, Release 0.18.6

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

98 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

class nio.events.account_data.PushUnknownCondition(condition: Dict[str, Any]) 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]]]) 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) Construct a TagEvent from a dictionary. class nio.events.account_data.UnknownAccountDataEvent(type: str, content: Dict[str, Any]) 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) Construct an UnknownAccountDataEvent from a dictionary.

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

5.1. API 99 nio Documentation, Release 0.18.6 class nio.event_builders.EventBuilder Bases: object The base class for event builders, should not be instancied. as_dict() 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, re- cipient_device: str, content: Dict[KT, VT]) 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, re- cipient: str, re- cipient_device: str, content: Dict[KT, VT], request_id: str, session_id: str, room_id: str, algorithm: str) 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]) Bases: nio.event_builders.event_builder.EventBuilder A to-device message that can be sent to the homeserver. type The type of the message.

100 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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() 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) 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() Format the event as a dictionary, to be sent to the server. class nio.event_builders.state_events.ChangeHistoryVisibilityBuilder(visibility: str) 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.

5.1. API 101 nio Documentation, Release 0.18.6

• 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() Format the event as a dictionary, to be sent to the server. class nio.event_builders.state_events.ChangeJoinRulesBuilder(rule: str) 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() Format the event as a dictionary, to be sent to the server. class nio.event_builders.state_events.ChangeNameBuilder(name: str) 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() Format the event as a dictionary, to be sent to the server. class nio.event_builders.state_events.ChangeTopicBuilder(topic: str) 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() 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’, rota- tion_ms: int = 604800000, rota- tion_msgs: int = 100) 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.

102 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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() Format the event as a dictionary, to be sent to the server.

5.1.6 Exceptions exception nio.exceptions.EncryptionError Bases: Exception exception nio.exceptions.GroupEncryptionError Bases: Exception exception nio.exceptions.LocalProtocolError Bases: nio.exceptions.ProtocolError exception nio.exceptions.LocalTransportError Bases: nio.exceptions.ProtocolError exception nio.exceptions.MembersSyncError Bases: nio.exceptions.LocalProtocolError exception nio.exceptions.OlmTrustError Bases: Exception exception nio.exceptions.OlmUnverifiedDeviceError(unverified_device, *args) Bases: nio.exceptions.OlmTrustError exception nio.exceptions.ProtocolError Bases: Exception exception nio.exceptions.RemoteProtocolError Bases: nio.exceptions.ProtocolError exception nio.exceptions.RemoteTransportError Bases: nio.exceptions.ProtocolError exception nio.exceptions.SendRetryError Bases: nio.exceptions.LocalProtocolError exception nio.exceptions.TransferCancelledError Bases: Exception exception nio.exceptions.VerificationError Bases: Exception

5.1. API 103 nio Documentation, Release 0.18.6

5.1.7 Responses class nio.responses.ContentRepositoryConfigResponse(upload_size: Optional[int] = None) 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] upload_size = None class nio.responses.ContentRepositoryConfigError(message: str, status_code: Op- tional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) A response for a unsuccessful content repository config request. class nio.responses.FileResponse(body: bytes, content_type: str, filename: Optional[str]) 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) 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)

classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.DeleteDevicesResponse

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

104 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

class nio.responses.DeletePushRuleResponse

static create_error(parsed_dict: Dict[str, Any]) class nio.responses.Device(id: str, display_name: str, last_seen_ip: str, last_seen_date: date- time.datetime)

classmethod from_dict(parsed_dict) class nio.responses.DeviceList(changed: List[str], left: List[str]) class nio.responses.DevicesResponse(devices: List[nio.responses.Device])

classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.DevicesError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.DeviceOneTimeKeyCount(: Union[int, NoneType], signed_curve25519: Union[int, NoneType]) class nio.responses.DiscoveryInfoError(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False) class nio.responses.DiscoveryInfoResponse(homeserver_url: str, identity_server_url: Op- tional[str] = None) 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] identity_server_url = None class nio.responses.DownloadResponse(body: bytes, content_type: str, filename: Optional[str]) A response representing a successful download request. classmethod from_data(data: bytes, content_type: str, filename: Optional[str] = None) 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) A response representing a unsuccessful download request. class nio.responses.EnablePushRuleResponse

5.1. API 105 nio Documentation, Release 0.18.6

static create_error(parsed_dict: Dict[str, Any]) class nio.responses.EnablePushRuleError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.ErrorResponse(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False)

classmethod from_dict(parsed_dict: Dict[Any, Any]) retry_after_ms = None soft_logout = False status_code = None class nio.responses.InviteInfo(invite_state: List) class nio.responses.JoinResponse(room_id: str)

static create_error(parsed_dict) class nio.responses.JoinError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.JoinedMembersResponse(members: List[nio.responses.RoomMember], room_id: str)

classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) class nio.responses.JoinedMembersError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) class nio.responses.JoinedRoomsResponse(rooms: List[str]) 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]) class nio.responses.JoinedRoomsError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) 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 = ”)

classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str = ”) 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 = ”) class nio.responses.KeysQueryResponse(device_keys: Dict, failures: Dict)

106 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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

classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.KeysUploadError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.RegisterResponse(user_id: str, device_id: str, access_token: str)

classmethod from_dict(parsed_dict) class nio.responses.LoginResponse(user_id: str, device_id: str, access_token: str)

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

classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.LoginInfoError(message: str, status_code: Union[str, NoneType] = None, retry_after_ms: Union[int, NoneType] = None, soft_logout: bool = False) class nio.responses.LogoutResponse

classmethod from_dict(parsed_dict: Dict[Any, Any]) 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) class nio.responses.Response

elapsed end_time = None start_time = None timeout = 0 transport_response = None uuid = '' class nio.responses.RoomBanResponse

static create_error(parsed_dict)

5.1. API 107 nio Documentation, Release 0.18.6 class nio.responses.RoomBanError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.RoomCreateResponse(room_id: str) Response representing a successful create room request. classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.RoomCreateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) 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, un- read_notifications: Union[nio.responses.UnreadNotifications, NoneType] = None)

static parse_account_data(event_dict) Parse the account data dictionary and produce a list of events. summary = None unread_notifications = None class nio.responses.RoomInviteResponse

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

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

static create_error(parsed_dict) class nio.responses.RoomLeaveError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.RoomForgetResponse(room_id: str) Response representing a successful forget room request. static create_error(parsed_dict, room_id) class nio.responses.RoomForgetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) class nio.responses.RoomMember(user_id: str, display_name: str, avatar_url: str)

108 Chapter 5. Api Documentation nio Documentation, Release 0.18.6 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)

classmethod from_dict(parsed_dict: Dict[Any, Any], room_id: str) class nio.responses.RoomMessagesError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) class nio.responses.RoomGetStateResponse(events: List[T], room_id: str) 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) classmethod from_dict(parsed_dict: List[Dict[Any, Any]], room_id: str) class nio.responses.RoomGetStateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) 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) 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) classmethod from_dict(parsed_dict: Dict[str, Any], event_type: str, state_key: str, room_id: str) → Union[nio.responses.RoomGetStateEventResponse, nio.responses.RoomGetStateEventError]

5.1. API 109 nio Documentation, Release 0.18.6

class nio.responses.RoomGetStateEventError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) A response representing an unsuccessful room state query. class nio.responses.RoomGetEventResponse A response indicating successful room get event request. event The requested event. Type Event event = Field(name=None,type=None,default=,default_factory=,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] class nio.responses.RoomGetEventError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) A response representing an unsuccessful room get event request. class nio.responses.RoomPutStateResponse(event_id: str, room_id: str) A response indicating successful sending of room state. static create_error(parsed_dict, room_id) class nio.responses.RoomPutStateError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) A response representing an unsuccessful room state sending request. class nio.responses.RoomRedactResponse(event_id: str, room_id: str)

static create_error(parsed_dict, room_id) class nio.responses.RoomRedactError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) class nio.responses.RoomResolveAliasResponse(room_alias: str, room_id: str, servers: List[str]) 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)

110 Chapter 5. Api Documentation nio Documentation, Release 0.18.6 class nio.responses.RoomResolveAliasError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) A response representing an unsuccessful room alias query. class nio.responses.RoomSendResponse(event_id: str, room_id: str)

static create_error(parsed_dict, room_id) class nio.responses.RoomSendError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) class nio.responses.RoomSummary(invited_member_count: Union[int, NoneType] = None, joined_member_count: Union[int, NoneType] = None, heroes: Union[List[str], NoneType] = None)

heroes = None invited_member_count = None joined_member_count = None class nio.responses.RoomUnbanResponse

static create_error(parsed_dict) class nio.responses.RoomUnbanError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.Rooms(invite: Dict[str, ForwardRef(’InviteInfo’)], join: Dict[str, For- wardRef(’RoomInfo’)], leave: Dict[str, ForwardRef(’RoomInfo’)]) class nio.responses.SetPushRuleError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.SetPushRuleResponse

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

static create_error(parsed_dict: Dict[str, Any]) class nio.responses.ShareGroupSessionResponse(room_id: str, users_shared_with: set) 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]]

5.1. API 111 nio Documentation, Release 0.18.6

classmethod from_dict(_: Dict[Any, Any], room_id: str, users_shared_with: Set[Tuple[str, str]]) 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]] = ) Response representing unsuccessful group sessions sharing request. classmethod from_dict(parsed_dict, room_id, users_shared_with) class nio.responses.SyncResponse(next_batch: str, rooms: nio.responses.Rooms, de- vice_key_count: nio.responses.DeviceOneTimeKeyCount, device_list: nio.responses.DeviceList, to_device_events: List[nio.events.to_device.ToDeviceEvent], pres- ence_events: List[nio.events.presence.PresenceEvent], ac- count_data_events: List[nio.events.account_data.AccountDataEvent] = )

classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.SyncError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.Timeline(events: List, limited: bool, prev_batch: str) class nio.responses.UpdateDeviceResponse

static create_error(parsed_dict) class nio.responses.UpdateDeviceError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.RoomTypingResponse(room_id: str) A response representing a successful room typing request. static create_error(parsed_dict, room_id) class nio.responses.RoomTypingError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) A response representing a unsuccessful room typing request. class nio.responses.RoomReadMarkersResponse(room_id: str) A response representing a successful room read markers request. static create_error(parsed_dict, room_id)

112 Chapter 5. Api Documentation nio Documentation, Release 0.18.6 class nio.responses.RoomReadMarkersError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) A response representing a unsuccessful room read markers request. class nio.responses.UploadResponse(content_uri: str) A response representing a successful upload request. classmethod from_dict(parsed_dict: Dict[Any, Any]) class nio.responses.UploadError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) 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] = ) 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]) class nio.responses.ProfileGetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.ProfileGetDisplayNameResponse(displayname: Optional[str] = None) 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]) class nio.responses.ProfileGetDisplayNameError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.ProfileSetDisplayNameResponse

static create_error(parsed_dict)

5.1. API 113 nio Documentation, Release 0.18.6

class nio.responses.ProfileSetDisplayNameError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.ProfileGetAvatarResponse(avatar_url: Optional[str] = None) 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]) class nio.responses.ProfileGetAvatarError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.ProfileSetAvatarResponse

static create_error(parsed_dict) class nio.responses.ProfileSetAvatarError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.PresenceGetResponse(user_id: str, presence: str, last_active_ago: Op- tional[int], currently_active: Optional[bool], sta- tus_msg: Optional[str]) 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]

114 Chapter 5. Api Documentation nio Documentation, Release 0.18.6 class nio.responses.PresenceGetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) Response representing a unsuccessful get presence request. class nio.responses.PresenceSetResponse Response representing a successful set presence request. static create_error(parsed_dict) class nio.responses.PresenceSetError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) Response representing a unsuccessful set presence request. class nio.responses.RoomKeyRequestResponse(request_id: str, session_id: str, room_id: str, algorithm: str) 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) 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 re- quested, 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) Response representing a failed room key request. class nio.responses.ThumbnailResponse(body: bytes, content_type: str, filename: Op- tional[str]) A response representing a successful thumbnail request.

5.1. API 115 nio Documentation, Release 0.18.6

classmethod from_data(data: bytes, content_type: str, filename: Optional[str] = None) 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) A response representing a unsuccessful thumbnail request. class nio.responses.ToDeviceResponse(to_device_message: nio.event_builders.direct_messages.ToDeviceMessage) Response representing a successful room key request. classmethod from_dict(parsed_dict, message) 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: Op- tional[nio.event_builders.direct_messages.ToDeviceMessage] = None) Response representing a unsuccessful room key request. classmethod from_dict(parsed_dict, message) 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]]) 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

116 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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) class nio.responses.RoomContextError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = ”) 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) class nio.responses.UploadFilterResponse(filter_id: str) 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] class nio.responses.UpdateReceiptMarkerError(message: str, status_code: Optional[str] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False) class nio.responses.UpdateReceiptMarkerResponse

static create_error(parsed_dict)

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

5.1. API 117 nio Documentation, Release 0.18.6 class nio.store.MatrixStore(user_id: str, device_id: str, store_path: str, pickle_key: str = ”, database_name: str = ”) Storage class for matrix state. add_outgoing_key_request(key_request) Add an outgoing key request to the store. blacklist_device(device) 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) Delete the a encrypted room from the store. ignore_device(device) 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) 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) Check if a device is blacklisted. Parameters device (OlmDevice) – The device that will be checked if it’s blacklisted. is_device_ignored(device) Check if a device is ignored. Parameters device (OlmDevice) – The device that will be checked if it’s ignored. is_device_verified(device) Check if a device is verified. Parameters device (OlmDevice) – The device that will be checked if it’s verified. load_account() 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() Load all the device keys from the database. Returns DeviceStore containing the OlmDevices with the device keys. load_encrypted_rooms() Load the set of encrypted rooms for this account. Returns Set containing room ids of encrypted rooms. load_inbound_group_sessions() Load all Olm sessions from the database.

118 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

Returns GroupSessionStore object, containing all the loaded sessions. load_outgoing_key_requests() Load the set of outgoing key requests for this account. Returns Set containing request ids of key requests. load_sessions() Load all Olm sessions from the database. Returns SessionStore object, containing all the loaded sessions. remove_outgoing_key_request(key_request) Remove an active outgoing key request from the store. save_account(account) 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) 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) Save the set of room ids for this account. save_inbound_group_session(session) Save the provided Megolm inbound group session to the database. Parameters session (InboundGroupSession) – The session to save. save_session(sender_key, session) 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) Save the given token unblacklist_device(device) Unmark a device as blacklisted. Parameters device (OlmDevice) – The device that will be unmarked as blacklisted unignore_device(device) 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) Unmark a device as verified. Parameters device (OlmDevice) – The device that will be unmarked as verified

5.1. API 119 nio Documentation, Release 0.18.6

Returns True if the device was unverified, False otherwise, e.g. if the device wasn’t verified. verify_device(device) 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 = ”) 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 = ”) 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=”) 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

120 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

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

5.1.9 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 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] 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 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) → Op- tional[nio.crypto.device.OlmDevice] 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() List of tuples in the form (user id, dict(device_id, OlmDevice). users Get the list of users that the device store knows about.

5.1. API 121 nio Documentation, Release 0.18.6

values() 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 = ) 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 “black- listed”. 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() 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.

122 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

verified Is the device verified. class nio.crypto.TrustState 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) 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 verifi- cation 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 authentica- tion methods that the client would like to allow for this authentication session. By default the ‘emoji’ and ‘decimal’ methods are allowed.

accept_sas() Accept the short authentication string. accept_verification() → nio.event_builders.direct_messages.ToDeviceMessage Create a content dictionary to accept the verification offer. cancel() 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) Create a SAS object from a KeyVerificationStart event. Parameters

5.1. API 123 nio Documentation, Release 0.18.6

• 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 Create a dictionary containing our verification cancellation. get_decimals() → Tuple[int, ...] 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]] 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 Create a dictionary containing our MAC. receive_accept_event(event) Receive a KeyVerificationAccept event. receive_key_event(event) Receive a KeyVerificationKey event. receive_mac_event(event) Receive a KeyVerificationMac event. Parameters event (KeyVerificationMac) – The MAC event that was received for this SAS session. reject_sas() Reject the authentication string. share_key() → nio.event_builders.direct_messages.ToDeviceMessage Create a dictionary containing our public key. start_verification() → nio.event_builders.direct_messages.ToDeviceMessage 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.

5.2 Examples

If you’ve built something with matrix-nio and want to support the project, add a shield!

124 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

To start making a chat bot quickly, considering using nio-template.

Attention: For E2EE support, python-olm is needed, which requires the libolm C library (version 3.x). After libolm has been installed, the e2ee enabled version of nio can be installed using pip install "matrix-nio[e2e]".

5.2.1 Projects built with nio

• pantalaimon • nio-template • matrix-tweetalong-bot • weechat-matrix • hemppa • devops-bot • podbot • delator • cody • matrix-nio-send • Mirage • matrix-commander • matrix-archive • matrix-eno-bot • matrix--bridge • Simple-Matrix-Bot-Lib • pushmatrix Are we missing a project? Submit a pull request and we’ll get you added! Just edit doc/built-with-nio.rst

5.2.2 A basic client

A basic client requires a few things before you start: • nio is installed • a Matrix homeserver URL (probably “https://matrix.example.org”) • a username and password for an account on that homeserver • a room ID for a room on that homeserver. In Riot, this is found in the Room’s settings page under “Advanced” By far the easiest way to use nio is using the asyncio layer, unless you have special restrictions that disallow the use of asyncio. All examples require Python 3.5+ for the async / await syntax.

5.2. Examples 125 nio Documentation, Release 0.18.6

1 import asyncio

2

3 from nio import AsyncClient, MatrixRoom, RoomMessageText

4

5

6 async def message_callback(room: MatrixRoom, event: RoomMessageText)-> None:

7 print(

8 f"Message received in room {room.display_name}\n"

9 f"{room.user_name(event.sender)} | {event.body}"

10 )

11

12 async def main()-> None:

13 client= AsyncClient("https://matrix.example.org","@alice:example.org")

14 client.add_event_callback(message_callback, RoomMessageText)

15

16 print(await client.login("my-secret-password"))

17 # "Logged in as @alice:example.org device id: RANDOMDID"

18

19 # If you made a new room and haven't joined as that user, you can use

20 # await client.join("your-room-id")

21

22 await client.room_send(

23 # Watch out! If you join an old room you'll see lots of old messages

24 room_id="!my-fave-room:example.org",

25 message_type="m.room.message",

26 content={

27 "msgtype":"m.text",

28 "body":"Hello world!"

29 }

30 )

31 await client.sync_forever(timeout=30000) # milliseconds

32

33 asyncio.get_event_loop().run_until_complete(main())

5.2.3 Log in using a stored access_token

Using access tokens requires that when you first log in you save a few values to use later. In this example, we’re going to write them to disk as a JSON object, but you could also store them in a database, print them out and post them up on the wall beside your desk, text them to your sister in law, or anything else that allows you access to the values at a later date. We’ve tried to keep this example small enough that it’s just enough to work; once you start writing your own programs with nio you may want to clean things up a bit. This example requires that the user running it has write permissions to the folder they’re in. If you copied this repo to your computer, you probably have write permissions. Now run the program restore_login.py twice. First time around it will ask you for credentials like homeserver and password. On the second run, the program will log in for you automatically and it will send a “Hello World” message to the room you specify.

1 #!/usr/bin/env python3

2

3 import asyncio

4 import json

5 import os

6 import sys

7 import getpass (continues on next page)

126 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

8

9 from nio import AsyncClient, LoginResponse

10

11 CONFIG_FILE="credentials.json"

12

13 # Check out main() below to see how it's done.

14

15

16 def write_details_to_disk(resp: LoginResponse, homeserver)-> None:

17 """Writes the required login details to disk so we can log in later without

18 using a password.

19

20 Arguments:

21 resp {LoginResponse} -- the successful client login response.

22 homeserver -- URL of homeserver, e.g. "https://matrix.example.org"

23 """

24 # open the config file in write-mode

25 with open(CONFIG_FILE,"w") as f:

26 # write the login details to disk

27 json.dump(

28 {

29 "homeserver": homeserver, # e.g. "https://matrix.example.org"

30 "user_id": resp.user_id, # e.g. "@user:example.org"

31 "device_id": resp.device_id, # device ID, 10 uppercase letters

32 "access_token": resp.access_token # cryptogr. access token

33 },

34 f

35 )

36

37

38 async def main()-> None:

39 # If there are no previously-saved credentials, we'll use the password

40 if not os.path.exists(CONFIG_FILE):

41 print("First time use. Did not find credential file. Asking for"

42 "homeserver, user, and password to create credential file.")

43 homeserver="https://matrix.example.org"

44 homeserver= input(f"Enter your homeserver URL: [ {homeserver}]")

45

46 if not (homeserver.startswith("https://")

47 or homeserver.startswith("http://")):

48 homeserver="https://"+ homeserver

49

50 user_id="@user:example.org"

51 user_id= input(f"Enter your full user ID: [ {user_id}]")

52

53 device_name="matrix-nio"

54 device_name= input(f"Choose a name for this device: [ {device_name}]")

55

56 client= AsyncClient(homeserver, user_id)

57 pw= getpass.getpass()

58

59 resp= await client.login(pw, device_name=device_name)

60

61 # check that we logged in succesfully

62 if (isinstance(resp, LoginResponse)):

63 write_details_to_disk(resp, homeserver)

64 else: (continues on next page)

5.2. Examples 127 nio Documentation, Release 0.18.6

(continued from previous page)

65 print(f"homeserver = \"{homeserver}\"; user = \"{user_id}\"")

66 print(f"Failed to log in: {resp}")

67 sys.exit(1)

68

69 print(

70 "Logged in using a password. Credentials were stored.",

71 "Try running the script again to login with credentials."

72 )

73

74 # Otherwise the config file exists, so we'll use the stored credentials

75 else:

76 # open the file in read-only mode

77 with open(CONFIG_FILE,"r") as f:

78 config= json.load(f)

79 client= AsyncClient(config['homeserver'])

80

81 client.access_token= config['access_token']

82 client.user_id= config['user_id']

83 client.device_id= config['device_id']

84

85 # Now we can send messages as the user

86 room_id="!myfavouriteroomid:example.org"

87 room_id= input(f"Enter room id for test message: [ {room_id}]")

88

89 await client.room_send(

90 room_id,

91 message_type="m.room.message",

92 content={

93 "msgtype":"m.text",

94 "body":"Hello world!"

95 }

96 )

97 print("Logged in using stored credentials. Sent a test message.")

98

99 # Either way we're logged in here, too

100 await client.close()

101

102 asyncio.get_event_loop().run_until_complete(main())

5.2.4 Sending an image

Now that you have sent a first “Hello World” text message, how about going one step further and sending an image, like a photo from your last vacation. Run the send_image.py program and provide a filename to the photo. Voila, you have just sent your first image!

1 #!/usr/bin/env python3

2

3 import asyncio

4 import json

5 import os

6 import sys

7 import getpass

8 from PIL import Image

9 import aiofiles.os

10 import magic (continues on next page)

128 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

11

12 from nio import AsyncClient, LoginResponse, UploadResponse

13

14 CONFIG_FILE="credentials.json"

15

16 # Check out main() below to see how it's done.

17

18

19 def write_details_to_disk(resp: LoginResponse, homeserver)-> None:

20 """Writes the required login details to disk so we can log in later without

21 using a password.

22

23 Arguments:

24 resp {LoginResponse} -- the successful client login response.

25 homeserver -- URL of homeserver, e.g. "https://matrix.example.org"

26 """

27 # open the config file in write-mode

28 with open(CONFIG_FILE,"w") as f:

29 # write the login details to disk

30 json.dump(

31 {

32 "homeserver": homeserver, # e.g. "https://matrix.example.org"

33 "user_id": resp.user_id, # e.g. "@user:example.org"

34 "device_id": resp.device_id, # device ID, 10 uppercase letters

35 "access_token": resp.access_token # cryptogr. access token

36 },

37 f

38 )

39

40

41 async def send_image(client, room_id, image):

42 """Send image to toom.

43

44 Arguments:

45 ------

46 client : Client

47 room_id : str

48 image : str, file name of image

49

50 This is a working example for a JPG image.

51 "content": {

52 "body": "someimage.jpg",

53 "info": {

54 "size": 5420,

55 "mimetype": "image/jpeg",

56 "thumbnail_info": {

57 "w": 100,

58 "h": 100,

59 "mimetype": "image/jpeg",

60 "size": 2106

61 },

62 "w": 100,

63 "h": 100,

64 "thumbnail_url": "mxc://example.com/SomeStrangeThumbnailUriKey"

65 },

66 "msgtype": "m.image",

67 "url": "mxc://example.com/SomeStrangeUriKey" (continues on next page)

5.2. Examples 129 nio Documentation, Release 0.18.6

(continued from previous page)

68 }

69

70 """

71 mime_type= magic.from_file(image, mime= True) # e.g. "image/jpeg"

72 if not mime_type.startswith("image/"):

73 print("Drop message because file does not have an image mime type.")

74 return

75

76 im= Image.open(image)

77 (width, height)= im.size # im.size returns (width,height) tuple

78

79 # first do an upload of image, then send URI of upload to room

80 file_stat= await aiofiles.os.stat(image)

81 async with aiofiles.open(image,"r+b") as f:

82 resp, maybe_keys= await client.upload(

83 f,

84 content_type=mime_type, # image/jpeg

85 filename=os.path.basename(image),

86 filesize=file_stat.st_size)

87 if (isinstance(resp, UploadResponse)):

88 print("Image was uploaded successfully to server.")

89 else:

90 print(f"Failed to upload image. Failure response: {resp}")

91

92 content={

93 "body": os.path.basename(image), # descriptive title

94 "info":{

95 "size": file_stat.st_size,

96 "mimetype": mime_type,

97 "thumbnail_info": None, # TODO

98 "w": width, # width in pixel

99 "h": height, # height in pixel

100 "thumbnail_url": None, # TODO

101 },

102 "msgtype":"m.image",

103 "url": resp.content_uri,

104 }

105

106 try:

107 await client.room_send(

108 room_id,

109 message_type="m.room.message",

110 content=content

111 )

112 print("Image was sent successfully")

113 except Exception:

114 print(f"Image send of file {image} failed.")

115

116

117 async def main()-> None:

118 # If there are no previously-saved credentials, we'll use the password

119 if not os.path.exists(CONFIG_FILE):

120 print("First time use. Did not find credential file. Asking for"

121 "homeserver, user, and password to create credential file.")

122 homeserver="https://matrix.example.org"

123 homeserver= input(f"Enter your homeserver URL: [ {homeserver}]")

124 (continues on next page)

130 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

125 if not (homeserver.startswith("https://")

126 or homeserver.startswith("http://")):

127 homeserver="https://"+ homeserver

128

129 user_id="@user:example.org"

130 user_id= input(f"Enter your full user ID: [ {user_id}]")

131

132 device_name="matrix-nio"

133 device_name= input(f"Choose a name for this device: [ {device_name}]")

134

135 client= AsyncClient(homeserver, user_id)

136 pw= getpass.getpass()

137

138 resp= await client.login(pw, device_name=device_name)

139

140 # check that we logged in succesfully

141 if (isinstance(resp, LoginResponse)):

142 write_details_to_disk(resp, homeserver)

143 else:

144 print(f"homeserver = \"{homeserver}\"; user = \"{user_id}\"")

145 print(f"Failed to log in: {resp}")

146 sys.exit(1)

147

148 print(

149 "Logged in using a password. Credentials were stored.",

150 "Try running the script again to login with credentials."

151 )

152

153 # Otherwise the config file exists, so we'll use the stored credentials

154 else:

155 # open the file in read-only mode

156 with open(CONFIG_FILE,"r") as f:

157 config= json.load(f)

158 client= AsyncClient(config['homeserver'])

159

160 client.access_token= config['access_token']

161 client.user_id= config['user_id']

162 client.device_id= config['device_id']

163

164 # Now we can send messages as the user

165 room_id="!myfavouriteroomid:example.org"

166 room_id= input(f"Enter room id for image message: [ {room_id}]")

167

168 image="exampledir/samplephoto.jpg"

169 image= input(f"Enter file name of image to send: [ {image}]")

170

171 await send_image(client, room_id, image)

172 print("Logged in using stored credentials. Sent a test message.")

173

174 # Close the client connection after we are done with it.

175 await client.close()

176

177 asyncio.get_event_loop().run_until_complete(main())

5.2. Examples 131 nio Documentation, Release 0.18.6

5.2.5 Manual encryption key verification

Below is a program that works through manual encryption of other users when you already know all of their device IDs. It’s a bit dense but provides a good example in terms of being pythonic and using nio’s design features purposefully. It is not designed to be a template that you can immediately extend to run your bot, it’s designed to be an example of how to use nio. The overall structure is this: we subclass nio’s AsyncClient class and add in our own handlers for a few things, namely: • automatically restoring login details from disk instead of creating new sessions each time we restart the process - callback for printing out any message we receive to stdout - callback for automatically joining any room @alice is invited to - a method for trusting devices using a user ID and (optionall) their list of trusted device IDs - a sample “hello world” encrypted message method In main, we make an instance of that subclass, attempt to login, then create an asyncio coroutine to run later that will trust the devices and send the hello world message. We then create ‘asyncio Tasks <>‘_ to run that coroutine as well as the sync_forever() coroutine that nio provides, which does most of the handling of required work for communicating with Matrix: it uploads keys, checks for new messages, executes callbacks when events occur that trigger those callbacks, etc. Main executes the result of those Tasks. You’ll need two accounts, which we’ll call @alice:example.org and @bob:example.org. @alice will be your nio application and @bob will be your second user account. Before the script runs, make a new room with the @bob account, enable encryption and invite @alice. Note the room ID as you’ll need it for this script. You’ll also need all of @bob’s device IDs, which you can get from within Riot under the profile settings > Advanced section. They may be called “session IDs”. These are the device IDs that your program will trust, and getting them into nio is the manual part here. In another example we’ll document automatic emoji verification. It may look long at first but much of the program is actually documentation explaining how it works. If you have questions about the example, please don’t hesitate to ask them on #nio:matrix.org. If you are stuck, it may be useful to read this primer from Matrix.org on implementing end-to-end encryption: https: //matrix.org/docs/guides/end-to-end-encryption-implementation-guide To delete the store, or clear the trusted devices, simply remove “nio_store” in the working directory as well as “man- ual_encrypted_verify.json”. Then the example script will log in (with a new session ID) and generate new keys.

1 import asyncio

2 import os

3 import sys

4 import json

5

6 from typing import Optional

7

8 from nio import (AsyncClient, ClientConfig, DevicesError, Event,InviteEvent,

˓→LoginResponse,

9 LocalProtocolError, MatrixRoom, MatrixUser, RoomMessageText,

10 crypto, exceptions, RoomSendResponse)

11

12 # This is a fully-documented example of how to do manual verification with nio,

13 # for when you already know the device IDs of the users you want to trust. If

14 # you want live verification using emojis, the process is more complicated and

15 # will be covered in another example.

16

17 # We're building on the restore_login example here to preserve device IDs and

18 # therefore preserve trust; if @bob trusts @alice's device ID ABC and @alice

19 # restarts this program, loading the same keys, @bob will preserve trust. If

20 # @alice logged in again @alice would have new keys and a device ID XYZ, and (continues on next page)

132 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

21 # @bob wouldn't trust it.

22

23 # The store is where we want to place encryption details like our keys, trusted

24 # devices and blacklisted devices. Here we place it in the working directory,

25 # but if you deploy your program you might consider /var or /opt for storage

26 STORE_FOLDER="nio_store/"

27

28 # This file is for restoring login details after closing the program, so you

29 # can preserve your device ID. If @alice logged in every time instead, @bob

30 # would have to re-verify. See the restoring login example for more into.

31 SESSION_DETAILS_FILE="credentials.json"

32

33 # Only needed for this example, this is who @alice will securely

34 # communicate with. We need all the device IDs of this user so we can consider

35 # them "trusted". If an unknown device shows up (like @bob signs into their

36 # account on another device), this program will refuse to send a message in the

37 # room. Try it!

38 BOB_ID="@bob:example.org"

39 BOB_DEVICE_IDS=[

40 # You can find these in Riot under Settings > Security & Privacy.

41 # They may also be called "session IDs". You'll want to add ALL of them here

42 # for the one other user in your encrypted room

43 "URDEVICEID",

44 ]

45

46 # the ID of the room you want your bot to join and send commands in.

47 # This can be a direct message or room; Matrix treats them the same

48 ROOM_ID="!myfavouriteroom:example.org"

49

50 ALICE_USER_ID="@alice:example.org"

51 ALICE_HOMESERVER="https://matrix.example.org"

52 ALICE_PASSWORD="hunter2"

53

54 class CustomEncryptedClient(AsyncClient):

55 def __init__(self, homeserver, user='', device_id='', store_path='', config=None,

˓→ssl=None, proxy=None):

56 # Calling super.__init__ means we're running the __init__ method

57 # defined in AsyncClient, which this class derives from. That does a

58 # bunch of setup for us automatically

59 super().__init__(homeserver, user=user, device_id=device_id, store_path=store_

˓→path, config=config, ssl=ssl, proxy=proxy)

60

61 # if the store location doesn't exist, we'll make it

62 if store_path and not os.path.isdir(store_path):

63 os.mkdir(store_path)

64

65 # auto-join room invites

66 self.add_event_callback(self.cb_autojoin_room, InviteEvent)

67

68 # print all the messages we receive

69 self.add_event_callback(self.cb_print_messages, RoomMessageText)

70

71 async def login(self)-> None:

72 """Log in either using the global variables or (if possible) using the

73 session details file.

74

75 NOTE: This method kinda sucks. Don't use these kinds of global (continues on next page)

5.2. Examples 133 nio Documentation, Release 0.18.6

(continued from previous page)

76 variables in your program; it would be much better to pass them

77 around instead. They are only used here to minimise the size of the

78 example.

79 """

80 # Restore the previous session if we can

81 # See the "restore_login.py" example if you're not sure how this works

82 if os.path.exists(SESSION_DETAILS_FILE) and os.path.isfile(SESSION_DETAILS_

˓→FILE):

83 try:

84 with open(SESSION_DETAILS_FILE,"r") as f:

85 config= json.load(f)

86 self.access_token= config['access_token']

87 self.user_id= config['user_id']

88 self.device_id= config['device_id']

89

90 # This loads our verified/blacklisted devices and our keys

91 self.load_store()

92 print(f"Logged in using stored credentials: {self.user_id} on

˓→{self.device_id}")

93

94 except IOError as err:

95 print(f"Couldn't load session from file. Logging in. Error: {err}")

96 except json.JSONDecodeError:

97 print("Couldn't read JSON file; overwriting")

98

99 # We didn't restore a previous session, so we'll log in with a password

100 if not self.user_id or not self.access_token or not self.device_id:

101 # this calls the login method defined in AsyncClient from nio

102 resp= await super().login(ALICE_PASSWORD)

103

104 if isinstance(resp, LoginResponse):

105 print("Logged in using a password; saving details to disk")

106 self.__write_details_to_disk(resp)

107 else:

108 print(f"Failed to log in: {resp}")

109 sys.exit(1)

110

111 def trust_devices(self, user_id: str, device_list: Optional[str]= None)-> None:

112 """Trusts the devices of a user.

113

114 If no device_list is provided, all of the users devices are trusted. If

115 one is provided, only the devices with IDs in that list are trusted.

116

117 Arguments:

118 user_id {str} -- the user ID whose devices should be trusted.

119

120 Keyword Arguments:

121 device_list {Optional[str]} -- The full list of device IDs to trust

122 from that user (default: {None})

123 """

124

125 print(f"{user_id}'s device store: {self.device_store[user_id]}")

126

127 # The device store contains a dictionary of device IDs and known

128 # OlmDevices for all users that share a room with us, including us.

129

130 # We can only run this after a first sync. We have to populate our (continues on next page)

134 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

131 # device store and that requires syncing with the server.

132 for device_id, olm_device in self.device_store[user_id].items():

133 if device_list and device_id not in device_list:

134 # a list of trusted devices was provided, but this ID is not in

135 # that list. That's an issue.

136 print(f"Not trusting {device_id} as it's not in {user_id}'s pre-

˓→approved list.")

137 continue

138

139 if user_id == self.user_id and device_id == self.device_id:

140 # We cannot explictly trust the device @alice is using

141 continue

142

143 self.verify_device(olm_device)

144 print(f"Trusting {device_id} from user {user_id}")

145

146 def cb_autojoin_room(self, room: MatrixRoom, event: InviteEvent):

147 """Callback to automatically joins a Matrix room on invite.

148

149 Arguments:

150 room {MatrixRoom} -- Provided by nio

151 event {InviteEvent} -- Provided by nio

152 """

153 self.join(room.room_id)

154 room= self.rooms[ROOM_ID]

155 print(f"Room {room.name} is encrypted: {room.encrypted}")

156

157 async def cb_print_messages(self, room: MatrixRoom, event: RoomMessageText):

158 """Callback to print all received messages to stdout.

159

160 Arguments:

161 room {MatrixRoom} -- Provided by nio

162 event {RoomMessageText} -- Provided by nio

163 """

164 if event.decrypted:

165 encrypted_symbol=""

166 else:

167 encrypted_symbol=""

168 print(f"{room.display_name} |{encrypted_symbol}| {room.user_name(event.

˓→sender)}: {event.body}")

169

170 async def send_hello_world(self):

171 # Now we send an encrypted message that @bob can read, although it will

172 # appear to be "unverified" when they see it, because @bob has not verified

173 # the device @alice is sending from.

174 # We'll leave that as an excercise for the reader.

175 try:

176 await self.room_send(

177 room_id=ROOM_ID,

178 message_type="m.room.message",

179 content={

180 "msgtype":"m.text",

181 "body":"Hello, this message is encrypted"

182 }

183 )

184 except exceptions.OlmUnverifiedDeviceError as err:

185 print("These are all known devices:") (continues on next page)

5.2. Examples 135 nio Documentation, Release 0.18.6

(continued from previous page)

186 device_store: crypto.DeviceStore= device_store

187 [print(f"\t{device.user_id}\t {device.device_id}\t {device.trust_state}\t

˓→ {device.display_name}") for device in device_store]

188 sys.exit(1)

189

190 @staticmethod

191 def __write_details_to_disk(resp: LoginResponse)-> None:

192 """Writes login details to disk so that we can restore our session later

193 without logging in again and creating a new device ID.

194

195 Arguments:

196 resp {LoginResponse} -- the successful client login response.

197 """

198 with open(SESSION_DETAILS_FILE,"w") as f:

199 json.dump({

200 "access_token": resp.access_token,

201 "device_id": resp.device_id,

202 "user_id": resp.user_id

203 }, f)

204

205

206 async def run_client(client: CustomEncryptedClient)-> None:

207 """A basic encrypted chat application using nio.

208 """

209

210 # This is our own custom login function that looks for a pre-existing config

211 # file and, if it exists, logs in using those details. Otherwise it will log

212 # in using a password.

213 await client.login()

214

215 # Here we create a coroutine that we can call in asyncio.gather later,

216 # along with sync_forever and any other API-related coroutines you'd like

217 # to do.

218 async def after_first_sync():

219 # We'll wait for the first firing of 'synced' before trusting devices.

220 # client.synced is an asyncio event that fires any time nio syncs. This

221 # code doesn't run in a loop, so it only fires once

222 print("Awaiting sync")

223 await client.synced.wait()

224

225

226 # In practice, you want to have a list of previously-known device IDs

227 # for each user you want ot trust. Here, we require that list as a

228 # global variable

229 client.trust_devices(BOB_ID, BOB_DEVICE_IDS)

230

231 # In this case, we'll trust _all_ of @alice's devices. NOTE that this

232 # is a SUPER BAD IDEA in practice, but for the purpose of this example

233 # it'll be easier, since you may end up creating lots of sessions for

234 # @alice as you play with the script

235 client.trust_devices(ALICE_USER_ID)

236

237 await client.send_hello_world()

238

239 # We're creating Tasks here so that you could potentially write other

240 # Python coroutines to do other work, like checking an API or using another

241 # library. All of these Tasks will be run concurrently. (continues on next page)

136 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

242 # For more details, check out https://docs.python.org/3/library/asyncio-task.html

243

244 # ensure_future() is for Python 3.5 and 3.6 compatability. For 3.7+, use

245 # asyncio.create_task()

246 after_first_sync_task= asyncio.ensure_future(after_first_sync())

247

248 # We use full_state=True here to pull any room invites that occured or

249 # messages sent in rooms _before_ this program connected to the

250 # Matrix server

251 sync_forever_task= asyncio.ensure_future(client.sync_forever(30000, full_

˓→state=True))

252

253 await asyncio.gather(

254 # The order here IS significant! You have to register the task to trust

255 # devices FIRST since it awaits the first sync

256 after_first_sync_task,

257 sync_forever_task

258 )

259

260 async def main():

261 # By setting `store_sync_tokens` to true, we'll save sync tokens to our

262 # store every time we sync, thereby preventing reading old, previously read

263 # events on each new sync.

264 # For more info, check out https://matrix-nio.readthedocs.io/en/latest/nio.html

˓→#asyncclient

265 config= ClientConfig(store_sync_tokens= True)

266 client= CustomEncryptedClient(

267 ALICE_HOMESERVER,

268 ALICE_USER_ID,

269 store_path=STORE_FOLDER,

270 config=config,

271 ssl=False,

272 proxy="http://localhost:8080",

273 )

274

275 try:

276 await run_client(client)

277 except (asyncio.CancelledError, KeyboardInterrupt):

278 await client.close()

279

280 # Run the main coroutine, which instantiates our custom subclass, trusts all the

281 # devices, and syncs forever (or until your press Ctrl+C)

282

283 if __name__ =="__main__":

284 try:

285 asyncio.run(

286 main()

287 )

288 except KeyboardInterrupt:

289 pass

5.2.6 Interactive encryption key verification

One way to interactively verify a device is via emojis. On popular Matrix clients you will find that devices are flagged as trusted or untrusted. If a device is untrusted you can verify to make it trusted. Most clients have a red symbol for

5.2. Examples 137 nio Documentation, Release 0.18.6

untrusted and a green icon for trusted. One can select un untrusted device and initiate a verify by emoji action. How would that look like in code? How can you add that to your application? Next we present a simple application that showcases emoji verification. Note, the app only accepts emoji verification. So, you have to start it on the other client (e.g. ). Initiating an emoji verification is similar in code, consider doing it as “homework” if you feel up to it. But for now, let’s have a look how emoji verification can be accepted and processed.

1 #!/usr/bin/env python3

2

3 """verify_with_emoji.py A sample program to demo Emoji verification.

4

5 # Objectives:

6 - Showcase the emoji verification using matrix-nio SDK

7 - This sample program tries to show the key steps involved in performing

8 an emoji verification.

9 - It does so only for incoming request, outgoing emoji verification request

10 are similar but not shown in this sample program

11

12 # Prerequisites:

13 - You must have matrix-nio and components for end-to-end encryption installed

14 See: https://github.com/poljar/matrix-nio

15 - You must have created a Matrix account already,

16 and have username and password ready

17 - You must have already joined a Matrix room with someone, e.g. yourself

18 - This other party initiates an emoji verifiaction with you

19 - You are using this sample program to accept this incoming emoji verification

20 and follow the protocol to successfully verify the other party's device

21

22 # Use Cases:

23 - Apply similar code in your Matrix bot

24 - Apply similar code in your Matrix client

25 - Just to learn about Matrix and the matrix-nio SDK

26

27 # Running the Program:

28 - Change permissions to allow execution

29 `chmod 755 ./verify_with_emoji.py`

30 - Optionally create a store directory, if not it will be done for you

31 `mkdir ./store/`

32 - Run the program as-is, no changes needed

33 `./verify_with_emoji.py`

34 - Run it as often as you like

35

36 # Sample Screen Output when Running Program:

37 $ ./verify_with_emoji.py

38 First time use. Did not find credential file. Asking for

39 homeserver, user, and password to create credential file.

40 Enter your homeserver URL: [https://matrix.example.org] matrix.example.org

41 Enter your full user ID: [@user:example.org] @user:example.org

42 Choose a name for this device: [matrix-nio] verify_with_emoji

43 Password:

44 Logged in using a password. Credentials were stored.

45 On next execution the stored login credentials will be used.

46 This program is ready and waiting for the other party to initiate an emoji

47 verification with us by selecting "Verify by Emoji" in their Matrix client.

48 [('', 'Anchor'), ('', 'Telephone'), ('', 'Smiley'), ('', 'Smiley'),

49 ('', 'Umbrella'), ('', 'Anchor'), ('', 'Telephone')]

50 Do the emojis match? (Y/N) y

51 Match! Device will be verified by accepting verification.

52 sas.we_started_it = False (continues on next page)

138 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

53 sas.sas_accepted = True

54 sas.canceled = False

55 sas.timed_out = False

56 sas.verified = True

57 sas.verified_devices = ['DEVICEIDXY']

58 Emoji verification was successful.

59 Hit Control-C to stop the program or initiate another Emoji verification

60 from another device or room.

61

62 """

63

64 from nio import (

65 AsyncClient,

66 AsyncClientConfig,

67 LoginResponse,

68 KeyVerificationEvent,

69 KeyVerificationStart,

70 KeyVerificationCancel,

71 KeyVerificationKey,

72 KeyVerificationMac,

73 ToDeviceError,

74 LocalProtocolError,

75 )

76 import traceback

77 import getpass

78 import sys

79 import os

80 import json

81 import asyncio

82

83

84 # file to store credentials in case you want to run program multiple times

85 CONFIG_FILE="credentials.json" # login credentials JSON file

86 # directory to store persistent data for end-to-end encryption

87 STORE_PATH="./store/" # local directory

88

89

90 class Callbacks(object):

91 """Class to pass client to callback methods."""

92

93 def __init__(self, client):

94 """Store AsyncClient."""

95 self.client= client

96

97 async def to_device_callback(self, event): # noqa

98 """Handle events sent to device."""

99 try:

100 client= self.client

101

102 if isinstance(event, KeyVerificationStart): # first step

103 """ first step: receive KeyVerificationStart

104 KeyVerificationStart(

105 source={'content':

106 {'method': 'm.sas.v1',

107 'from_device': 'DEVICEIDXY',

108 'key_agreement_protocols':

109 ['curve25519-hkdf-sha256', 'curve25519'], (continues on next page)

5.2. Examples 139 nio Documentation, Release 0.18.6

(continued from previous page)

110 'hashes': ['sha256'],

111 'message_authentication_codes':

112 ['hkdf-hmac-sha256', 'hmac-sha256'],

113 'short_authentication_string':

114 ['decimal', 'emoji'],

115 'transaction_id': 'SomeTxId'

116 },

117 'type': 'm.key.verification.start',

118 'sender': '@user2:example.org'

119 },

120 sender='@user2:example.org',

121 transaction_id='SomeTxId',

122 from_device='DEVICEIDXY',

123 method='m.sas.v1',

124 key_agreement_protocols=[

125 'curve25519-hkdf-sha256', 'curve25519'],

126 hashes=['sha256'],

127 message_authentication_codes=[

128 'hkdf-hmac-sha256', 'hmac-sha256'],

129 short_authentication_string=['decimal', 'emoji'])

130 """

131

132 if "emoji" not in event.short_authentication_string:

133 print("Other device does not support emoji verification"

134 f"{event.short_authentication_string}.")

135 return

136 resp= await client.accept_key_verification(

137 event.transaction_id)

138 if isinstance(resp, ToDeviceError):

139 print(f"accept_key_verification failed with {resp}")

140

141 sas= client.key_verifications[event.transaction_id]

142

143 todevice_msg= sas.share_key()

144 resp= await client.to_device(todevice_msg)

145 if isinstance(resp, ToDeviceError):

146 print(f"to_device failed with {resp}")

147

148 elif isinstance(event, KeyVerificationCancel): # anytime

149 """ at any time: receive KeyVerificationCancel

150 KeyVerificationCancel(source={

151 'content': {'code': 'm.mismatched_sas',

152 'reason': 'Mismatched authentication string',

153 'transaction_id': 'SomeTxId'},

154 'type': 'm.key.verification.cancel',

155 'sender': '@user2:example.org'},

156 sender='@user2:example.org',

157 transaction_id='SomeTxId',

158 code='m.mismatched_sas',

159 reason='Mismatched short authentication string')

160 """

161

162 # There is no need to issue a

163 # client.cancel_key_verification(tx_id, reject=False)

164 # here. The SAS flow is already cancelled.

165 # We only need to inform the user.

166 print(f"Verification has been cancelled by {event.sender} " (continues on next page)

140 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

167 f"for reason \"{event.reason}\".")

168

169 elif isinstance(event, KeyVerificationKey): # second step

170 """ Second step is to receive KeyVerificationKey

171 KeyVerificationKey(

172 source={'content': {

173 'key': 'SomeCryptoKey',

174 'transaction_id': 'SomeTxId'},

175 'type': 'm.key.verification.key',

176 'sender': '@user2:example.org'

177 },

178 sender='@user2:example.org',

179 transaction_id='SomeTxId',

180 key='SomeCryptoKey')

181 """

182 sas= client.key_verifications[event.transaction_id]

183

184 print(f"{sas.get_emoji()}")

185

186 yn= input("Do the emojis match? (Y/N) (C for Cancel)")

187 if yn.lower() =="y":

188 print("Match! The verification for this"

189 "device will be accepted.")

190 resp= await client.confirm_short_auth_string(

191 event.transaction_id)

192 if isinstance(resp, ToDeviceError):

193 print(f"confirm_short_auth_string failed with {resp}")

194 elif yn.lower() =="n": # no, don't match, reject

195 print("No match! Device will NOT be verified"

196 "by rejecting verification.")

197 resp= await client.cancel_key_verification(

198 event.transaction_id, reject=True)

199 if isinstance(resp, ToDeviceError):

200 print(f"cancel_key_verification failed with {resp}")

201 else: # C or anything for cancel

202 print("Cancelled by user! Verification will be"

203 "cancelled.")

204 resp= await client.cancel_key_verification(

205 event.transaction_id, reject=False)

206 if isinstance(resp, ToDeviceError):

207 print(f"cancel_key_verification failed with {resp}")

208

209 elif isinstance(event, KeyVerificationMac): # third step

210 """ Third step is to receive KeyVerificationMac

211 KeyVerificationMac(

212 source={'content': {

213 'mac': {'ed25519:DEVICEIDXY': 'SomeKey1',

214 'ed25519:SomeKey2': 'SomeKey3'},

215 'keys': 'SomeCryptoKey4',

216 'transaction_id': 'SomeTxId'},

217 'type': 'm.key.verification.mac',

218 'sender': '@user2:example.org'},

219 sender='@user2:example.org',

220 transaction_id='SomeTxId',

221 mac={'ed25519:DEVICEIDXY': 'SomeKey1',

222 'ed25519:SomeKey2': 'SomeKey3'},

223 keys='SomeCryptoKey4') (continues on next page)

5.2. Examples 141 nio Documentation, Release 0.18.6

(continued from previous page)

224 """

225 sas= client.key_verifications[event.transaction_id]

226 try:

227 todevice_msg= sas.get_mac()

228 except LocalProtocolError as e:

229 # e.g. it might have been cancelled by ourselves

230 print(f"Cancelled or protocol error: Reason: {e}.\n"

231 f"Verification with {event.sender} not concluded."

232 "Try again?")

233 else:

234 resp= await client.to_device(todevice_msg)

235 if isinstance(resp, ToDeviceError):

236 print(f"to_device failed with {resp}")

237 print(f"sas.we_started_it = {sas.we_started_it}\n"

238 f"sas.sas_accepted = {sas.sas_accepted}\n"

239 f"sas.canceled = {sas.canceled}\n"

240 f"sas.timed_out = {sas.timed_out}\n"

241 f"sas.verified = {sas.verified}\n"

242 f"sas.verified_devices = {sas.verified_devices}\n")

243 print("Emoji verification was successful!\n"

244 "Hit Control-C to stop the program or"

245 "initiate another Emoji verification from"

246 "another device or room.")

247 else:

248 print(f"Received unexpected event type {type(event)}."

249 f"Event is {event}. Event will be ignored.")

250 except BaseException:

251 print(traceback.format_exc())

252

253

254 def write_details_to_disk(resp: LoginResponse, homeserver)-> None:

255 """Write the required login details to disk.

256

257 It will allow following logins to be made without password.

258

259 Arguments:

260 ------

261 resp : LoginResponse - successful client login response

262 homeserver : str - URL of homeserver, e.g. "https://matrix.example.org"

263

264 """

265 # open the config file in write-mode

266 with open(CONFIG_FILE,"w") as f:

267 # write the login details to disk

268 json.dump(

269 {

270 "homeserver": homeserver, # e.g. "https://matrix.example.org"

271 "user_id": resp.user_id, # e.g. "@user:example.org"

272 "device_id": resp.device_id, # device ID, 10 uppercase letters

273 "access_token": resp.access_token # cryptogr. access token

274 },

275 f

276 )

277

278

279 async def login()-> AsyncClient:

280 """Handle login with or without stored credentials.""" (continues on next page)

142 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

(continued from previous page)

281 # Configuration options for the AsyncClient

282 client_config= AsyncClientConfig(

283 max_limit_exceeded=0,

284 max_timeouts=0,

285 store_sync_tokens=True,

286 encryption_enabled=True,

287 )

288

289 # If there are no previously-saved credentials, we'll use the password

290 if not os.path.exists(CONFIG_FILE):

291 print("First time use. Did not find credential file. Asking for"

292 "homeserver, user, and password to create credential file.")

293 homeserver="https://matrix.example.org"

294 homeserver= input(f"Enter your homeserver URL: [ {homeserver}]")

295

296 if not (homeserver.startswith("https://")

297 or homeserver.startswith("http://")):

298 homeserver="https://"+ homeserver

299

300 user_id="@user:example.org"

301 user_id= input(f"Enter your full user ID: [ {user_id}]")

302

303 device_name="matrix-nio"

304 device_name= input(f"Choose a name for this device: [ {device_name}]")

305

306 if not os.path.exists(STORE_PATH):

307 os.makedirs(STORE_PATH)

308

309 # Initialize the matrix client

310 client= AsyncClient(

311 homeserver,

312 user_id,

313 store_path=STORE_PATH,

314 config=client_config,

315 )

316 pw= getpass.getpass()

317

318 resp= await client.login(password=pw, device_name=device_name)

319

320 # check that we logged in succesfully

321 if (isinstance(resp, LoginResponse)):

322 write_details_to_disk(resp, homeserver)

323 else:

324 print(f"homeserver = \"{homeserver}\"; user = \"{user_id}\"")

325 print(f"Failed to log in: {resp}")

326 sys.exit(1)

327

328 print("Logged in using a password. Credentials were stored."

329 "On next execution the stored login credentials will be used.")

330

331 # Otherwise the config file exists, so we'll use the stored credentials

332 else:

333 # open the file in read-only mode

334 with open(CONFIG_FILE,"r") as f:

335 config= json.load(f)

336 # Initialize the matrix client based on credentials from file

337 client= AsyncClient( (continues on next page)

5.2. Examples 143 nio Documentation, Release 0.18.6

(continued from previous page)

338 config['homeserver'],

339 config['user_id'],

340 device_id=config['device_id'],

341 store_path=STORE_PATH,

342 config=client_config,

343 )

344

345 client.restore_login(

346 user_id=config['user_id'],

347 device_id=config['device_id'],

348 access_token=config['access_token']

349 )

350 print("Logged in using stored credentials.")

351

352 return client

353

354

355 async def main()-> None:

356 """Login and wait for and perform emoji verify."""

357 client= await login()

358 # Set up event callbacks

359 callbacks= Callbacks(client)

360 client.add_to_device_callback(

361 callbacks.to_device_callback, (KeyVerificationEvent,))

362 # Sync encryption keys with the server

363 # Required for participating in encrypted rooms

364 if client.should_upload_keys:

365 await client.keys_upload()

366 print("This program is ready and waiting for the other party to initiate"

367 "an emoji verification with us by selecting \"Verify by Emoji\" "

368 "in their Matrix client.")

369 await client.sync_forever(timeout=30000, full_state=True)

370

371 try:

372 asyncio.get_event_loop().run_until_complete(main())

373 except Exception:

374 print(traceback.format_exc())

375 sys.exit(1)

376 except KeyboardInterrupt:

377 print("Received keyboard interrupt.")

378 sys.exit(0)

5.2.7 Further reading and exploration

In an external repo, not maintained by us, is a simple Matix client that includes sending, receiving and verification. It gives an example of • how to send text, images, audio, video, other text files • listen to messages forever • get just the newest unread messages • get the last N messages • perform emoji verification • etc.

144 Chapter 5. Api Documentation nio Documentation, Release 0.18.6

So, if you want more example code and want to explore further have a look at this external repo called matrix- commander. And of course, you should check out all the other projects built with matrix-nio. To do so, check out our built-with-marix-nio list.

5.3 Contributing

There are lots of ways to contribute, from adding new features via pull requests to opening issues for missing features. Check out our issues list and filter for good first issues to find something we think you could tackle. We recommend creating a Python 3 virtual environment (or using pipenv) before you start coding to keep the packages you need for nio separate from the packages you might need for other projects. Throughout the rest of the document, we’ll assume you’re working in your virtual environment.

5.3.1 Prerequisites

You’ll need to install the following: • make • matrix-org/olm version 3.x You’ll also need to install some pip packages: pip install -r test-requirements.txt pip install -r rtd-requirements.txt

5.3.2 Testing

As you write, you may want to test your changes. You can add new tests and test files in tests/ to be picked up by pytest. To run the full test suite (please do this before submitting your pull request!), run make test

If you only want to test your changes (and not run all of the test suite), you can run the following: python3 -m pytest --benchmark-disable tests/your-test.py

5.3.3 Getting ready for a pull request

Get early feedback. You don’t need to perfect your changes to submit them; early feedback can help guide you in the right direction, especially if you’re struggling. Make sure any new classes or methods you’ve added are properly documented, and if you’ve changed any existing methods make sure their docstrings are still up-to-date. It’s really important to have good documentation because you encourage other people to use that great feature you just added! Before you submit your code for discussion, please make sure your code passes the test suite by reading Testing. Next, run make typecheck to verify that mypy is happy with the types in your code. Not sure about an error you got from either? No worries; submit your changes and we’ll talk about it. When ready, push your changes to a fork of poljar/matrix-nio and open up a pull request. Give us a bit of a description of what changes you’ve made and why. If you are trying to close an open issue, you can link to it just by writing “Closes #104” in the description.

5.3. Contributing 145 nio Documentation, Release 0.18.6

5.3.4 Adding documentation

Writing might be hard, but with a few instructions we’ll get you started. As you code, you can just write docstrings in your classes and methods, but if you want to document the architecture of nio (and we’d love if you did!) you can help us write documentation in the reStructuredText format. You’ll need to install Sphinx if you’d like to preview your changes: pip install sphinx

Once that is done, edit the .rst files in doc/ and run make html in the same directory. You’ll now have HTML pages in doc/build/html you can review.

146 Chapter 5. Api Documentation CHAPTER 6

Indices and tables

• genindex • modindex • search

147 nio Documentation, Release 0.18.6

148 Chapter 6. Indices and tables Python Module Index

n nio.client, 24 nio.crypto, 121 nio.event_builders, 99 nio.event_builders.direct_messages, 100 nio.event_builders.state_events, 101 nio.events, 63 nio.events.account_data, 93 nio.events.ephemeral, 91 nio.events.invite_events, 83 nio.events.misc, 63 nio.events.room_events, 65 nio.events.to_device, 85 nio.exceptions, 103 nio.responses, 104 nio.rooms, 61 nio.store, 117

149 nio Documentation, Release 0.18.6

150 Python Module Index Index

A attribute), 102 accept_key_verification() (nio.AsyncClient algorithm (nio.events.room_events.MegolmEvent at- method), 33 tribute), 70 accept_key_verification() (nio.HttpClient algorithm (nio.events.room_events.UnknownEncryptedEvent method), 56 attribute), 82 accept_sas() (nio.crypto.Sas method), 123 algorithm (nio.events.to_device.ForwardedRoomKeyEvent accept_verification() (nio.crypto.Sas method), attribute), 86 123 algorithm (nio.events.to_device.RoomKeyEvent at- access (nio.event_builders.state_events.ChangeGuestAccessBuildertribute), 90 attribute), 101 algorithm (nio.events.to_device.RoomKeyRequest at- access_token (nio.Client attribute), 25 tribute), 90 AccountDataEvent (class in algorithm (nio.responses.RoomKeyRequestResponse nio.events.account_data), 93 attribute), 115 action (nio.events.account_data.PushUnknownAction answer (nio.events.room_events.CallAnswerEvent at- attribute), 98 tribute), 65 actions (nio.events.account_data.PushRule attribute), Api (class in nio), 11 96 as_dict() (nio.crypto.OlmDevice method), 122 active_user_devices() (nio.crypto.DeviceStore as_dict() (nio.event_builders.direct_messages.ToDeviceMessage method), 121 method), 101 add() (nio.crypto.DeviceStore method), 121 as_dict() (nio.event_builders.EventBuilder method), add_ephemeral_callback() (nio.Client method), 100 25 as_dict() (nio.event_builders.state_events.ChangeGuestAccessBuilder add_event_callback() (nio.Client method), 26 method), 101 add_global_account_data_callback() as_dict() (nio.event_builders.state_events.ChangeHistoryVisibilityBuilder (nio.Client method), 26 method), 102 add_member() (nio.rooms.MatrixRoom method), 61 as_dict() (nio.event_builders.state_events.ChangeJoinRulesBuilder add_outgoing_key_request() method), 102 (nio.store.MatrixStore method), 118 as_dict() (nio.event_builders.state_events.ChangeNameBuilder add_presence_callback() (nio.Client method), method), 102 26 as_dict() (nio.event_builders.state_events.ChangeTopicBuilder add_response_callback() (nio.AsyncClient method), 102 method), 34 as_dict() (nio.event_builders.state_events.EnableEncryptionBuilder add_room_account_data_callback() method), 103 (nio.Client method), 26 as_key_request() (nio.events.room_events.MegolmEvent add_to_device_callback() (nio.Client method), method), 70 27 as_value (nio.events.account_data.PushAction at- algorithm (nio.event_builders.direct_messages.RoomKeyRequestMessagetribute), 93 attribute), 100 as_value (nio.events.account_data.PushCoalesce at- algorithm (nio.event_builders.state_events.EnableEncryptionBuildertribute), 94 as_value (nio.events.account_data.PushCondition at-

151 nio Documentation, Release 0.18.6

tribute), 94 C as_value (nio.events.account_data.PushContainsDisplayNamecall_id (nio.events.room_events.CallEvent attribute), attribute), 94 65 as_value (nio.events.account_data.PushDontNotify CallAnswerEvent (class in nio.events.room_events), attribute), 94 65 as_value (nio.events.account_data.PushEventMatch CallCandidatesEvent (class in attribute), 94 nio.events.room_events), 65 as_value (nio.events.account_data.PushNotify at- CallEvent (class in nio.events.room_events), 65 tribute), 95 CallHangupEvent (class in nio.events.room_events), as_value (nio.events.account_data.PushRoomMemberCount 66 attribute), 95 CallInviteEvent (class in nio.events.room_events), as_value (nio.events.account_data.PushSenderNotificationPermission66 attribute), 98 can_user_ban() (nio.events.room_events.PowerLevels as_value (nio.events.account_data.PushSetTweak at- method), 71 tribute), 98 can_user_invite() as_value (nio.events.account_data.PushUnknownAction (nio.events.room_events.PowerLevels method), attribute), 98 71 as_value (nio.events.account_data.PushUnknownConditioncan_user_kick() (nio.events.room_events.PowerLevels attribute), 99 method), 71 AsyncClient (class in nio), 32 can_user_notify() avatar_url (nio.events.room_events.RoomAvatarEvent (nio.events.room_events.PowerLevels method), attribute), 74 71 avatar_url (nio.responses.ProfileGetAvatarResponse can_user_redact() attribute), 114 (nio.events.room_events.PowerLevels method), avatar_url (nio.responses.ProfileGetResponse 71 attribute), 113 can_user_send_message() avatar_url() (nio.rooms.MatrixRoom method), 61 (nio.events.room_events.PowerLevels method), average_speed (nio.TransferMonitor attribute), 55 71 can_user_send_state() B (nio.events.room_events.PowerLevels method), BadEvent (class in nio.events.misc), 63 71 ban (nio.events.room_events.DefaultLevels attribute), 67 cancel (nio.TransferMonitor attribute), 55 BaseRoomKeyRequest (class in cancel() (nio.crypto.Sas method), 123 nio.events.to_device), 85 cancel_key_share() (nio.Client method), 27 blacklist_device() (nio.Client method), 27 cancel_key_verification() (nio.AsyncClient blacklist_device() (nio.store.MatrixStore method), 34 method), 118 cancel_key_verification() (nio.HttpClient blacklisted (nio.crypto.OlmDevice attribute), 122 method), 56 body (nio.events.room_events.RoomEncryptedMedia at- canceled (nio.crypto.Sas attribute), 123 tribute), 75 canonical_alias (nio.events.invite_events.InviteAliasEvent body (nio.events.room_events.RoomMessageEmote at- attribute), 83 tribute), 79 canonical_alias (nio.events.room_events.RoomAliasEvent body (nio.events.room_events.RoomMessageFormatted attribute), 73 attribute), 79 ChangeGuestAccessBuilder (class in body (nio.events.room_events.RoomMessageMedia at- nio.event_builders.state_events), 101 tribute), 80 ChangeHistoryVisibilityBuilder (class in body (nio.events.room_events.RoomMessageNotice at- nio.event_builders.state_events), 101 tribute), 80 ChangeJoinRulesBuilder (class in body (nio.events.room_events.RoomMessageText at- nio.event_builders.state_events), 102 tribute), 80 ChangeNameBuilder (class in body (nio.events.room_events.StickerEvent attribute), 82 nio.event_builders.state_events), 102 body (nio.responses.FileResponse attribute), 104 ChangeTopicBuilder (class in nio.event_builders.state_events), 102 ciphertext (nio.events.room_events.MegolmEvent at-

152 Index nio Documentation, Release 0.18.6

tribute), 70 create_error() (nio.responses.EnablePushRuleResponse ciphertext (nio.events.to_device.OlmEvent at- static method), 105 tribute), 89 create_error() (nio.responses.JoinResponse static Client (class in nio), 25 method), 106 ClientConfig (class in nio), 24 create_error() (nio.responses.PresenceSetResponse close() (nio.AsyncClient method), 34 static method), 115 code (nio.events.to_device.KeyVerificationCancel create_error() (nio.responses.ProfileSetAvatarResponse attribute), 87 static method), 114 commitment (nio.events.to_device.KeyVerificationAccept create_error() (nio.responses.ProfileSetDisplayNameResponse attribute), 86 static method), 113 condition (nio.events.account_data.PushUnknownConditioncreate_error() (nio.responses.RoomBanResponse attribute), 99 static method), 107 conditions (nio.events.account_data.PushRule at- create_error() (nio.responses.RoomForgetResponse tribute), 96 static method), 108 confirm_key_verification() (nio.Client create_error() (nio.responses.RoomGetStateEventResponse method), 27 static method), 109 confirm_short_auth_string() create_error() (nio.responses.RoomGetStateResponse (nio.AsyncClient method), 34 static method), 109 confirm_short_auth_string() (nio.HttpClient create_error() (nio.responses.RoomInviteResponse method), 56 static method), 108 connect() (nio.HttpClient method), 56 create_error() (nio.responses.RoomKickResponse content (nio.event_builders.direct_messages.ToDeviceMessage static method), 108 attribute), 101 create_error() (nio.responses.RoomLeaveResponse content (nio.events.account_data.PushRuleset at- static method), 108 tribute), 97 create_error() (nio.responses.RoomPutStateResponse content (nio.events.account_data.UnknownAccountDataEvent static method), 110 attribute), 99 create_error() (nio.responses.RoomReadMarkersResponse content (nio.events.invite_events.InviteMemberEvent static method), 112 attribute), 84 create_error() (nio.responses.RoomRedactResponse content (nio.events.room_events.RoomMemberEvent static method), 110 attribute), 78 create_error() (nio.responses.RoomSendResponse content (nio.events.room_events.RoomMessageUnknown static method), 111 attribute), 81 create_error() (nio.responses.RoomTypingResponse content (nio.events.room_events.StickerEvent at- static method), 112 tribute), 82 create_error() (nio.responses.RoomUnbanResponse content (nio.responses.RoomGetStateEventResponse static method), 111 attribute), 109 create_error() (nio.responses.SetPushRuleActionsResponse content_repository_config() (nio.Api static static method), 111 method), 11 create_error() (nio.responses.SetPushRuleResponse content_repository_config() static method), 111 (nio.AsyncClient method), 34 create_error() (nio.responses.UpdateDeviceResponse content_type (nio.responses.FileResponse attribute), static method), 112 104 create_error() (nio.responses.UpdateReceiptMarkerResponse ContentRepositoryConfigError (class in static method), 117 nio.responses), 104 create_key_verification() (nio.Client ContentRepositoryConfigResponse (class in method), 28 nio.responses), 104 create_matrix_response() (nio.AsyncClient continue_key_share() (nio.Client method), 28 method), 35 count (nio.events.account_data.PushRoomMemberCount creator (nio.events.room_events.RoomCreateEvent at- attribute), 95 tribute), 74 create_error() (nio.responses.DeleteDevicesResponsecurrently_active (nio.responses.PresenceGetResponse static method), 104 attribute), 114 create_error() (nio.responses.DeletePushRuleResponsecurve25519 (nio.crypto.OlmDevice attribute), 122 static method), 105

Index 153 nio Documentation, Release 0.18.6

D DiscoveryInfoResponse (class in nio.responses), data_to_send() (nio.HttpClient method), 56 105 decrypt_event() (nio.Client method), 28 display_name (nio.crypto.OlmDevice attribute), 122 decrypted (nio.events.misc.BadEvent attribute), 64 display_name (nio.rooms.MatrixRoom attribute), 61 decrypted (nio.events.misc.UnknownBadEvent at- displayname (nio.responses.ProfileGetDisplayNameResponse tribute), 64 attribute), 113 decrypted (nio.events.room_events.Event attribute), displayname (nio.responses.ProfileGetResponse at- 68 tribute), 113 default (nio.events.account_data.PushRule attribute), done (nio.TransferMonitor attribute), 55 96 download() (nio.Api static method), 12 DefaultLevels (class in nio.events.room_events), 66 download() (nio.AsyncClient method), 36 defaults (nio.events.room_events.PowerLevels at- download() (nio.HttpClient method), 56 tribute), 71 DownloadError (class in nio.responses), 105 DefaultStore (class in nio.store), 120 DownloadResponse (class in nio.responses), 105 delete_devices() (nio.Api static method), 11 DummyEvent (class in nio.events.to_device), 85 delete_devices() (nio.AsyncClient method), 35 DummyMessage (class in delete_devices() (nio.HttpClient method), 56 nio.event_builders.direct_messages), 100 delete_encrypted_room() (nio.store.MatrixStore method), 118 E delete_pushrule() (nio.Api static method), 11 ed25519 (nio.crypto.OlmDevice attribute), 122 delete_pushrule() (nio.AsyncClient method), 35 elapsed (nio.responses.Response attribute), 107 deleted (nio.crypto.OlmDevice attribute), 122 enable_pushrule() (nio.Api static method), 12 DeleteDevicesAuthResponse (class in enable_pushrule() (nio.AsyncClient method), 36 nio.responses), 104 enabled (nio.events.account_data.PushRule attribute), DeleteDevicesError (class in nio.responses), 104 96 DeleteDevicesResponse (class in nio.responses), EnableEncryptionBuilder (class in 104 nio.event_builders.state_events), 102 DeletePushRuleError (class in nio.responses), 104 EnablePushRuleError (class in nio.responses), 106 DeletePushRuleResponse (class in nio.responses), EnablePushRuleResponse (class in nio.responses), 104 105 Device (class in nio.responses), 105 encrypt() (nio.Client method), 28 device_from_sender_key() encrypted_mxc_to_plumb() (nio.Api static (nio.crypto.DeviceStore method), 121 method), 12 device_id (nio.crypto.OlmDevice attribute), 122 EncryptedToDeviceEvent (class in device_id (nio.events.room_events.MegolmEvent at- nio.events.to_device), 86 tribute), 70 encryption_enabled (nio.ClientConfig attribute), device_rules (nio.events.account_data.PushRulesEvent 24 attribute), 96 EncryptionError, 103 device_store (nio.Client attribute), 28 end (nio.responses.RoomContextResponse attribute), DeviceList (class in nio.responses), 105 116 DeviceOneTimeKeyCount (class in nio.responses), end_time (nio.responses.Response attribute), 107 105 end_time (nio.TransferMonitor attribute), 55 devices() (nio.Api static method), 12 EphemeralEvent (class in nio.events.ephemeral), 92 devices() (nio.AsyncClient method), 36 ErrorResponse (class in nio.responses), 106 devices() (nio.HttpClient method), 56 Event (class in nio.events.room_events), 67 DevicesError (class in nio.responses), 105 event (nio.responses.RoomContextResponse attribute), DevicesResponse (class in nio.responses), 105 117 DeviceStore (class in nio.crypto), 121 event (nio.responses.RoomGetEventResponse at- disambiguated_name (nio.rooms.MatrixUser tribute), 110 attribute), 63 event_id (nio.events.account_data.FullyReadEvent disconnect() (nio.HttpClient method), 56 attribute), 93 discovery_info() (nio.Api static method), 12 event_id (nio.events.ephemeral.Receipt attribute), 92 discovery_info() (nio.AsyncClient method), 36 event_id (nio.events.misc.BadEvent attribute), 63 DiscoveryInfoError (class in nio.responses), 105 event_id (nio.events.room_events.Event attribute), 68

154 Index nio Documentation, Release 0.18.6 event_id (nio.events.room_events.MegolmEvent at- from_data() (nio.responses.ThumbnailResponse tribute), 69 class method), 115 event_type (nio.events.room_events.RedactedEvent from_device (nio.events.to_device.KeyVerificationStart attribute), 73 attribute), 88 event_type (nio.responses.RoomGetStateEventResponsefrom_dict() (nio.events.account_data.FullyReadEvent attribute), 109 class method), 93 EventBuilder (class in nio.event_builders), 99 from_dict() (nio.events.account_data.PushAction events (nio.events.room_events.PowerLevels attribute), class method), 93 71 from_dict() (nio.events.account_data.PushCondition events (nio.responses.RoomGetStateResponse at- class method), 94 tribute), 109 from_dict() (nio.events.account_data.PushRoomMemberCount events_after (nio.responses.RoomContextResponse class method), 95 attribute), 117 from_dict() (nio.events.account_data.PushRule events_before (nio.responses.RoomContextResponse class method), 96 attribute), 116 from_dict() (nio.events.account_data.PushRuleset events_default (nio.events.room_events.DefaultLevels class method), 97 attribute), 67 from_dict() (nio.events.account_data.PushRulesEvent expired (nio.events.room_events.CallInviteEvent at- class method), 97 tribute), 66 from_dict() (nio.events.account_data.TagEvent export_keys() (nio.AsyncClient method), 37 class method), 99 export_keys() (nio.Client method), 29 from_dict() (nio.events.account_data.UnknownAccountDataEvent class method), 99 F from_dict() (nio.events.ephemeral.EphemeralEvent federate (nio.events.room_events.RoomCreateEvent class method), 92 attribute), 74 from_dict() (nio.events.ephemeral.ReceiptEvent filename (nio.responses.FileResponse attribute), 104 class method), 92 FileResponse (class in nio.responses), 104 from_dict() (nio.events.ephemeral.TypingNoticeEvent filter_id (nio.responses.UploadFilterResponse at- class method), 93 tribute), 117 from_dict() (nio.events.invite_events.InviteAliasEvent flattened() (nio.events.room_events.Event method), class method), 83 68 from_dict() (nio.events.invite_events.InviteEvent format (nio.events.room_events.RoomMessageEmote class method), 84 attribute), 79 from_dict() (nio.events.invite_events.InviteMemberEvent format (nio.events.room_events.RoomMessageFormatted class method), 84 attribute), 79 from_dict() (nio.events.invite_events.InviteNameEvent format (nio.events.room_events.RoomMessageNotice class method), 85 attribute), 80 from_dict() (nio.events.room_events.CallAnswerEvent format (nio.events.room_events.RoomMessageText at- class method), 65 tribute), 81 from_dict() (nio.events.room_events.CallCandidatesEvent formatted_body (nio.events.room_events.RoomMessageEmote class method), 65 attribute), 79 from_dict() (nio.events.room_events.CallHangupEvent formatted_body (nio.events.room_events.RoomMessageFormattedclass method), 66 attribute), 79 from_dict() (nio.events.room_events.CallInviteEvent formatted_body (nio.events.room_events.RoomMessageNotice class method), 66 attribute), 80 from_dict() (nio.events.room_events.DefaultLevels formatted_body (nio.events.room_events.RoomMessageText class method), 67 attribute), 80 from_dict() (nio.events.room_events.Event class ForwardedRoomKeyEvent (class in method), 69 nio.events.to_device), 86 from_dict() (nio.events.room_events.MegolmEvent from_data() (nio.responses.DownloadResponse class class method), 71 method), 105 from_dict() (nio.events.room_events.PowerLevelsEvent from_data() (nio.responses.FileResponse class class method), 72 method), 104 from_dict() (nio.events.room_events.RedactedEvent class method), 73

Index 155 nio Documentation, Release 0.18.6 from_dict() (nio.events.room_events.RedactionEvent from_dict() (nio.events.to_device.RoomKeyRequest class method), 73 class method), 90 from_dict() (nio.events.room_events.RoomAliasEvent from_dict() (nio.events.to_device.RoomKeyRequestCancellation class method), 73 class method), 91 from_dict() (nio.events.room_events.RoomAvatarEventfrom_dict() (nio.events.to_device.ToDeviceEvent class method), 74 class method), 91 from_dict() (nio.events.room_events.RoomCreateEventfrom_dict() (nio.responses.ContentRepositoryConfigResponse class method), 74 class method), 104 from_dict() (nio.events.room_events.RoomEncryptedMediafrom_dict() (nio.responses.DeleteDevicesAuthResponse class method), 76 class method), 104 from_dict() (nio.events.room_events.RoomEncryptionEventfrom_dict() (nio.responses.Device class method), class method), 76 105 from_dict() (nio.events.room_events.RoomGuestAccessEventfrom_dict() (nio.responses.DevicesResponse class class method), 77 method), 105 from_dict() (nio.events.room_events.RoomHistoryVisibilityEventfrom_dict() (nio.responses.DiscoveryInfoResponse class method), 77 class method), 105 from_dict() (nio.events.room_events.RoomJoinRulesEventfrom_dict() (nio.responses.ErrorResponse class class method), 77 method), 106 from_dict() (nio.events.room_events.RoomMemberEventfrom_dict() (nio.responses.JoinedMembersResponse class method), 78 class method), 106 from_dict() (nio.events.room_events.RoomMessageFormattedfrom_dict() (nio.responses.JoinedRoomsResponse class method), 79 class method), 106 from_dict() (nio.events.room_events.RoomMessageMediafrom_dict() (nio.responses.KeysClaimResponse class method), 80 class method), 106 from_dict() (nio.events.room_events.RoomMessageUnknownfrom_dict() (nio.responses.KeysQueryResponse class method), 81 class method), 106 from_dict() (nio.events.room_events.RoomNameEvent from_dict() (nio.responses.KeysUploadResponse class method), 81 class method), 107 from_dict() (nio.events.room_events.RoomTopicEvent from_dict() (nio.responses.LoginInfoResponse class class method), 82 method), 107 from_dict() (nio.events.room_events.StickerEvent from_dict() (nio.responses.LoginResponse class class method), 82 method), 107 from_dict() (nio.events.room_events.UnknownEncryptedEventfrom_dict() (nio.responses.LogoutResponse class class method), 82 method), 107 from_dict() (nio.events.room_events.UnknownEvent from_dict() (nio.responses.PresenceGetResponse class method), 83 class method), 114 from_dict() (nio.events.to_device.DummyEvent from_dict() (nio.responses.ProfileGetAvatarResponse class method), 86 class method), 114 from_dict() (nio.events.to_device.ForwardedRoomKeyEventfrom_dict() (nio.responses.ProfileGetDisplayNameResponse class method), 86 class method), 113 from_dict() (nio.events.to_device.KeyVerificationAcceptfrom_dict() (nio.responses.ProfileGetResponse class class method), 87 method), 113 from_dict() (nio.events.to_device.KeyVerificationCancelfrom_dict() (nio.responses.RegisterResponse class class method), 87 method), 107 from_dict() (nio.events.to_device.KeyVerificationKey from_dict() (nio.responses.RoomContextResponse class method), 88 class method), 117 from_dict() (nio.events.to_device.KeyVerificationMac from_dict() (nio.responses.RoomCreateResponse class method), 88 class method), 108 from_dict() (nio.events.to_device.KeyVerificationStart from_dict() (nio.responses.RoomGetEventResponse class method), 89 class method), 110 from_dict() (nio.events.to_device.OlmEvent class from_dict() (nio.responses.RoomGetStateEventResponse method), 89 class method), 109 from_dict() (nio.events.to_device.RoomKeyEvent from_dict() (nio.responses.RoomGetStateResponse class method), 90 class method), 109

156 Index nio Documentation, Release 0.18.6 from_dict() (nio.responses.RoomKeyRequestResponse get_timeout_retry_wait_time() class method), 115 (nio.AsyncClient method), 38 from_dict() (nio.responses.RoomMessagesResponse get_user_level() (nio.events.room_events.PowerLevels class method), 109 method), 72 from_dict() (nio.responses.RoomResolveAliasResponseget_users_for_key_claiming() (nio.Client class method), 110 method), 30 from_dict() (nio.responses.ShareGroupSessionError global_rules (nio.events.account_data.PushRulesEvent class method), 112 attribute), 96 from_dict() (nio.responses.ShareGroupSessionResponsegroup_name() (nio.rooms.MatrixRoom method), 62 class method), 111 group_name_structure() from_dict() (nio.responses.SyncResponse class (nio.rooms.MatrixRoom method), 62 method), 112 GroupEncryptionError, 103 from_dict() (nio.responses.ToDeviceError class guest_access (nio.events.room_events.RoomGuestAccessEvent method), 116 attribute), 76, 77 from_dict() (nio.responses.ToDeviceResponse class method), 116 H from_dict() (nio.responses.UploadFilterResponse handle_account_data() (nio.rooms.MatrixRoom class method), 117 method), 62 from_dict() (nio.responses.UploadResponse class handle_ephemeral_event() method), 113 (nio.rooms.MatrixRoom method), 62 from_key_verification_start() handle_event() (nio.rooms.MatrixInvitedRoom (nio.crypto.Sas class method), 123 method), 63 FullyReadEvent (class in nio.events.account_data), handle_event() (nio.rooms.MatrixRoom method), 93 62 handle_key_upload_error() (nio.HttpClient G method), 57 gen_avatar_url (nio.rooms.MatrixRoom attribute), handle_membership() 62 (nio.rooms.MatrixInvitedRoom method), get_active_key_requests() (nio.Client 63 method), 29 handle_membership() (nio.rooms.MatrixRoom get_active_sas() (nio.Client method), 29 method), 62 get_avatar() (nio.AsyncClient method), 37 hash (nio.events.to_device.KeyVerificationAccept get_avatar() (nio.HttpClient method), 57 attribute), 87 get_cancellation() (nio.crypto.Sas method), 124 hashes (nio.events.room_events.RoomEncryptedMedia get_decimals() (nio.crypto.Sas method), 124 attribute), 75 get_displayname() (nio.AsyncClient method), 37 hashes (nio.events.to_device.KeyVerificationStart at- get_displayname() (nio.HttpClient method), 57 tribute), 89 get_emoji() (nio.crypto.Sas method), 124 heroes (nio.responses.RoomSummary attribute), 111 get_mac() (nio.crypto.Sas method), 124 history_visibility get_message_event_required_level() (nio.events.room_events.RoomHistoryVisibilityEvent (nio.events.room_events.PowerLevels method), attribute), 77 72 homeserver_url (nio.responses.DiscoveryInfoResponse get_missing_sessions() (nio.Client method), 30 attribute), 105 get_notification_required_level() HttpClient (class in nio), 56 (nio.events.room_events.PowerLevels method), 72 I get_presence() (nio.Api static method), 13 id (nio.crypto.OlmDevice attribute), 122 get_presence() (nio.AsyncClient method), 37 id (nio.events.account_data.PushRule attribute), 95 get_profile() (nio.AsyncClient method), 38 identity_server_url get_profile() (nio.HttpClient method), 57 (nio.responses.DiscoveryInfoResponse at- get_state_event_required_level() tribute), 105 (nio.events.room_events.PowerLevels method), ignore_device() (nio.Client method), 30 72 ignore_device() (nio.store.MatrixStore method), 118

Index 157 nio Documentation, Release 0.18.6 ignore_devices() (nio.store.MatrixStore method), JoinedRoomsResponse (class in nio.responses), 106 118 JoinError (class in nio.responses), 106 ignored (nio.crypto.OlmDevice attribute), 122 JoinResponse (class in nio.responses), 106 import_keys() (nio.AsyncClient method), 38 import_keys() (nio.Client method), 30 K invalidate_outbound_session() (nio.Client key (nio.events.account_data.PushEventMatch at- method), 30 tribute), 94 invite (nio.events.room_events.DefaultLevels at- key (nio.events.account_data.PushSenderNotificationPermission tribute), 67 attribute), 97 InviteAliasEvent (class in key (nio.events.room_events.RoomEncryptedMedia at- nio.events.invite_events), 83 tribute), 75 invited_count (nio.rooms.MatrixRoom attribute), key (nio.events.to_device.KeyVerificationKey attribute), 62 88 invited_member_count key_agreement_protocol (nio.responses.RoomSummary attribute), (nio.events.to_device.KeyVerificationAccept 111 attribute), 87 invited_rooms (nio.Client attribute), 25 key_agreement_protocols InviteEvent (class in nio.events.invite_events), 83 (nio.events.to_device.KeyVerificationStart InviteInfo (class in nio.responses), 106 attribute), 88 InviteMemberEvent (class in key_verifications (nio.Client attribute), 30 nio.events.invite_events), 84 keys (nio.crypto.OlmDevice attribute), 122 InviteNameEvent (class in nio.events.invite_events), keys (nio.events.to_device.KeyVerificationMac at- 84 tribute), 88 is_device_blacklisted() (nio.store.MatrixStore keys_claim() (nio.Api static method), 13 method), 118 keys_claim() (nio.AsyncClient method), 39 is_device_ignored() (nio.store.MatrixStore keys_claim() (nio.HttpClient method), 57 method), 118 keys_query() (nio.Api static method), 14 is_device_verified() (nio.store.MatrixStore keys_query() (nio.AsyncClient method), 39 method), 118 keys_query() (nio.HttpClient method), 57 is_group (nio.rooms.MatrixRoom attribute), 62 keys_upload() (nio.Api static method), 14 is_named (nio.rooms.MatrixRoom attribute), 62 keys_upload() (nio.AsyncClient method), 39 items() (nio.crypto.DeviceStore method), 121 keys_upload() (nio.HttpClient method), 57 iv (nio.events.room_events.RoomEncryptedMedia at- KeysClaimError (class in nio.responses), 106 tribute), 75 KeysClaimResponse (class in nio.responses), 106 KeysQueryError (class in nio.responses), 107 J KeysQueryResponse (class in nio.responses), 106 join() (nio.Api static method), 13 KeysUploadError (class in nio.responses), 107 join() (nio.AsyncClient method), 38 KeysUploadResponse (class in nio.responses), 107 join() (nio.HttpClient method), 57 KeyVerificationAccept (class in join_rule (nio.events.room_events.RoomJoinRulesEvent nio.events.to_device), 86 attribute), 77 KeyVerificationCancel (class in joined_count (nio.rooms.MatrixRoom attribute), 62 nio.events.to_device), 87 joined_member_count KeyVerificationEvent (class in (nio.responses.RoomSummary attribute), nio.events.to_device), 87 111 KeyVerificationKey (class in joined_members() (nio.Api static method), 13 nio.events.to_device), 87 joined_members() (nio.AsyncClient method), 38 KeyVerificationMac (class in joined_members() (nio.HttpClient method), 57 nio.events.to_device), 88 joined_rooms() (nio.Api static method), 13 KeyVerificationStart (class in joined_rooms() (nio.AsyncClient method), 38 nio.events.to_device), 88 JoinedMembersError (class in nio.responses), 106 kick (nio.events.room_events.DefaultLevels attribute), JoinedMembersResponse (class in nio.responses), 67 106 kind (nio.events.account_data.PushRule attribute), 95 JoinedRoomsError (class in nio.responses), 106

158 Index nio Documentation, Release 0.18.6

L matches() (nio.events.account_data.PushSenderNotificationPermission lag (nio.HttpClient attribute), 57 method), 98 last_active_ago (nio.responses.PresenceGetResponsematching_rule() (nio.events.account_data.PushRuleset attribute), 114 method), 97 lifetime (nio.events.room_events.CallInviteEvent at- MatrixInvitedRoom (class in nio.rooms), 63 tribute), 66 MatrixRoom (class in nio.rooms), 61 load_account() (nio.store.MatrixStore method), 118 MatrixStore (class in nio.store), 117 load_device_keys() (nio.store.MatrixStore MatrixUser (class in nio.rooms), 63 method), 118 MegolmEvent (class in nio.events.room_events), 69 load_encrypted_rooms() (nio.store.MatrixStore member_count (nio.rooms.MatrixRoom attribute), 62 method), 118 membership (nio.events.invite_events.InviteMemberEvent load_inbound_group_sessions() attribute), 84 (nio.store.MatrixStore method), 118 membership (nio.events.room_events.RoomMemberEvent load_outgoing_key_requests() attribute), 78 (nio.store.MatrixStore method), 119 MembersSyncError, 103 load_sessions() (nio.store.MatrixStore method), message_authentication_code 119 (nio.events.to_device.KeyVerificationAccept load_store() (nio.Client method), 30 attribute), 87 LocalProtocolError, 103 message_authentication_codes LocalTransportError, 103 (nio.events.to_device.KeyVerificationStart logged_in (nio.Client attribute), 30 attribute), 89 login() (nio.Api static method), 14 method (nio.events.to_device.KeyVerificationStart at- login() (nio.AsyncClient method), 39 tribute), 88 login() (nio.HttpClient method), 57 mimetype (nio.events.room_events.RoomEncryptedMedia login_info() (nio.Api static method), 14 attribute), 75 login_info() (nio.AsyncClient method), 39 mimetype_to_msgtype() (nio.Api static method), login_info() (nio.HttpClient method), 57 15 login_raw() (nio.Api static method), 14 msgtype (nio.events.room_events.RoomMessageUnknown login_raw() (nio.AsyncClient method), 40 attribute), 81 login_raw() (nio.HttpClient method), 58 mxc_to_http() (nio.Api static method), 15 LoginError (class in nio.responses), 107 mxc_to_http() (nio.AsyncClient method), 40 LoginInfoError (class in nio.responses), 107 LoginInfoResponse (class in nio.responses), 107 N LoginResponse (class in nio.responses), 107 name (nio.event_builders.state_events.ChangeNameBuilder logout() (nio.Api static method), 15 attribute), 102 logout() (nio.AsyncClient method), 40 name (nio.events.invite_events.InviteNameEvent at- logout() (nio.HttpClient method), 58 tribute), 85 LogoutError (class in nio.responses), 107 name (nio.events.room_events.RoomNameEvent at- LogoutResponse (class in nio.responses), 107 tribute), 81 name (nio.rooms.MatrixUser attribute), 63 M named_room_name() (nio.rooms.MatrixRoom mac (nio.events.to_device.KeyVerificationMac attribute), method), 62 88 next_batch (nio.Client attribute), 25 machine_name (nio.rooms.MatrixRoom attribute), 62 next_response() (nio.HttpClient method), 58 matches() (nio.events.account_data.PushCondition nio.client (module), 24 method), 94 nio.crypto (module), 121 matches() (nio.events.account_data.PushContainsDisplayNamenio.event_builders (module), 99 method), 94 nio.event_builders.direct_messages (mod- matches() (nio.events.account_data.PushEventMatch ule), 100 method), 95 nio.event_builders.state_events (module), matches() (nio.events.account_data.PushRoomMemberCount 101 method), 95 nio.events (module), 63 matches() (nio.events.account_data.PushRule nio.events.account_data (module), 93 method), 96 nio.events.ephemeral (module), 91

Index 159 nio Documentation, Release 0.18.6

nio.events.invite_events (module), 83 parse_event() (nio.events.invite_events.InviteEvent nio.events.misc (module), 63 class method), 84 nio.events.room_events (module), 65 parse_event() (nio.events.room_events.CallEvent nio.events.to_device (module), 85 static method), 66 nio.exceptions (module), 103 parse_event() (nio.events.room_events.Event class nio.responses (module), 104 method), 69 nio.rooms (module), 61 parse_event() (nio.events.room_events.RoomMessage nio.store (module), 117 class method), 78 notifications (nio.events.room_events.DefaultLevels parse_event() (nio.events.to_device.BaseRoomKeyRequest attribute), 67 class method), 85 parse_event() (nio.events.to_device.ToDeviceEvent O class method), 91 offer (nio.events.room_events.CallInviteEvent at- pattern (nio.events.account_data.PushEventMatch at- tribute), 66 tribute), 94 olm_account_shared (nio.Client attribute), 31 pattern (nio.events.account_data.PushRule attribute), OlmDevice (class in nio.crypto), 122 96 OlmEvent (class in nio.events.to_device), 89 pause (nio.TransferMonitor attribute), 55, 56 OlmTrustError, 103 percent_done (nio.TransferMonitor attribute), 56 OlmUnverifiedDeviceError, 103 pickle_key (nio.ClientConfig attribute), 24 on_speed_changed (nio.TransferMonitor attribute), power_levels (nio.events.room_events.PowerLevelsEvent 55 attribute), 72 on_transferred (nio.TransferMonitor attribute), 55 PowerLevels (class in nio.events.room_events), 71 operator (nio.events.account_data.PushRoomMemberCountPowerLevelsEvent (class in attribute), 95 nio.events.room_events), 72 other_info (nio.responses.ProfileGetResponse presence (nio.responses.PresenceGetResponse at- attribute), 113 tribute), 114 outgoing_key_requests (nio.Client attribute), 31 PresenceGetError (class in nio.responses), 114 outgoing_to_device_messages (nio.Client at- PresenceGetResponse (class in nio.responses), 114 tribute), 31 PresenceSetError (class in nio.responses), 115 override (nio.events.account_data.PushRuleset PresenceSetResponse (class in nio.responses), 115 attribute), 97 prev_content (nio.events.invite_events.InviteMemberEvent attribute), 84 P prev_content (nio.events.room_events.RoomMemberEvent parse_account_data() (nio.responses.RoomInfo attribute), 78 static method), 108 prev_membership (nio.events.invite_events.InviteMemberEvent parse_body() (nio.AsyncClient method), 40 attribute), 84 parse_body() (nio.HttpClient method), 58 prev_membership (nio.events.room_events.RoomMemberEvent parse_decrypted_event() attribute), 78 (nio.events.room_events.Event class method), profile_get() (nio.Api static method), 15 69 profile_get_avatar() (nio.Api static method), 15 parse_decrypted_event() profile_get_displayname() (nio.Api static (nio.events.room_events.RoomMessage class method), 15 method), 78 profile_set_avatar() (nio.Api static method), 16 parse_encrypted_event() profile_set_displayname() (nio.Api static (nio.events.room_events.Event class method), method), 16 69 ProfileGetAvatarError (class in nio.responses), parse_encrypted_event() 114 (nio.events.to_device.ToDeviceEvent class ProfileGetAvatarResponse (class in method), 91 nio.responses), 114 parse_event() (nio.events.account_data.AccountDataEventProfileGetDisplayNameError (class in class method), 93 nio.responses), 113 parse_event() (nio.events.ephemeral.EphemeralEvent ProfileGetDisplayNameResponse (class in class method), 92 nio.responses), 113 ProfileGetError (class in nio.responses), 113

160 Index nio Documentation, Release 0.18.6

ProfileGetResponse (class in nio.responses), 113 receive_response() (nio.AsyncClient method), 40 ProfileSetAvatarError (class in nio.responses), receive_response() (nio.Client method), 31 114 recipient (nio.event_builders.direct_messages.ToDeviceMessage ProfileSetAvatarResponse (class in attribute), 101 nio.responses), 114 recipient_device (nio.event_builders.direct_messages.ToDeviceMessage ProfileSetDisplayNameError (class in attribute), 101 nio.responses), 113 redact (nio.events.room_events.DefaultLevels at- ProfileSetDisplayNameResponse (class in tribute), 67 nio.responses), 113 RedactedEvent (class in nio.events.room_events), 72 ProtocolError, 103 redacter (nio.events.room_events.RedactedEvent at- PushAction (class in nio.events.account_data), 93 tribute), 73 PushCoalesce (class in nio.events.account_data), 93 RedactionEvent (class in nio.events.room_events), PushCondition (class in nio.events.account_data), 94 73 PushContainsDisplayName (class in redacts (nio.events.room_events.RedactionEvent at- nio.events.account_data), 94 tribute), 73 PushDontNotify (class in nio.events.account_data), register() (nio.Api static method), 16 94 register() (nio.AsyncClient method), 41 PushEventMatch (class in nio.events.account_data), RegisterResponse (class in nio.responses), 107 94 reject_sas() (nio.crypto.Sas method), 124 PushNotify (class in nio.events.account_data), 95 remaining (nio.TransferMonitor attribute), 56 PushRoomMemberCount (class in remaining_time (nio.TransferMonitor attribute), 56 nio.events.account_data), 95 RemoteProtocolError, 103 PushRule (class in nio.events.account_data), 95 RemoteTransportError, 103 PushRuleset (class in nio.events.account_data), 97 remove_member() (nio.rooms.MatrixRoom method), PushRulesEvent (class in nio.events.account_data), 62 96 remove_outgoing_key_request() PushSenderNotificationPermission (class in (nio.store.MatrixStore method), 119 nio.events.account_data), 97 request_id (nio.event_builders.direct_messages.RoomKeyRequestMessage PushSetTweak (class in nio.events.account_data), 98 attribute), 100 PushUnknownAction (class in request_id (nio.responses.RoomKeyRequestResponse nio.events.account_data), 98 attribute), 115 PushUnknownCondition (class in request_room_key() (nio.AsyncClient method), 41 nio.events.account_data), 98 request_room_key() (nio.HttpClient method), 58 Response (class in nio.responses), 107 R restore_login() (nio.Client method), 31 reason (nio.events.room_events.RedactedEvent at- retry_after_ms (nio.responses.ErrorResponse at- tribute), 73 tribute), 106 reason (nio.events.room_events.RedactionEvent room (nio.events.account_data.PushRuleset attribute), attribute), 73 97 reason (nio.events.to_device.KeyVerificationCancel at- room_alias (nio.responses.RoomResolveAliasResponse tribute), 87 attribute), 110 Receipt (class in nio.events.ephemeral), 92 room_ban() (nio.Api static method), 16 receipt_type (nio.events.ephemeral.Receipt at- room_ban() (nio.AsyncClient method), 41 tribute), 92 room_contains_unverified() (nio.Client ReceiptEvent (class in nio.events.ephemeral), 92 method), 31 receipts (nio.events.ephemeral.ReceiptEvent at- room_context() (nio.Api static method), 16 tribute), 92 room_context() (nio.AsyncClient method), 41 receive() (nio.HttpClient method), 58 room_create() (nio.Api static method), 17 receive_accept_event() (nio.crypto.Sas room_create() (nio.AsyncClient method), 42 method), 124 room_create() (nio.HttpClient method), 58 receive_key_event() (nio.crypto.Sas method), room_devices() (nio.Client method), 31 124 room_forget() (nio.Api static method), 17 receive_mac_event() (nio.crypto.Sas method), room_forget() (nio.AsyncClient method), 42 124 room_forget() (nio.HttpClient method), 59

Index 161 nio Documentation, Release 0.18.6 room_get_event() (nio.Api static method), 17 room_resolve_alias() (nio.Api static method), 20 room_get_event() (nio.AsyncClient method), 43 room_resolve_alias() (nio.AsyncClient method), room_get_state() (nio.Api static method), 18 46 room_get_state() (nio.AsyncClient method), 43 room_send() (nio.Api static method), 20 room_get_state_event() (nio.Api static method), room_send() (nio.AsyncClient method), 46 18 room_send() (nio.HttpClient method), 60 room_get_state_event() (nio.AsyncClient room_typing() (nio.Api static method), 20 method), 43 room_typing() (nio.AsyncClient method), 46 room_id (nio.event_builders.direct_messages.RoomKeyRequestMessageroom_typing() (nio.HttpClient method), 60 attribute), 100 room_unban() (nio.Api static method), 20 room_id (nio.events.room_events.MegolmEvent at- room_unban() (nio.AsyncClient method), 47 tribute), 70, 71 room_version (nio.events.room_events.RoomCreateEvent room_id (nio.events.to_device.ForwardedRoomKeyEvent attribute), 74 attribute), 86 RoomAliasEvent (class in nio.events.room_events), room_id (nio.events.to_device.RoomKeyEvent at- 73 tribute), 90 RoomAvatarEvent (class in nio.events.room_events), room_id (nio.events.to_device.RoomKeyRequest 74 attribute), 90 RoomBanError (class in nio.responses), 107 room_id (nio.responses.KeysClaimResponse attribute), RoomBanResponse (class in nio.responses), 107 106 RoomContextError (class in nio.responses), 117 room_id (nio.responses.RoomContextResponse at- RoomContextResponse (class in nio.responses), 116 tribute), 116 RoomCreateError (class in nio.responses), 108 room_id (nio.responses.RoomGetStateEventResponse RoomCreateEvent (class in nio.events.room_events), attribute), 109 74 room_id (nio.responses.RoomGetStateResponse at- RoomCreateResponse (class in nio.responses), 108 tribute), 109 RoomEncryptedAudio (class in room_id (nio.responses.RoomKeyRequestResponse at- nio.events.room_events), 74 tribute), 115 RoomEncryptedFile (class in room_id (nio.responses.RoomResolveAliasResponse at- nio.events.room_events), 74 tribute), 110 RoomEncryptedImage (class in room_id (nio.responses.ShareGroupSessionResponse nio.events.room_events), 75 attribute), 111 RoomEncryptedMedia (class in room_invite() (nio.Api static method), 18 nio.events.room_events), 75 room_invite() (nio.AsyncClient method), 43 RoomEncryptedVideo (class in room_invite() (nio.HttpClient method), 59 nio.events.room_events), 76 room_kick() (nio.Api static method), 18 RoomEncryptionEvent (class in room_kick() (nio.AsyncClient method), 44 nio.events.room_events), 76 room_kick() (nio.HttpClient method), 59 RoomForgetError (class in nio.responses), 108 room_leave() (nio.Api static method), 18 RoomForgetResponse (class in nio.responses), 108 room_leave() (nio.AsyncClient method), 44 RoomGetEventError (class in nio.responses), 110 room_leave() (nio.HttpClient method), 59 RoomGetEventResponse (class in nio.responses), room_messages() (nio.Api static method), 19 110 room_messages() (nio.AsyncClient method), 44 RoomGetStateError (class in nio.responses), 109 room_messages() (nio.HttpClient method), 59 RoomGetStateEventError (class in nio.responses), room_put_state() (nio.Api static method), 19 109 room_put_state() (nio.AsyncClient method), 45 RoomGetStateEventResponse (class in room_put_state() (nio.HttpClient method), 59 nio.responses), 109 room_read_markers() (nio.Api static method), 19 RoomGetStateResponse (class in nio.responses), room_read_markers() (nio.AsyncClient method), 109 45 RoomGuestAccessEvent (class in room_read_markers() (nio.HttpClient method), 59 nio.events.room_events), 76 room_redact() (nio.Api static method), 19 RoomHistoryVisibilityEvent (class in room_redact() (nio.AsyncClient method), 45 nio.events.room_events), 77 room_redact() (nio.HttpClient method), 60 RoomInfo (class in nio.responses), 108

162 Index nio Documentation, Release 0.18.6

RoomInviteError (class in nio.responses), 108 RoomResolveAliasError (class in nio.responses), RoomInviteResponse (class in nio.responses), 108 110 RoomJoinRulesEvent (class in RoomResolveAliasResponse (class in nio.events.room_events), 77 nio.responses), 110 RoomKeyEvent (class in nio.events.to_device), 89 Rooms (class in nio.responses), 111 RoomKeyRequest (class in nio.events.to_device), 90 rooms (nio.Client attribute), 25 RoomKeyRequestCancellation (class in rooms (nio.responses.JoinedRoomsResponse attribute), nio.events.to_device), 91 106 RoomKeyRequestError (class in nio.responses), 115 RoomSendError (class in nio.responses), 111 RoomKeyRequestMessage (class in RoomSendResponse (class in nio.responses), 111 nio.event_builders.direct_messages), 100 RoomSummary (class in nio.responses), 111 RoomKeyRequestResponse (class in nio.responses), RoomTopicEvent (class in nio.events.room_events), 115 81 RoomKickError (class in nio.responses), 108 RoomTypingError (class in nio.responses), 112 RoomKickResponse (class in nio.responses), 108 RoomTypingResponse (class in nio.responses), 112 RoomLeaveError (class in nio.responses), 108 RoomUnbanError (class in nio.responses), 111 RoomLeaveResponse (class in nio.responses), 108 RoomUnbanResponse (class in nio.responses), 111 RoomMember (class in nio.responses), 108 rotation_ms (nio.event_builders.state_events.EnableEncryptionBuilder RoomMemberEvent (class in nio.events.room_events), attribute), 103 77 rotation_msgs (nio.event_builders.state_events.EnableEncryptionBuilder RoomMessage (class in nio.events.room_events), 78 attribute), 103 RoomMessageAudio (class in rule (nio.event_builders.state_events.ChangeJoinRulesBuilder nio.events.room_events), 79 attribute), 102 RoomMessageEmote (class in run_response_callbacks() (nio.AsyncClient nio.events.room_events), 79 method), 47 RoomMessageFile (class in nio.events.room_events), 79 S RoomMessageFormatted (class in Sas (class in nio.crypto), 123 nio.events.room_events), 79 sas_accepted (nio.crypto.Sas attribute), 123 RoomMessageImage (class in save_account() (nio.store.MatrixStore method), 119 nio.events.room_events), 80 save_device_keys() (nio.store.MatrixStore RoomMessageMedia (class in method), 119 nio.events.room_events), 80 save_encrypted_rooms() (nio.store.MatrixStore RoomMessageNotice (class in method), 119 nio.events.room_events), 80 save_inbound_group_session() RoomMessagesError (class in nio.responses), 109 (nio.store.MatrixStore method), 119 RoomMessagesResponse (class in nio.responses), save_session() (nio.store.MatrixStore method), 119 108 save_sync_token() (nio.store.MatrixStore RoomMessageText (class in nio.events.room_events), method), 119 80 send() (nio.AsyncClient method), 47 RoomMessageUnknown (class in send_to_device_messages() (nio.AsyncClient nio.events.room_events), 81 method), 47 RoomMessageVideo (class in sender (nio.events.account_data.PushRuleset at- nio.events.room_events), 81 tribute), 97 RoomNameEvent (class in nio.events.room_events), 81 sender (nio.events.invite_events.InviteEvent attribute), RoomPutStateError (class in nio.responses), 110 84 RoomPutStateResponse (class in nio.responses), sender (nio.events.misc.BadEvent attribute), 63 110 sender (nio.events.room_events.Event attribute), 68 RoomReadMarkersError (class in nio.responses), sender (nio.events.room_events.MegolmEvent at- 112 tribute), 70 RoomReadMarkersResponse (class in sender (nio.events.to_device.DummyEvent attribute), nio.responses), 112 85 RoomRedactError (class in nio.responses), 110 sender (nio.events.to_device.ForwardedRoomKeyEvent RoomRedactResponse (class in nio.responses), 110 attribute), 86

Index 163 nio Documentation, Release 0.18.6

sender (nio.events.to_device.OlmEvent attribute), 89 set_pushrule() (nio.Api static method), 21 sender (nio.events.to_device.RoomKeyEvent attribute), set_pushrule() (nio.AsyncClient method), 48 90 set_pushrule_actions() (nio.Api static method), sender (nio.events.to_device.ToDeviceEvent attribute), 21 91 set_pushrule_actions() (nio.AsyncClient sender_key (nio.events.misc.BadEvent attribute), 64 method), 49 sender_key (nio.events.misc.UnknownBadEvent at- SetPushRuleActionsError (class in tribute), 65 nio.responses), 111 sender_key (nio.events.room_events.Event attribute), SetPushRuleActionsResponse (class in 68, 69 nio.responses), 111 sender_key (nio.events.room_events.MegolmEvent at- SetPushRuleError (class in nio.responses), 111 tribute), 70 SetPushRuleResponse (class in nio.responses), 111 sender_key (nio.events.to_device.DummyEvent share_group_session() (nio.AsyncClient attribute), 85 method), 50 sender_key (nio.events.to_device.ForwardedRoomKeyEventshare_group_session() (nio.HttpClient method), attribute), 86 60 sender_key (nio.events.to_device.OlmEvent at- share_key() (nio.crypto.Sas method), 124 tribute), 89 ShareGroupSessionError (class in nio.responses), sender_key (nio.events.to_device.RoomKeyEvent at- 112 tribute), 90 ShareGroupSessionResponse (class in sender_key (nio.events.to_device.RoomKeyRequest nio.responses), 111 attribute), 90 short_authentication_string SendRetryError, 103 (nio.events.to_device.KeyVerificationAccept server_timestamp (nio.events.misc.BadEvent at- attribute), 87 tribute), 64 short_authentication_string server_timestamp (nio.events.room_events.Event (nio.events.to_device.KeyVerificationStart attribute), 68 attribute), 89 server_timestamp (nio.events.room_events.MegolmEventshould_claim_keys (nio.Client attribute), 31 attribute), 70 should_query_keys (nio.Client attribute), 31 servers (nio.responses.RoomResolveAliasResponse at- should_upload_keys (nio.Client attribute), 32 tribute), 110 soft_logout (nio.responses.ErrorResponse at- session_id (nio.event_builders.direct_messages.RoomKeyRequestMessagetribute), 106 attribute), 100 source (nio.events.invite_events.InviteEvent attribute), session_id (nio.events.misc.BadEvent attribute), 64 83 session_id (nio.events.misc.UnknownBadEvent at- source (nio.events.misc.BadEvent attribute), 63 tribute), 65 source (nio.events.misc.UnknownBadEvent attribute), session_id (nio.events.room_events.Event attribute), 64 68, 69 source (nio.events.room_events.Event attribute), 68 session_id (nio.events.room_events.MegolmEvent at- source (nio.events.to_device.ToDeviceEvent attribute), tribute), 70 91 session_id (nio.events.to_device.ForwardedRoomKeyEventspeed_period (nio.TransferMonitor attribute), 56 attribute), 86 spent_time (nio.TransferMonitor attribute), 56 session_id (nio.events.to_device.RoomKeyEvent at- SqliteMemoryStore (class in nio.store), 120 tribute), 90 SqliteStore (class in nio.store), 120 session_id (nio.events.to_device.RoomKeyRequest start (nio.responses.RoomContextResponse attribute), attribute), 90 116 session_id (nio.responses.RoomKeyRequestResponse start_key_verification() (nio.AsyncClient attribute), 115 method), 50 set_avatar() (nio.AsyncClient method), 47 start_key_verification() (nio.HttpClient set_avatar() (nio.HttpClient method), 60 method), 61 set_displayname() (nio.AsyncClient method), 48 start_time (nio.responses.Response attribute), 107 set_displayname() (nio.HttpClient method), 60 start_time (nio.TransferMonitor attribute), 55 set_presence() (nio.Api static method), 21 start_verification() (nio.crypto.Sas method), set_presence() (nio.AsyncClient method), 48 124

164 Index nio Documentation, Release 0.18.6 state (nio.responses.RoomContextResponse attribute), to_json() (nio.Api static method), 23 117 ToDeviceError (class in nio.responses), 116 state_default (nio.events.room_events.DefaultLevels ToDeviceEvent (class in nio.events.to_device), 91 attribute), 67 ToDeviceMessage (class in state_key (nio.events.invite_events.InviteMemberEvent nio.event_builders.direct_messages), 100 attribute), 84 ToDeviceResponse (class in nio.responses), 116 state_key (nio.events.room_events.RoomMemberEvent topic (nio.event_builders.state_events.ChangeTopicBuilder attribute), 78 attribute), 102 state_key (nio.responses.RoomGetStateEventResponse topic (nio.events.room_events.RoomTopicEvent at- attribute), 109 tribute), 82 status_code (nio.responses.ErrorResponse at- transaction_id (nio.events.misc.BadEvent at- tribute), 106 tribute), 64 status_msg (nio.responses.PresenceGetResponse at- transaction_id (nio.events.misc.UnknownBadEvent tribute), 114 attribute), 65 StickerEvent (class in nio.events.room_events), 82 transaction_id (nio.events.room_events.Event at- store (nio.ClientConfig attribute), 24, 25 tribute), 68, 69 store_name (nio.ClientConfig attribute), 24 transaction_id (nio.events.room_events.MegolmEvent store_sync_tokens (nio.ClientConfig attribute), 25 attribute), 70 summary (nio.responses.RoomInfo attribute), 108 transaction_id (nio.events.to_device.KeyVerificationEvent sync() (nio.Api static method), 22 attribute), 87 sync() (nio.AsyncClient method), 50 transaction_id (nio.events.to_device.OlmEvent at- sync() (nio.HttpClient method), 61 tribute), 89 sync_forever() (nio.AsyncClient method), 51 TransferCancelledError, 103 synced (nio.AsyncClient attribute), 33 TransferMonitor (class in nio), 55 SyncError (class in nio.responses), 112 transferred (nio.TransferMonitor attribute), 56 SyncResponse (class in nio.responses), 112 transport_response (nio.responses.Response at- tribute), 107 T trust_state (nio.crypto.OlmDevice attribute), 122 TagEvent (class in nio.events.account_data), 99 TrustState (class in nio.crypto), 123 tags (nio.events.account_data.TagEvent attribute), 99 tweak (nio.events.account_data.PushSetTweak at- thumbnail() (nio.Api static method), 22 tribute), 98 thumbnail() (nio.AsyncClient method), 51 type (nio.event_builders.direct_messages.ToDeviceMessage thumbnail() (nio.HttpClient method), 61 attribute), 100 thumbnail_hashes (nio.events.room_events.RoomEncryptedMediatype (nio.events.account_data.UnknownAccountDataEvent attribute), 76 attribute), 99 thumbnail_iv (nio.events.room_events.RoomEncryptedMediatype (nio.events.misc.BadEvent attribute), 64 attribute), 76 type (nio.events.room_events.RedactedEvent attribute), thumbnail_key (nio.events.room_events.RoomEncryptedMedia 73 attribute), 76 type (nio.events.room_events.RoomMessageUnknown thumbnail_url (nio.events.room_events.RoomEncryptedMedia attribute), 81 attribute), 76 type (nio.events.room_events.UnknownEncryptedEvent ThumbnailError (class in nio.responses), 116 attribute), 82 ThumbnailResponse (class in nio.responses), 115 type (nio.events.room_events.UnknownEvent attribute), timed_out (nio.crypto.Sas attribute), 124 83 Timeline (class in nio.responses), 112 TypingNoticeEvent (class in nio.events.ephemeral), timeout (nio.responses.Response attribute), 107 93 timestamp (nio.events.ephemeral.Receipt attribute), 92 U to_canonical_json() (nio.Api static method), 23 unblacklist_device() (nio.Client method), 32 to_device() (nio.Api static method), 23 unblacklist_device() (nio.store.MatrixStore to_device() (nio.AsyncClient method), 52 method), 119 to_device() (nio.HttpClient method), 61 underride (nio.events.account_data.PushRuleset at- to_device_message (nio.responses.ToDeviceError tribute), 97 attribute), 116 unignore_device() (nio.Client method), 32

Index 165 nio Documentation, Release 0.18.6

unignore_device() (nio.store.MatrixStore user_name() (nio.rooms.MatrixRoom method), 62 method), 119 user_name_clashes() (nio.rooms.MatrixRoom UnknownAccountDataEvent (class in method), 63 nio.events.account_data), 99 users (nio.crypto.DeviceStore attribute), 121 UnknownBadEvent (class in nio.events.misc), 64 users (nio.events.ephemeral.TypingNoticeEvent at- UnknownEncryptedEvent (class in tribute), 93 nio.events.room_events), 82 users (nio.events.room_events.PowerLevels attribute), UnknownEvent (class in nio.events.room_events), 83 71 unread_notifications (nio.responses.RoomInfo users_default (nio.events.room_events.DefaultLevels attribute), 108 attribute), 67 unverify_device() (nio.Client method), 32 users_for_key_query (nio.Client attribute), 32 unverify_device() (nio.store.MatrixStore users_shared_with method), 119 (nio.responses.ShareGroupSessionResponse update() (nio.events.room_events.PowerLevels attribute), 111 method), 72 uuid (nio.responses.Response attribute), 107 update_device() (nio.Api static method), 23 update_device() (nio.AsyncClient method), 52 V update_device() (nio.HttpClient method), 61 valeu (nio.events.account_data.PushSetTweak at- update_receipt_marker() (nio.Api static tribute), 98 method), 23 value (nio.events.account_data.PushSetTweak at- update_receipt_marker() (nio.AsyncClient tribute), 98 method), 52 values() (nio.crypto.DeviceStore method), 121 update_summary() (nio.rooms.MatrixRoom VerificationError, 103 method), 62 verified (nio.crypto.OlmDevice attribute), 123 update_unread_notifications() verified (nio.crypto.Sas attribute), 124 (nio.rooms.MatrixRoom method), 62 verified (nio.events.misc.BadEvent attribute), 64 UpdateDeviceError (class in nio.responses), 112 verified (nio.events.misc.UnknownBadEvent at- UpdateDeviceResponse (class in nio.responses), tribute), 64 112 verified (nio.events.room_events.Event attribute), 68, UpdateReceiptMarkerError (class in 69 nio.responses), 117 verified_devices (nio.crypto.Sas attribute), 123 UpdateReceiptMarkerResponse (class in verify_device() (nio.Client method), 32 nio.responses), 117 verify_device() (nio.store.MatrixStore method), upload() (nio.Api static method), 23 120 upload() (nio.AsyncClient method), 53 version (nio.events.room_events.CallEvent attribute), upload_filter() (nio.Api static method), 24 66 upload_filter() (nio.AsyncClient method), 54 visibility (nio.event_builders.state_events.ChangeHistoryVisibilityBuilder upload_size (nio.responses.ContentRepositoryConfigResponse attribute), 101 attribute), 104 UploadError (class in nio.responses), 113 W UploadFilterError (class in nio.responses), 117 we_started_it (nio.crypto.Sas attribute), 123 UploadFilterResponse (class in nio.responses), whoami() (nio.Api static method), 24 117 whoami() (nio.AsyncClient method), 55 UploadResponse (class in nio.responses), 113 url (nio.events.room_events.RoomEncryptedMedia at- tribute), 75 url (nio.events.room_events.RoomMessageMedia attribute), 80 url (nio.events.room_events.StickerEvent attribute), 82 user_id (nio.Client attribute), 25 user_id (nio.crypto.OlmDevice attribute), 122 user_id (nio.events.ephemeral.Receipt attribute), 92 user_id (nio.responses.PresenceGetResponse at- tribute), 114

166 Index