nio API

This document details the API of nio.

Api

class nio.Api[source]

Matrix API class.

Static methods reflecting the Matrix REST API.

static delete_devices(access_token, devices, auth_dict=None)[source]

Delete a device.

This API endpoint uses the User-Interactive Authentication API.

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

Should first be called with no additional authentication information.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • devices (List[str]) – A list of devices which will be deleted.
  • auth_dict (Dict) – Additional authentication information for the user-interactive authentication API.
static devices(access_token)[source]

Get the list of devices for the current user.

Returns the HTTP method and HTTP path for the request.

Parameters:access_token (str) – The access token to be used with the request.
static encrypted_mxc_to_plumb(mxc, key, hash, iv, homeserver=None)[source]

Convert a matrix content URI to a encrypted mxc URI.

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

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

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.
static join(access_token, room_id)[source]

Join a room.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room identifier or alias to join.
static joined_members(access_token, room_id)[source]

Get the list of joined members for a room.

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 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 keys_claim(access_token, user_set)[source]

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • user_set (Dict[str, List[str]]) – The users and devices for which to claim one-time keys to be claimed. A map from user ID, to a list of device IDs.
static keys_query(access_token, user_set, token=None)[source]

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • user_set (Set[str]) – The users for which the keys should be downloaded.
  • token (Optional[str]) – If the client is fetching keys as a result of a device update received in a sync request, this should be the ‘since’ token of that sync request, or any later sync token.
static keys_upload(access_token, key_dict)[source]

Publish end-to-end encryption keys.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • key_dict (Dict) – The dictionary containing device and one-time keys that will be published to the server.
static login(user, password=None, device_name='', device_id='', token=None)[source]

Authenticate the user.

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

Parameters:
  • user (str) – The fully qualified user ID or just local part of the user ID, to log in.
  • 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()[source]

Get the homeserver’s supported login types

Returns the HTTP method and HTTP path for the request.

static logout(access_token)[source]

Logout the session.

Returns nothing.

Parameters:access_token (str) – the access token to be used with the request.
static mimetype_to_msgtype(mimetype)[source]

Turn a mimetype into a matrix message type.

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

Convert a matrix content URI to a HTTP URI.

static profile_get(access_token, user_id)[source]

Get the combined profile information for a user.

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 to get the profile for.
static profile_get_avatar(access_token, user_id)[source]

Get avatar URL.

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 to get avatar for.
static profile_get_displayname(access_token, user_id)[source]

Get display name.

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 to get display name for.
static profile_set_avatar(access_token, user_id, avatar_url)[source]

Set avatar url.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • user_id (str) – User id to set display name for.
  • avatar_url (str) – matrix content URI of the avatar to set.
static profile_set_displayname(access_token, user_id, display_name)[source]

Set display name.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • user_id (str) – User id to set display name for.
  • display_name (str) – Display name for user to set.
static room_context(access_token, room_id, event_id, limit=None)[source]

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room_id of the room that contains the event and its context.
  • event_id (str) – The event_id of the event that we wish to get the context for.
  • limit (int, optional) – The maximum number of events to request.
static room_forget(access_token, room_id)[source]

Forget a room.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room that will be forgotten.
static room_invite(access_token, room_id, user_id)[source]

Invite a user to a room.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room that the user will be invited to.
  • user_id (str) – The user_id of the user that should be invited.
static room_kick(access_token, room_id, user_id, reason=None)[source]

Kick a user from a room.

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.
static room_leave(access_token, room_id)[source]

Leave a room.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room that will be left.
static room_messages(access_token, room_id, start, end=None, direction=<MessageDirection.back: 0>, limit=10)[source]

Get room messages.

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – room id of the room for which to download the messages
  • start (str) – The token to start returning events from.
  • end (str) – The token to stop returning events at.
  • direction (MessageDirection) – The direction to return events from.
  • limit (int) – The maximum number of events to return.
static room_put_state(access_token, room_id, event_type, body)[source]

Send a state event.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room where the event will be sent to.
  • event_type (str) – The type of the event that will be sent.
  • body (Dict) – The body of the event. The fields in this object will vary depending on the type of event.
static room_read_markers(access_token, room_id, fully_read_event, read_event=None)[source]

Update read markers 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 of the room where the read markers should be updated
  • fully_read_event (str) – The event ID the read marker should be located at.
  • read_event (Optional[str]) – The event ID to set the read receipt location at.
static room_redact(access_token, room_id, event_id, tx_id, reason=None)[source]

Strip information out of an event.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room that contains the event that will be redacted.
  • event_id (str) – The ID of the event that will be redacted.
  • tx_id (str) – The transaction ID for this event.
  • reason (str) – A description explaining why the event was redacted.
static room_send(access_token, room_id, event_type, body, tx_id)[source]

Send a message event to a room.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – The room id of the room where the event will be sent to.
  • event_type (str) – The type of the message that will be sent.
  • body (Dict) – The body of the event. The fields in this object will vary depending on the type of event.
  • tx_id (str) – The transaction ID for this event.
static room_typing(access_token, room_id, user_id, typing_state=True, timeout=30000)[source]

Send a typing notice to the server.

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • room_id (str) – Room id of the room where the user is typing.
  • user_id (str) – The user who has started to type.
  • typign_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 sync(access_token, since=None, timeout=None, filter=None, full_state=None)[source]

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

Returns the HTTP method and HTTP path for the request.

Parameters:
  • access_token (str) – The access token to be used with the request.
  • since (str) – The room id of the room where the event will be sent to.
  • timeout (int) – The maximum time to wait, in milliseconds, before returning this request.
  • filter (Dict) – A dictionary containing a filter configuration for the request.
static thumbnail(access_token, server_name, media_id, width, height, method=<ResizingMethod.scale: 'scale'>, allow_remote=True)[source]

Get the thumbnail of a file from the content repository.

Returns the HTTP method and HTTP path for the request.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • server_name (str) – The server name from the mxc:// URI.
  • media_id (str) – The media ID from the mxc:// URI.
  • width (int) – The desired width of the thumbnail.
  • height (int) – The desired height of the thumbnail.
  • method (ResizingMethod) – The desired resizing method.
  • allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
static to_canonical_json(content_dict)[source]

Turn a dictionary into a canonical json string.

static to_device(access_token, event_type, content, tx_id)[source]

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • event_type (str) – The type of the event which will be sent.
  • content (Dict) – The messages to send. A map from user ID, to a map from device ID to message body. The device ID may also be *, meaning all known devices for the user.
  • tx_id (str) – The transaction ID for this event.
static to_json(content_dict)[source]

Turn a dictionary into a json string.

static update_device(access_token, device_id, content)[source]

Update the metadata of the given device.

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • device_id (str) – The device for which the metadata will be updated.
  • content (Dict) – A dictionary of metadata values that will be updated for the device.
static upload(access_token, filename=None)[source]

Upload a file’s content to the content repository.

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

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

Parameters:
  • access_token (str) – The access token to be used with the request.
  • filename (str) – The name of the file being uploaded
static whoami(access_token)[source]

Get information about the owner of a given access token.

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

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

nio Clients

class nio.ClientConfig(store: Callable = <class 'nio.store.database.DefaultStore'>, encryption_enabled: bool = True, store_name: str = '', pickle_key: str = 'DEFAULT_KEY', store_sync_tokens: bool = False)[source]

nio client configuration.

store

The store that should be used for state storage.

Type:MatrixStore, optional
store_name

Filename that should be used for the store.

Type:str, optional
encryption_enabled

Should end to end encryption be used.

Type:bool, optional
pickle_key

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

Type:str, optional
store_sync_tokens

Should the client store and restore sync tokens.

Type:bool, optional

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

Client

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

Matrix no-IO client.

access_token

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

Type:str
user_id

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

Type:str
next_batch

The current sync token.

Type:str
rooms

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

Type:Dict[str, MatrixRoom)
Parameters:
  • user (str) – User that will be used to log in.
  • device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.
  • store_dir (str, optional) – The directory that should be used for state storeage.
  • config (ClientConfig, optional) – Configuration for the client.
add_ephemeral_callback(callback, filter)[source]

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

Parameters:
  • callback (Callable[MatrixRoom, Event]) – A function that will be called if the event type in the filter argument is found in the ephemeral room event list.
  • filter (Type, Tuple[Type]) – The event type or a tuple containing multiple types for which the function will be called.
add_ephermeral_callback(callback, filter)[source]

Deprecated: typo in function name.

add_event_callback(callback, filter)[source]

Add a callback that will be executed on room events.

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

Parameters:
  • callback (Callable[Union[MatrixRoom, MatrixInvitedRoom, Event]) – A function that will be called if the event type in the filter argument is found in a room timeline.
  • filter (Type, Tuple[Type]) – The event type or a tuple containing multiple types for which the function will be called.
add_to_device_callback(callback, filter)[source]

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

Parameters:
  • callback (Callable[Event]) – 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 (Type, Tuple[Type]) – The event type or a tuple containing multiple types for which the function will be called.
blacklist_device(device)[source]

Mark a device as blacklisted.

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

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

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

cancel_key_share(event)[source]

Cancel a previously interrupted key share event.

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

>>> client.cancel_key_share(room_key_request)
Parameters:event (RoomKeyRequest) – The event which we would like to cancel.
Returns:True if the request was cancelled, False otherwise.
Return type:bool
confirm_key_verification(transaction_id)[source]

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

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

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

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

continue_key_share(event)[source]

Continue a previously interrupted key share event.

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

>>> client.add_to_device_callback(callback, RoomKeyRequest)

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

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

>>> client.continue_key_share(room_key_request)
Parameters:event (RoomKeyRequest) – The event which we would like to continue.

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

Returns:True if the request was continued, False otherwise.
Return type:bool
create_key_verification(device)[source]

Start a new key verification process with the given device.

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

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

decrypt_event(event)[source]

Try to decrypt an undecrypted megolm event.

Parameters:event (MegolmEvent) – Event that should be decrypted.

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

device_store

Store containing known devices.

Returns a DeviceStore holding all known olm devices.

encrypt(room_id, message_type, content)[source]

Encrypt a message to be sent to the provided room.

Parameters:
  • room_id (str) – The room id of the room where the message will be sent.
  • message_type (str) – The type of the message.
  • content (str) – The dictionary containing the content of the message.

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

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

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

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

Export all the Megolm decryption keys of this device.

The keys will be encrypted using the passphrase.

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

Parameters:
  • outfile (str) – The file to write the keys to.
  • passphrase (str) – The encryption passphrase.
  • count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.
get_active_key_requests(user_id, device_id)[source]

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

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

Example

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

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

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

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

get_missing_sessions(room_id)[source]

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

Parameters:room_id (str) – The room id of the room for which we should get the users with missing Olm sessions.
Raises LocalProtocolError if the room with the provided room id is
not found or the room is not encrypted.
get_users_for_key_claiming()[source]

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

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

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

ignore_device(device)[source]

Mark a device as ignored.

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

Parameters:device (OlmDevice) – the device to ignore

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

import_keys(infile, passphrase)[source]

Import Megolm decryption keys.

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

Parameters:
  • infile (str) – The file containing the keys.
  • passphrase (str) – The decryption passphrase.
Raises EncryptionError if the file is invalid or couldn’t be
decrypted.

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

invalidate_outbound_session(room_id)[source]

Explicitely remove encryption keys for a room.

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

Key verifications that the client is participating in.

load_store()[source]

Load the session store and olm account.

Raises LocalProtocolError if the session_path, user_id and devic_id are
not set.
logged_in

Check if we are logged in.

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

olm_account_shared

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

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

outgoing_key_requests

Our active key requests that we made.

outgoing_to_device_messages

To-device messages that we need to send out.

receive_response(response)[source]

Receive a Matrix Response and change the client state accordingly.

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

Parameters:response (Response) – the response that we wish the client to handle
room_contains_unverified(room_id)[source]

Check if a room contains unverified devices.

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

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

room_devices(room_id)[source]

Get all Olm devices participating in a room.

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

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

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

should_claim_keys

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

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

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

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

should_query_keys

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

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

should_upload_keys

Check if the client should upload encryption keys.

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

unblacklist_device(device)[source]

Unmark a device as blacklisted.

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

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

unignore_device(device)[source]

Unmark a device as ignored.

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

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

unverify_device(device)[source]

Unmark a device as verified.

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

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

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

users_for_key_query

Users for whom we should make a key query.

verify_device(device)[source]

Mark a device as verified.

A device needs to be either trusted 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, user='', device_id='', store_path='', config=None, ssl=None, proxy=None)[source]

Bases: nio.client.base_client.Client

An async IO matrix client.

Parameters:
  • homeserver (str) – The URL of the homeserver which we want to connect to.
  • user (str, optional) – The user which will be used when we log in to the homeserver.
  • device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.
  • store_path (str, optional) – The directory that should be used for state storage.
  • config (AsyncClientConfig, optional) – Configuration for the client.
  • ssl (bool/ssl.SSLContext, optional) – SSL validation mode. None for default SSL check (ssl.create_default_context() is used), False for skip SSL certificate validation connection.
  • proxy (str, optional) – The proxy that should be used for the HTTP connection.
synced

An asyncio event that is fired every time the client successfully syncs with the server.

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, tx_id=None)[source]

Accept a key verification start event.

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

Parameters:transaction_id (str) – An transaction id of a valid key verification process.
add_response_callback(func, cb_filter=None)[source]

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

Parameters:
  • func (Coroutine) – The coroutine that will be called with the response as the argument.
  • cb_filter (Type, optional) – A type or a tuple of types for which the callback should be called.

Example

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

Cancel a interactive key verification with the given device.

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

Parameters:
  • transaction_id (str) – An transaction id of a valid key verification process.
  • reject (bool) – Is the cancelation reason because we’re rejecting the short auth string and mark it as mismatching or a normal user cancelation.

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

close()[source]

Close the underlying http session.

confirm_short_auth_string(transaction_id, tx_id=None)[source]

Confirm a short auth string and mark it as matching.

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

Parameters:transaction_id (str) – An transaction id of a valid key verification process.
create_matrix_response(response_class, transport_response, data=None)[source]

Transform a transport response into a nio matrix response.

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.

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

Export all the Megolm decryption keys of this device.

The keys will be encrypted using the passphrase.

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

Parameters:
  • outfile (str) – The file to write the keys to.
  • passphrase (str) – The encryption passphrase.
  • count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.
get_avatar(user_id=None)[source]

Get a user’s avatar URL.

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

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

Get a user’s display name.

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

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

Parameters:user_id (str) – User id of the user to get the display name for.
get_profile(user_id=None)[source]

Get a user’s combined profile information.

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

Returns 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)[source]
import_keys(infile, passphrase)[source]

Import Megolm decryption keys.

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

Parameters:
  • infile (str) – The file containing the keys.
  • passphrase (str) – The decryption passphrase.
Raises EncryptionError if the file is invalid or couldn’t be
decrypted.

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

join(room_id)[source]

Join a room.

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

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

Send a message to a room.

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

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

keys_claim(user_set)[source]

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

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

Query the server for user keys.

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

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

Upload the E2E encryption keys.

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

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, device_name='')[source]

Login to the homeserver.

Parameters:
  • password (str) – 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.

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

logout()[source]

Logout from the homeserver.

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

parse_body(transport_response)[source]

Parse the body of the response.

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

Returns a dictionary representing the response.

receive_response(response)[source]

Receive a Matrix Response and change the client state accordingly.

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

Parameters:response (Response) – the response that we wish the client to handle
request_room_key(event, tx_id=None)[source]

Request a missing room key.

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

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

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.

room_context(room_id, event_id, limit=None)[source]

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

This allows clients to get the context surrounding an event.

Returns 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_forget(room_id)[source]

Forget a room.

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

Returns 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_leave(room_id)[source]

Leave a room or reject an invite.

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

Returns 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, start, end=None, direction=<MessageDirection.back: 0>, limit=10)[source]

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

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

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.

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

Example

>>> response = await client.room_messages(room_id, previous_batch)
>>> next_response = await client.room_messages(room_id,
...                                            response.end)
room_send(room_id, message_type, content, tx_id=None, ignore_unverified_devices=False)[source]

Send a message to a room.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.
  • message_type (str) – A string identifying the type of the message.
  • content (Dict[Any, Any]) – A dictionary containing the content of the message.
  • tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.
  • ignore_unverified_devices (bool) – If the room is encrypted and contains unverified devices, the devices can be marked as ignored here. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

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

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

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

Raises LocalProtocolError if the client isn’t logged in.

room_typing(room_id, typing_state=True, timeout=30000)[source]

Send a typing notice to the server.

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

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

Parameters:
  • room_id (str) – The room id of the room where the user is typing.
  • typign_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.
run_response_callbacks(responses)[source]

Run the configured response callbacks for the given responses.

send(method, path, data=None, headers=None)[source]

Send a request to the homeserver.

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

Send out outgoing to-device messages.

set_avatar(avatar_url)[source]

Set the user’s avatar URL.

This tells the server to set the avatar of the currently logged in user to supplied matrix content URI.

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

Set user’s display name.

This tells the server to set display name of the currently logged in user to the supplied string.

Returns either a ProfileSetDisplayNameResponse if the request was successful or a ProfileSetDisplayNameError if there was an error with the request.

Parameters:displayname (str) – Display name to set.
share_group_session(room_id, tx_id=None, ignore_unverified_devices=False)[source]

Share a group session with a room.

This method sends a group session to members of a room.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.
  • tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.
  • ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists, the room isn’t an encrypted room or a key sharing request is already in flight for this room.

start_key_verification(device, tx_id=None)[source]

Start a interactive key verification with the given device.

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

Parameters:device (OlmDevice) – An device with which we would like to start the interactive key verification process.
sync(timeout=None, sync_filter=None, since=None, full_state=None)[source]

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

Parameters:
  • timeout (int, optional) – The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds.
  • sync_filter (Dict[Any, Any], optional) – A filter that should be used for this sync request.
  • full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter.
  • since (str, optional) – A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call.

Returns either a SyncResponse if the request was successful or a SyncError if there was an error with the request.

sync_forever(timeout=None, sync_filter=None, since=None, full_state=None, loop_sleep_time=None)[source]

Continuously sync with the configured homeserver.

This method calls the sync method in a loop. To react to events event callbacks should be configured.

The loop also makes sure to handle other required requests between syncs. 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.
  • sync_filter (Dict[Any, Any], optional) – A filter 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. 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.
thumbnail(server_name, media_id, width, height, method=<ResizingMethod.scale: 'scale'>, allow_remote=True)[source]

Get the thumbnail of a file from the content repository.

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

Returns 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, tx_id=None)[source]

Send a to-device message.

Parameters:
  • message (ToDeviceMessage) – The message that should be sent out.
  • tx_id (str, optional) – The transaction ID for this message. Should be unique.

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

upload(data, content_type, filename=None)[source]

Upload a file’s content to the content repository.

Returns either a UploadResponse if the request was successful or a UploadError if there was an error with the request.

Parameters:
  • data (bytes/BinaryIO/AsyncIterable[bytes]) – The file’s binary content. Using a binary file-like object or async iterable allows sending large files without reading them into memory.
  • content_type (str) – The content MIME type of the file, e.g. “image/png”
  • filename (str, optional) – The file’s original name.

Example

>>> with open("vid.webm", "rb") as f:
>>>     response = await client.upload(f, "video/webm", "vid.webm")
>>>     http_url = nio.Api.mxc_to_http(response.content_uri)

HttpClient

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

Bases: nio.client.base_client.Client

accept_key_verification(transaction_id, tx_id=None)[source]

Accept a key verification start event.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:transaction_id (str) – An transaction id of a valid key verification process.
cancel_key_verification(transaction_id, tx_id=None)[source]

Abort an interactive key verification.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:transaction_id (str) – An transaction id of a valid key verification process.
confirm_short_auth_string(transaction_id, tx_id=None)[source]

Confirm a short auth string and mark it as matching.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:transaction_id (str) – An transaction id of a valid key verification process.
connect(transport_type=<TransportType.HTTP: 0>)[source]
data_to_send()[source]
delete_devices(devices, auth=None)[source]
devices()[source]
disconnect()[source]
get_avatar(user_id=None)[source]

Get a user’s avatar URL.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:user_id (str) – User id of the user to get the avatar for.
get_displayname(user_id=None)[source]

Get a user’s display name.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:user_id (str) – User id of the user to get the display name for.
get_profile(user_id=None)[source]

Get a user’s combined profile information.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:user_id (str) – User id of the user to get the profile for.
handle_key_upload_error(response)[source]
join(room_id)[source]

Join a room.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:room_id – The room id or alias of the room to join.
joined_members(room_id)[source]
keys_claim(room_id)[source]
keys_query()[source]

Query the server for user keys.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

keys_upload()[source]
lag
login(password=None, device_name='', token=None)[source]
login_info()[source]

Get the available login methods from the server

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

logout()[source]
next_response(max_events=0)[source]
parse_body(transport_response)[source]

Parse the body of the response.

Parameters:transport_response (TransportResponse) – The transport response that contains the body of the response.

Returns a dictionary representing the response.

receive(data)[source]

Pass received data to the client

request_room_key(event, tx_id=None)[source]

Request a missing room key.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:event (str) – An undecrypted MegolmEvent for which we would like to request the decryption key.
room_forget(room_id)[source]

Forget a room.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:room_id (str) – The room id of the room to forget.
room_invite(room_id, user_id)[source]
room_kick(room_id, user_id, reason=None)[source]
room_leave(room_id)[source]

Leave a room or reject an invite.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:room_id – The room id of the room to leave.
room_messages(room_id, start, end=None, direction=<MessageDirection.back: 0>, limit=10)[source]
room_put_state(room_id, event_type, body)[source]
room_read_markers(room_id, fully_read_event, read_event=None)[source]

Update read markers for a room.

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

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 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.
room_redact(room_id, event_id, reason=None, tx_id=None)[source]
room_send(room_id, message_type, content, tx_id=None)[source]
room_typing(room_id, typing_state=True, timeout=30000)[source]

Send a typing notice to the server.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • room_id (str) – Room id of the room where the user is typing.
  • typign_state (bool) – A flag representing whether the user started or stopped typing
  • timeout (int) – For how long should the new typing notice be valid for in milliseconds.
set_avatar(avatar_url)[source]

Set the user’s avatar URL.

This tells the server to set avatar of the currently logged in user to supplied matrix content URI.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:avatar_url (str) – matrix content URI of the avatar to set.
set_displayname(displayname)[source]

Set the user’s display name.

This tells the server to set the display name of the currently logged in user to supplied string.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:displayname (str) – Display name to set.
share_group_session(room_id, ignore_missing_sessions=False, tx_id=None, ignore_unverified_devices=False)[source]

Share a group session with a room.

This method sends a group session to members of a room.

Parameters:
  • room_id (str) – The room id of the room where the message should be sent to.
  • tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.
  • ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.

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

start_key_verification(device, tx_id=None)[source]

Start a interactive key verification with the given device.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:device (OlmDevice) – An device with which we would like to start the interactive key verification process.
sync(timeout=None, filter=None, full_state=False)[source]
thumbnail(server_name, media_id, width, height, method=<ResizingMethod.scale: 'scale'>, allow_remote=True)[source]

Get the thumbnail of a file from the content repository.

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

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • server_name (str) – The server name from the mxc:// URI.
  • media_id (str) – The media ID from the mxc:// URI.
  • width (int) – The desired width of the thumbnail.
  • height (int) – The desired height of the thumbnail.
  • method (ResizingMethod) – The desired resizing method.
  • allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
to_device(message, tx_id=None)[source]

Send a message to a specific device.

Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.

Parameters:
  • message (ToDeviceMessage) – The message that should be sent out.
  • tx_id (str, optional) – The transaction ID for this message. Should be unique.
update_device(device_id, content)[source]

Rooms

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

Bases: object

Represents a Matrix room.

add_member(user_id, display_name, avatar_url)[source]
avatar_url(user_id)[source]

Get avatar url for a user.

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

display_name

Calculate display name for a room.

Prefer returning the room name if it exists, falling back to a group-style name if not.

Follows: https://matrix.org/docs/spec/client_server/r0.3.0.html#id268

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

Return the group-style name of the room.

In other words, a display name based on the names of room members. This is used for ad-hoc groups of people (usually direct chats).

handle_ephemeral_event(event)[source]
handle_event(event)[source]
handle_membership(event)[source]

Handle a membership event for the room.

Parameters:event (RoomMemberEvent) – The event that should be handled that updates the room state.

Returns True if the member list of the room has changed False otherwise.

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

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

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
members_synced

Check if the room member state is fully synced.

Room members can be missing from the room if syncs are done using lazy member loading, the room summary will contain the full member count but other member info will be missing.

A joined_members request should be done for this room to populate the member list. This is crucial for encrypted rooms before sending any messages.

named_room_name()[source]

Return the name of the room, if it’s a named room.

Otherwise, return None.

remove_member(user_id)[source]
update_summary(summary)[source]
user_name(user_id)[source]

Get disambiguated display name for a user.

Returns display name of a user if display name is unique or returns a display name in form “<display name> (<matrix id>)” if there is more than one user with same display name.

user_name_clashes(name)[source]

Get a list of users that have same display name.

class nio.rooms.MatrixInvitedRoom(room_id, own_user_id)[source]

Bases: nio.rooms.MatrixRoom

handle_event(event)[source]
handle_membership(event)[source]

Handle a membership event for the invited room.

Parameters:event (RoomMemberEvent) – The event that should be handled that updates the room state.

Returns True if the member list of the room has changed False otherwise.

class nio.rooms.MatrixUser(user_id, display_name=None, avatar_url=None, power_level=0)[source]

Bases: object

disambiguated_name
name

Events

Nio Events Module.

The model of conversation history exposed by a Matrix server can be considered as a list of events. The server ‘linearises’ the eventually-consistent event graph of events into an ‘event stream’ at any given point in time:

Nio contains clases for most known Matrix Event types.

class nio.events.misc.BadEvent(source, event_id, sender, server_timestamp, type)[source]

Bases: object

An event that failed event schema and type validation.

This type of event will be created if the event has a valid core structure but failed validation for the given event type.

The event can still be inspected with the source attribute.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:dict
event_id

A globally unique event identifier.

Type:str
sender

The fully-qualified ID of the user who sent this event.

Type:str
server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:int
type

The claimed type of the event.

Type:str
decrypted

A flag signaling if the event was decrypted.

Type:bool
verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:bool
sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:str, optional
session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:str, optional
transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:str, optional
class nio.events.misc.UnknownBadEvent(source)[source]

Bases: object

An event that doesn’t have the minimal necessary structure.

This type of event will be created if we can’t find the event_id, sender, origin server timestamp or event type.

The event can still be inspected with the source attribute.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:dict
decrypted

A flag signaling if the event was decrypted.

Type:bool
verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:bool
sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:str, optional
session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:str, optional
transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:str, optional

Room Events

class nio.events.room_events.CallAnswerEvent(source, call_id, version, answer)[source]

Bases: nio.events.room_events.CallEvent

Event representing the answer to a VoIP call.

This event is sent by the callee when they wish to answer the call.

answer

The session description object. A dictionary containing the keys “type” which must be “answer” for this event and “sdp” which contains the SDP text of the session description.

Type:dict
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.CallCandidatesEvent(source, call_id, version, candidates)[source]

Bases: nio.events.room_events.CallEvent

Call event holding additional VoIP ICE candidates.

This event is sent by callers after sending an invite and by the callee after answering. Its purpose is to give the other party additional ICE candidates to try using to communicate.

Parameters:candidates (list) – A list of dictionaries describing the candidates.
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.CallEvent(source, call_id, version)[source]

Bases: nio.events.room_events.Event

Base Class for Matrix call signalling events.

call_id

The unique identifier of the call.

Type:str
version

The version of the VoIP specification this message adheres to.

Type:int
static parse_event(event_dict)[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level CallEvent object representing the parsed event.

The event structure is checked for correctness and the event fields are type checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:event_dict (dict) – The raw matrix event dictionary.
class nio.events.room_events.CallHangupEvent(source, call_id, version)[source]

Bases: nio.events.room_events.CallEvent

An event representing the end of a VoIP call.

Sent by either party to signal their termination of the call. This can be sent either once the call has has been established or before to abort the call.

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.CallInviteEvent(source, call_id, version, lifetime, offer)[source]

Bases: nio.events.room_events.CallEvent

Event representing an invitation to a VoIP call.

This event is sent by a caller when they wish to establish a call.

lifetime

The time in milliseconds that the invite is valid for.

Type:integer
offer

The session description object. A dictionary containing the keys “type” which must be “offer” for this event and “sdp” which contains the SDP text of the session description.

Type:dict
expired

Property marking if the invite event expired.

classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.DefaultLevels(ban: int = 50, invite: int = 50, kick: int = 50, redact: int = 50, state_default: int = 0, events_default: int = 0, users_default: int = 0)[source]

Bases: object

Class holding information about default power levels of a room.

ban

The level required to ban a user.

Type:int
invite

The level required to invite a user.

Type:int
kick

The level required to kick a user.

Type:int
redact

The level required to redact events.

Type:int
state_default

The level required to send state events. This can be overridden by the events power level mapping.

Type:int
events_default

The level required to send message events. This can be overridden by the events power level mapping.

Type:int
users_default

The default power level for every user in the room. This can be overridden by the users power level mapping.

Type:int
classmethod from_dict(parsed_dict)[source]

Create a DefaultLevels object from a dictionary.

This creates the DefaultLevels object from a dictionary containing a m.room.power_levels event. The event structure isn’t checked in this method.

This shouldn’t be used directly, the PowerLevelsEvent method will call this method to construct the DefaultLevels object.

class nio.events.room_events.Event(source)[source]

Bases: object

Matrix Event class.

This is the base event class, most events inherit from this class.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:dict
event_id

A globally unique event identifier.

Type:str
sender

The fully-qualified ID of the user who sent this event.

Type:str
server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:int
decrypted

A flag signaling if the event was decrypted.

Type:bool
verified

A flag signaling if the event is verified, is True if the event was sent from a verified device.

Type:bool
sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:str, optional
session_id

The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.

Type:str, optional
transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:str, optional
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
classmethod parse_decrypted_event(event_dict)[source]

Parse a decrypted event and create a higher level event object.

Parameters:event_dict (dict) – The dictionary representation of the event.
classmethod parse_encrypted_event(event_dict)[source]

Parse an encrypted event.

Encrypted events may have different fields depending on the algorithm that was used to encrypt them.

This function checks the algorithm of the event and produces a higher level event from the provided dictionary.

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

Returns None if the algorithm of the event is unknown.

classmethod parse_event(event_dict)[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:event_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.MegolmEvent(source, device_id, ciphertext, algorithm, room_id='')[source]

Bases: nio.events.room_events.Event

An undecrypted Megolm event.

MegolmEvents are presented to library users only if the library fails to decrypt the event because of a missing session key.

MegolmEvents can be stored for later use. If a RoomKeyEvent is later on received with a session id that matches the session_id of this event decryption can be retried.

event_id

A globally unique event identifier.

Type:str
sender

The fully-qualified ID of the user who sent this event.

Type:str
server_timestamp

Timestamp in milliseconds on originating homeserver when this event was sent.

Type:int
sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:str
device_id

The unique identifier of the device that was used to encrypt the event.

Type:str
session_id

The unique identifier of the session that was used to encrypt the message.

Type:str
ciphertext

The undecrypted ciphertext of the event.

Type:str
algorithm

The encryption algorithm that was used to encrypt the message.

Type:str
room_id

The unique identifier of the room in which the message was sent.

Type:str
transaction_id

The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.

Type:str, optional
as_key_request(user_id, requesting_device_id, request_id=None)[source]

Make a to-device message for a room key request.

MegolmEvents are presented to library users only if the library fails to decrypt the event because of a missing session key.

A missing key can be requested later on by sending a key request, this method creates a ToDeviceMessage that can be sent out if such a request should be made.

Parameters:user_id (str) – The user id of the user that should receive the key request.
classmethod from_dict(event_dict)[source]

Create a MegolmEvent from a dictionary.

Parameters:event_dict (Dict) – Dictionary containing the event.

Returns a MegolmEvent if the event_dict contains a valid event or a BadEvent if it’s invalid.

class nio.events.room_events.PowerLevels(defaults=NOTHING, users: Dict[str, int] = NOTHING, events: Dict[str, int] = NOTHING)[source]

Bases: object

Class holding information of room power levels.

defaults

The default power levels of the room.

Type:DefaultLevels
users

The power levels for specific users. This is a mapping from user_id to power level for that user.

Type:dict
events

The level required to send specific event types. This is a mapping from event type to power level required.

Type:dict
get_user_level(user_id)[source]

Get the power level of a user.

Parameters:user_id (str) – The fully-qualified ID of the user for whom we would like to get the power level.

Returns the integer representing the user power level.

update(new_levels)[source]

Update the power levels object with new levels.

Parameters:new_levels (PowerLevels) – A new PowerLevels object that we received from a newer PowerLevelsEvent.
class nio.events.room_events.PowerLevelsEvent(source, power_levels)[source]

Bases: nio.events.room_events.Event

Class representing a m.room.power_levels event.

This event specifies the minimum level a user must have in order to perform a certain action. It also specifies the levels of each user in the room.

power_levels

The PowerLevels object holding information of the power levels of the room.

Type:PowerLevels
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RedactedEvent(source, type: str, redacter: str, reason: Optional[str])[source]

Bases: nio.events.room_events.Event

An event that has been redacted.

type

The type of the event that has been redacted.

Type:str
redacter

The fully-qualified ID of the user who redacted the event.

Type:str
reason

A string describing why the event was redacted, can be None.

Type:str, optional
event_type

Type of the event.

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RedactionEvent(source, redacts, reason=None)[source]

Bases: nio.events.room_events.Event

An event signaling that another event has been redacted.

Events can be redacted by either room or server administrators. Redacting an event means that all keys not required by the protocol are stripped off.

redacts

The event id of the event that has been redacted.

Type:str
reason

A string describing why the event was redacted, can be None.

Type:str, optional
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

An event informing us about which alias should be preferred.

canonical_alias

The alias that is considered canonical.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomAvatarEvent(source, avatar_url)[source]

Bases: nio.events.room_events.Event

Event holding a picture that is associated with the room.

avatar_url

The URL to the picture.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomCreateEvent(source, creator: str, federate: bool = True, room_version: str = '1')[source]

Bases: nio.events.room_events.Event

The first event in a room, signaling that the room was created.

creator

The fully-qualified ID of the user who created the room.

Type:str
federate

A boolean flag telling us whether users on other homeservers are able to join this room.

Type:bool
room_version

The version of the room. Different room versions

Type:str
will have different event formats. Clients shouldn't worry about this
too much unless they want to perform room upgrades.
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomEncryptedAudio(source, url, body, key, hashes, iv)[source]

Bases: nio.events.room_events.RoomEncryptedMedia

A room message containing an audio clip where the file is encrypted.

class nio.events.room_events.RoomEncryptedFile(source, url, body, key, hashes, iv)[source]

Bases: nio.events.room_events.RoomEncryptedMedia

A room message containing a generic encrypted file.

class nio.events.room_events.RoomEncryptedImage(source, url, body, key, hashes, iv)[source]

Bases: nio.events.room_events.RoomEncryptedMedia

A room message containing an image where the file is encrypted.

class nio.events.room_events.RoomEncryptedMedia(source, url, body, key, hashes, iv)[source]

Bases: nio.events.room_events.RoomMessage

Base class for encrypted room messages containing an URI.

url

The URL of the file.

Type:str
body

The description of the message.

Type:str
key

The key that can be used to decrypt the file.

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

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomEncryptedVideo(source, url, body, key, hashes, iv)[source]

Bases: nio.events.room_events.RoomEncryptedMedia

A room message containing a video clip where the file is encrypted.

class nio.events.room_events.RoomEncryptionEvent(source)[source]

Bases: nio.events.room_events.Event

An event signaling that encryption has been enabled in a room.

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

Event signaling whether guest users are allowed to join rooms.

guest_access

A string describing the guest access policy of the room. Can be one of “can_join” or “forbidden”.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

An event telling whether users can read the room history.

Room history visibility can be set up in multiple ways in Matrix:

  • world_readable
    All events value may be shared by any participating homeserver with anyone, regardless of whether they have ever joined the room.
  • shared
    Previous events are always accessible to newly joined members. All events in the room are accessible, even those sent when the member was not a part of the room.
  • invited
    Events are accessible to newly joined members from the point they were invited onwards. Events stop being accessible when the member’s state changes to something other than invite or join.
  • joined
    Events are only accessible to members from the point on they joined to the room and stop being accessible when they aren’t joined anymore.
history_visibility

A string describing who can read the room history. One of “invited”, “joined”, “shared”, “world_readable”.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

An event telling us how users can join the room.

join_rule

A string telling us how users may join the room, can be one of “public” meaning anyone can join the room without any restrictions or “invite” meaning users can only join if they have been previously invited.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

Class representing to an m.room.member event.

state_key

The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.

Type:str
membership

The membership state of the user. One of “invite”, “join”, “leave”, “ban”.

Type:str
prev_membership

The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.

Type:str, optional
content

The content of the of the membership event.

Type:dict
prev_content

The content of a previous membership event that this one is overwriting.

Type:dict, optional
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomMessage(source)[source]

Bases: nio.events.room_events.Event

Abstract room message class.

This class corespondents to a Matrix event of the m.room.message type. It is used when messages are sent to the room.

The class has one child class per msgtype.

classmethod parse_decrypted_event(parsed_dict)[source]

Parse a decrypted event and create a higher level event object.

Parameters:event_dict (dict) – The dictionary representation of the event.
classmethod parse_event(parsed_dict)[source]

Parse a Matrix event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.

If the type of the event is now known an UnknownEvent will be produced.

Parameters:event_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomMessageAudio(source, url, body)[source]

Bases: nio.events.room_events.RoomMessageMedia

A room message containing an audio clip.

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

Bases: nio.events.room_events.RoomMessageFormatted

A room message coresponding to the m.emote msgtype.

This message is similar to m.text except that the sender is ‘performing’ the action contained in the body key, similar to /me in IRC.

body

The textual body of the message.

Type:str
formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:str, optional
format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:str, optional
class nio.events.room_events.RoomMessageFile(source, url, body)[source]

Bases: nio.events.room_events.RoomMessageMedia

A room message containing a generic file.

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

Bases: nio.events.room_events.RoomMessage

Base abstract class for room messages that can have formatted bodies.

body

The textual body of the message.

Type:str
formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:str, optional
format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:str, optional
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.RoomMessageMedia

A room message containing an image.

class nio.events.room_events.RoomMessageMedia(source, url, body)[source]

Bases: nio.events.room_events.RoomMessage

Base class for room messages containing a URI.

url

The URL of the file.

Type:str
body

The description of the message.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.RoomMessage

A room message corresponding to the m.notice msgtype.

Room notices are primarily intended for responses from automated clients.

body

The text of the notice.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.RoomMessageText(source, body: str, formatted_body: Optional[str], format: Optional[str])[source]

Bases: nio.events.room_events.RoomMessageFormatted

A room message corresponding to the m.text msgtype.

This message is the most basic message and is used to represent text.

body

The textual body of the message.

Type:str
formatted_body

The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.

Type:str, optional
format

The format used in the formatted_body. This specifies how the formatted_body should be interpreted.

Type:str, optional
class nio.events.room_events.RoomMessageUnknown(source, msgtype: str, content)[source]

Bases: nio.events.room_events.RoomMessage

A m.room.message which we do not understand.

This event is created every time nio tries to parse a room message of an unknown msgtype. Since custom and extensible events are a feature of Matrix this allows clients to use custom messages but care should be taken that the clients will be responsible to validate and type check the content of the message.

msgtype

The msgtype of the room message.

Type:str
content

The dictionary holding the content of the room message. The keys and values of this dictionary will differ depending on the msgtype.

Type:dict
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Get the msgtype of the room message.

class nio.events.room_events.RoomMessageVideo(source, url, body)[source]

Bases: nio.events.room_events.RoomMessageMedia

A room message containing a video clip.

class nio.events.room_events.RoomNameEvent(source, name)[source]

Bases: nio.events.room_events.Event

Event holding the name of the room.

The room name is a human-friendly string designed to be displayed to the end-user. The room name is not unique, as multiple rooms can have the same room name set.

name

The name of the room.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

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

Bases: nio.events.room_events.Event

Event holding the topic of a room.

A topic is a short message detailing what is currently being discussed in the room. It can also be used as a way to display extra information about the room, which may not be suitable for the room name.

topic

The topic of the room.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.UnknownEncryptedEvent(source, type, algorithm)[source]

Bases: nio.events.room_events.Event

An encrypted event which we don’t know how to decrypt.

This event is created every time nio tries to parse an event encrypted event that was encrypted using an unknown algorithm.

type

The type of the event.

Type:str
algorithm

The algorithm of the event.

Type:str
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.room_events.UnknownEvent(source, type)[source]

Bases: nio.events.room_events.Event

An Event which we do not understand.

This event is created every time nio tries to parse an event of an unknown type. Since custom and extensible events are a feature of Matrix this allows clients to use custom events but care should be taken that the clients will be responsible to validate and type check the event.

type

The type of the event.

Type:str
classmethod from_dict(event_dict)[source]

Create an Event from a dictionary.

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

Invite Room Events

Matrix Invite Events.

Events for invited rooms will have a stripped down version of their counterparts for joined rooms.

Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.

These events help set up the state of an invited room so more information can be displayed to users if they are invited to a room.

class nio.events.invite_events.InviteAliasEvent(source: Dict[KT, VT], sender: str, canonical_alias)[source]

Bases: nio.events.invite_events.InviteEvent

An event informing us about which alias should be preferred.

This is the RoomAliasEvent equivalent for invited rooms.

canonical_alias

The alias that is considered canonical.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

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

Bases: object

Matrix Event class for events in invited rooms.

Events for invited rooms will have a stripped down version of their counterparts for joined rooms.

Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:dict
sender

The fully-qualified ID of the user who sent this event.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
classmethod parse_event(event_dict)[source]

Parse a Matrix invite event and create a higher level event object.

This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

Parameters:event_dict (dict) – The dictionary representation of the event.
class nio.events.invite_events.InviteMemberEvent(source: Dict[KT, VT], sender: str, state_key: str, membership: str, prev_membership: str, content: dict, prev_content: dict = None)[source]

Bases: nio.events.invite_events.InviteEvent

Class representing to an m.room.member event in an invited room.

state_key

The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.

Type:str
membership

The membership state of the user. One of “invite”, “join”, “leave”, “ban”.

Type:str
prev_membership

The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.

Type:str, optional
content

The content of the of the membership event.

Type:dict
prev_content

The content of a previous membership event that this one is overwriting.

Type:dict, optional
classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

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

Bases: nio.events.invite_events.InviteEvent

Event holding the name of the invited room.

This is the RoomNameEvent equivalent for invited rooms.

The room name is a human-friendly string designed to be displayed to the end-user. The room name is not unique, as multiple rooms can have the same room name set.

name

The name of the room.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an InviteEvent from a dictionary.

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

To-device Events

nio to-device events.

To-device events are events that are sent dirrectly between two devices instead of normally sending events in a room.

To-device events can be sent to a specific device of a user or to all devices of a user.

class nio.events.to_device.BaseRoomKeyRequest(source, sender, requesting_device_id: str, request_id: str)[source]

Bases: nio.events.to_device.ToDeviceEvent

Base class for room key requests. requesting_device_id (str): The id of the device that is requesting the

key.

request_id (str): A unique identifier for the request.

classmethod parse_event(event_dict)[source]

Parse a to-device event and create a higher level event object.

This function parses the type of the to-device event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

Parameters:event_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.DummyEvent(source, sender, sender_key, sender_device)[source]

Bases: nio.events.to_device.ToDeviceEvent

Event containing a dummy message.

This event type is used start a new Olm session with a device. The event has no content.

sender

The sender of the event.

Type:str
sender_key

The key of the sender that sent the event.

Type:str
classmethod from_dict(event_dict, sender, sender_key)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.EncryptedToDeviceEvent(source, sender)[source]

Bases: nio.events.to_device.ToDeviceEvent

class nio.events.to_device.ForwardedRoomKeyEvent(source, sender, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]

Bases: nio.events.to_device.RoomKeyEvent

Event containing a room key that got forwarded to us.

sender

The sender of the event.

Type:str
sender_key

The key of the sender that sent the event.

Type:str
room_id

The room ID of the room to which the session key belongs to.

Type:str
session_id

The session id of the session key.

Type:str
algorithm

The algorithm of the session key.

Type:str
classmethod from_dict(event_dict, sender, sender_key)[source]

Create a ForwardedRoomKeyEvent from a event dictionary.

Parameters:
  • event_dict (Dict) – The dictionary containing the event.
  • sender (str) – The sender of the event.
  • sender_key (str) – The key of the sender that sent the event.
class nio.events.to_device.KeyVerificationAccept(source, sender, transaction_id: str, commitment: str, key_agreement_protocol: str, hash: str, message_authentication_code: str, short_authentication_string: List[str])[source]

Bases: nio.events.to_device.KeyVerificationEvent

Event signaling that the SAS verification start has been accepted.

commitment

The commitment value of the verification process.

Type:str
key_agreement_protocol

The key agreement protocol the device is choosing to use

Type:str
hash

A list of strings specifying the hash methods the sending device understands.

Type:str
message_authentication_code

The message authentication code the device is choosing to use.

Type:str
short_authentication_string

A list of strings specifying the SAS methods that can be used in the verification process.

Type:list
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.KeyVerificationCancel(source, sender, transaction_id: str, code: str, reason: str)[source]

Bases: 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 cancelled by the user.

Type:str
reason

A human readable description of the cancelation code.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.KeyVerificationEvent(source, sender, transaction_id: str)[source]

Bases: 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, sender, transaction_id: str, key: str)[source]

Bases: nio.events.to_device.KeyVerificationEvent

Event carrying a key verification key.

After this event is received the short authentication string can be shown to the user.

key

The device’s ephemeral public key, encoded as unpadded base64.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.KeyVerificationMac(source, sender, transaction_id: str, mac: Dict[str, str], keys: str)[source]

Bases: nio.events.to_device.KeyVerificationEvent

Event holding a message authentication code of the verification process.

After this event is received the device that we are verifying will be marked as verified given that we have accepted the short authentication string as well.

mac

A map of the key ID to the MAC of the key, using the algorithm in the verification process. The MAC is encoded as unpadded base64.

Type:dict
keys

The MAC of the comma-separated, sorted, list of key IDs given in the mac property, encoded as unpadded base64.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.KeyVerificationStart(source, sender, transaction_id: str, from_device: str, method: str, key_agreement_protocols: List[str], hashes: List[str], message_authentication_codes: List[str], short_authentication_string: List[str])[source]

Bases: nio.events.to_device.KeyVerificationEvent

Event signaling the start of a SAS key verification process.

from_device

The device ID which is initiating the process.

Type:str
method

The verification method to use.

Type:str
key_agreement_protocols

A list of strings specifying the key agreement protocols the sending device understands.

Type:list
hashes

A list of strings specifying the hash methods the sending device understands.

Type:list
message_authentication_codes

A list of strings specifying the message authentication codes that the sending device understands.

Type:list
short_authentication_string

A list of strings specifying the SAS methods the sending device (and the sending device’s user) understands.

Type:list
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.OlmEvent(source, sender, sender_key, ciphertext, transaction_id=None)[source]

Bases: nio.events.to_device.EncryptedToDeviceEvent

An Olm encrypted event.

Olm events are used to exchange end to end encrypted messages between two devices. They will mostly contain encryption keys to establish a Megolm session for a room.

nio users will never see such an event under normal circumstances since decrypting this event will produce an event of another type.

sender

The fully-qualified ID of the user who sent this event.

Type:str
sender_key

The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.

Type:str, optional
ciphertext

The undecrypted ciphertext of the event.

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

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.RoomKeyEvent(source, sender, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]

Bases: nio.events.to_device.ToDeviceEvent

Event containing a megolm room key that got sent to us.

sender

The sender of the event.

Type:str
sender_key

The key of the sender that sent the event.

Type:str
room_id

The room ID of the room to which the session key belongs to.

Type:str
session_id

The session id of the session key.

Type:str
algorithm

The algorithm of the session key.

Type:str
classmethod from_dict(event_dict, sender, sender_key)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.RoomKeyRequest(source, sender, requesting_device_id: str, request_id: str, algorithm: str, room_id: str, sender_key: str, session_id: str)[source]

Bases: nio.events.to_device.BaseRoomKeyRequest

Event signaling that a room key was requested from us.

algorithm

The encryption algorithm the requested key in this event is to be used with. Will be set only if the action is ‘request’.

Type:str, optional
room_id

The id of the room that the key is used in. Will be set only if the action is ‘request’.

Type:str, optional
sender_key

The key of the device that initiated the session. Will be set only if the action is ‘request’.

Type:str, optional
session_id

The id of the session the key is for. Will

Type:str, optional
be set only if the action is 'request'.
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.RoomKeyRequestCancellation(source, sender, requesting_device_id: str, request_id: str)[source]

Bases: nio.events.to_device.BaseRoomKeyRequest

Event signaling that a previous room key request was canceled.

classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
class nio.events.to_device.ToDeviceEvent(source, sender)[source]

Bases: object

Base Event class for events that are sent using the to-device endpoint.

source

The source dictionary of the event. This allows access to all the event fields in a non-secure way.

Type:dict
sender

The fully-qualified ID of the user who sent this event.

Type:str
classmethod from_dict(parsed_dict)[source]

Create an Event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
classmethod parse_encrypted_event(event_dict)[source]

Parse an encrypted to-device event.

Encrypted events may have different fields depending on the algorithm that was used to encrypt them.

This function checks the algorithm of the event and produces a higher level event from the provided dictionary.

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

Returns None if the algorithm of the event is unknown.

classmethod parse_event(event_dict)[source]

Parse a to-device event and create a higher level event object.

This function parses the type of the to-device event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

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

Ephemeral Events

nio Ephemeral events.

Ephemeral events are a special type of events that are not recorded in the room history.

Ephemeral events are used for typing notifications and read receipts.

class nio.events.ephemeral.EphemeralEvent[source]

Bases: object

Base class for ephemeral events.

classmethod from_dict(parsed_dict)[source]

Create an Ephemeral event from a dictionary.

Parameters:parsed_dict (dict) – The dictionary representation of the event.
classmethod parse_event(event_dict)[source]

Parse an ephemeral event and create a higher level event object.

This function parses the type of the ephemeral event and produces a higher level event object representing the parsed event.

The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.

If the event has an unknown type None is returned as well.

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

Bases: nio.events.ephemeral.EphemeralEvent

Informs the client of the list of users currently typing in a room.

users

The list of user IDs typing in this room, if any.

Type:List
classmethod from_dict(parsed_dict)[source]

Create an Ephemeral event from a dictionary.

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

Account Data

nio Account data events.

Clients can store custom config data for their account on their homeserver.

This account data will be synced between different devices and can persist across installations on a particular device.

class nio.events.account_data.AccountDataEvent[source]

Bases: object

Abstract class for account data events.

classmethod parse_event(event_dict)[source]
class nio.events.account_data.FullyReadEvent(event_id)[source]

Bases: nio.events.account_data.AccountDataEvent

Read marker location event.

The current location of the user’s read marker in a room. This event appears in the user’s room account data for the room the marker is applicable for.

event_id

The event id the user’s read marker is located at in the room.

Type:str
classmethod from_dict(event_dict)[source]

Construct a FullyReadEvent from a dictionary.

class nio.events.account_data.TagEvent(tags)[source]

Bases: nio.events.account_data.AccountDataEvent

Event representing the tags of a room.

Room tags may include:

  • m.favourite for favourite rooms
  • m.lowpriority for low priority room

A tag may have an order between 0 and 1, indicating the room’s possition towards other rooms with the same tag.

tags

The tags of the room

Type:Dict[string, Optional[Dict[str, float]]
and their contents.
classmethod from_dict(event_dict)[source]

Construct a TagEvent from a dictionary.

class nio.events.account_data.UnknownAccountDataEvent(type, content)[source]

Bases: nio.events.account_data.AccountDataEvent

Account data event of an unknown type.

type

The type of the event.

Type:str
content

The content of the event.

Type:Dict
classmethod from_dict(event_dict)[source]

Construct an UnknownAccountDataEvent from a dictionary.

Messages

class nio.messages.ToDeviceMessage(type: str, recipient: str, recipient_device: str, content: Dict[KT, VT])[source]

A to-device message that can be sent to the homeserver.

type

The type of the message.

Type:str
recipient

The user to whom we should sent this message.

Type:str
recipient_device

The device id of the device that the message should be sent to.

Type:str
content

The content that should be sent to the user.

Type:Dict[Any, Any]
as_dict()[source]

Format the to-device message as a dictionary for a HTTP request.

Exceptions

exception nio.exceptions.EncryptionError[source]

Bases: Exception

exception nio.exceptions.GroupEncryptionError[source]

Bases: Exception

exception nio.exceptions.LocalProtocolError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.LocalTransportError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.MembersSyncError[source]

Bases: nio.exceptions.LocalProtocolError

exception nio.exceptions.OlmTrustError[source]

Bases: Exception

exception nio.exceptions.ProtocolError[source]

Bases: Exception

exception nio.exceptions.RemoteProtocolError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.RemoteTransportError[source]

Bases: nio.exceptions.ProtocolError

exception nio.exceptions.SendRetryError[source]

Bases: nio.exceptions.LocalProtocolError

exception nio.exceptions.VerificationError[source]

Bases: Exception

Responses

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

A response representing a successful file content request.

body

The file’s content in bytes.

Type:bytes
content_type

The content MIME type of the file, e.g. “image/png”.

Type:str
classmethod from_data(data, content_type)[source]

Create a FileResponse from file content returned by the server.

Parameters:
  • data (bytes) – The file’s content in bytes.
  • content_type (str) – The content MIME type of the file, e.g. “image/png”.
class nio.responses.DeleteDevicesAuthResponse(session: str, flows: Dict[KT, VT], params: Dict[KT, VT])[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.DeleteDevicesResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.DeleteDevicesError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Device(id: str, display_name: str, last_seen_ip: str, last_seen_date: datetime.datetime)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.DeviceList(changed: List[str], left: List[str])[source]
class nio.responses.DevicesResponse(devices: List[nio.responses.Device])[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.DevicesError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.DeviceOneTimeKeyCount(curve25519: int, signed_curve25519: int)[source]
class nio.responses.ErrorResponse(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.InviteInfo(invite_state: List[T])[source]
class nio.responses.JoinResponse(room_id: str)[source]
static create_error(parsed_dict)[source]
class nio.responses.JoinError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.JoinedMembersResponse(members: List[nio.responses.RoomMember], room_id: str)[source]
classmethod from_dict(parsed_dict, room_id)[source]
class nio.responses.JoinedMembersError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.KeysClaimResponse(one_time_keys: Dict[Any, Any], failures: Dict[Any, Any], room_id: str = '')[source]
classmethod from_dict(parsed_dict, room_id='')[source]
class nio.responses.KeysClaimError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.KeysQueryResponse(device_keys: Dict[KT, VT], failures: Dict[KT, VT])[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.KeysQueryError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.KeysUploadResponse(curve25519_count: int, signed_curve25519_count: int)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.KeysUploadError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.LoginResponse(user_id: str, device_id: str, access_token: str)[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.LoginError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.LoginInfoResponse(flows: List[str])[source]
classmethod from_dict(parsed_dict)[source]
class nio.responses.LoginInfoError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.LogoutResponse[source]
classmethod from_dict(parsed_dict)[source]

Create a response for logout response from server.

class nio.responses.LogoutError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Response[source]
elapsed
end_time = None
start_time = None
timeout = 0
uuid = ''
class nio.responses.RoomInfo(timeline: nio.responses.Timeline, state: List[T], ephemeral: List[T], account_data: List[T], summary: Optional[nio.responses.RoomSummary] = None)[source]
static parse_account_data(event_dict)[source]

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

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

Response representing a successful forget room request.

static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomForgetError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomMember(user_id: str, display_name: str, avatar_url: str)[source]
class nio.responses.RoomMessagesResponse(room_id: str, chunk: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], start: str, end: str)[source]
classmethod from_dict(parsed_dict, room_id)[source]
class nio.responses.RoomMessagesError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomPutStateResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomPutStateError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomRedactResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomRedactError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomSendResponse(event_id: str, room_id: str)[source]
static create_error(parsed_dict, room_id)[source]
class nio.responses.RoomSendError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]
class nio.responses.RoomSummary(invited_member_count: Optional[int] = None, joined_member_count: Optional[int] = None, heroes: List[str] = [])[source]
class nio.responses.Rooms(invite: Dict[KT, VT], join: Dict[KT, VT], leave: Dict[KT, VT])[source]
class nio.responses.ShareGroupSessionResponse(room_id: str, users_shared_with: set)[source]

Response representing a successful group sessions sharing request.

room_id

The room id of the group session.

Type:str
users_shared_with

A set containing a tuple of user id device id pairs with whom we shared the group session in this request.

Type:Set[Tuple[str, str]]
classmethod from_dict(_, room_id, users_shared_with)[source]

Create a response from the json dict the server returns.

Parameters:
  • parsed_dict (Dict) – The dict containing the raw json response.
  • room_id (str) – The room id of the room to which the group session belongs to.
  • users_shared_with (Set[Tuple[str, str]]) – A set containing a tuple of user id device id pairs with whom we shared the group session in this request.
class nio.responses.ShareGroupSessionError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '', users_shared_with: set = None)[source]

Response representing unsuccessful group sessions sharing request.

classmethod from_dict(parsed_dict, room_id, users_shared_with)[source]
class nio.responses.SyncResponse(next_batch: str, rooms: nio.responses.Rooms, device_key_count: nio.responses.DeviceOneTimeKeyCount, device_list: nio.responses.DeviceList, to_device_events: List[nio.events.to_device.ToDeviceEvent])[source]
class nio.responses.PartialSyncResponse(next_batch: str, rooms: nio.responses.Rooms, device_key_count: nio.responses.DeviceOneTimeKeyCount, device_list: nio.responses.DeviceList, to_device_events: List[nio.events.to_device.ToDeviceEvent], unhandled_rooms: Dict[str, nio.responses.RoomInfo])[source]
next_part(max_events=0)[source]
class nio.responses.SyncError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.Timeline(events: List[T], limited: bool, prev_batch: str)[source]
class nio.responses.UpdateDeviceResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.UpdateDeviceError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RoomTypingResponse(room_id: str)[source]

A response representing a successful room typing request.

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

A response representing a unsuccessful room typing request.

class nio.responses.RoomReadMarkersResponse(room_id: str)[source]

A response representing a successful room read markers request.

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

A response representing a unsuccessful room read markers request.

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

A response representing a successful upload request.

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

A response representing a unsuccessful upload request.

class nio.responses.ProfileGetResponse(displayname: Optional[str] = None, avatar_url: Optional[str] = None, other_info: Dict[Any, Any] = NOTHING)[source]

Response representing a successful get profile request.

displayname

The display name of the user. None if the user doesn’t have a display name.

Type:str, optional
avatar_url

The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.

Type:str, optional
other_info

Contains any other information returned for the user’s profile.

Type:dict
classmethod from_dict(parsed_dict)[source]
class nio.responses.ProfileGetError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetDisplayNameResponse(displayname: Optional[str] = None)[source]

Response representing a successful get display name request.

displayname

The display name of the user. None if the user doesn’t have a display name.

Type:str, optional
classmethod from_dict(parsed_dict)[source]
class nio.responses.ProfileGetDisplayNameError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetDisplayNameResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.ProfileSetDisplayNameError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileGetAvatarResponse(avatar_url: Optional[str] = None)[source]

Response representing a successful get avatar request.

avatar_url

The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.

Type:str, optional
classmethod from_dict(parsed_dict)[source]
class nio.responses.ProfileGetAvatarError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.ProfileSetAvatarResponse[source]
static create_error(parsed_dict)[source]
class nio.responses.ProfileSetAvatarError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]
class nio.responses.RoomKeyRequestResponse(request_id: str, session_id: str, room_id: str, algorithm: str)[source]

Response representing a successful room key request.

request_id

The id of the that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.

Type:str
session_id

The id of the session that we requested.

Type:str
room_id

The id of the room that the session belongs to.

Type:str
algorithm

The encryption algorithm of the session.

Type:str
classmethod from_dict(_, request_id, session_id, room_id, algorithm)[source]

Create a RoomKeyRequestResponse from a json response.

Parameters:
  • parsed_dict (Dict) – The dictionary containing the json response.
  • request_id (str) – The id of that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.
  • session_id (str) – The id of the session that we requested.
  • room_id (str) – The id of the room that the session belongs to.
  • algorithm (str) – The encryption algorithm of the session.
class nio.responses.RoomKeyRequestError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]

Response representing a failed room key request.

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

A response representing a successful thumbnail request.

classmethod from_data(data, content_type)[source]

Create a FileResponse from file content returned by the server.

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

A response representing a unsuccessful thumbnail request.

class nio.responses.ToDeviceResponse(to_device_message)[source]

Response representing a successful room key request.

classmethod from_dict(parsed_dict, message)[source]

Create a ToDeviceResponse from a json response.

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

Response representing a unsuccessful room key request.

classmethod from_dict(parsed_dict, message)[source]
class nio.responses.RoomContextResponse(room_id: str, start: str, end: str, event, events_before: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], events_after: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], state: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]])[source]

Room event context response.

This Response holds a number of events that happened just before and after a specified event.

room_id

The room id of the room which the events belong to.

Type:str
start

A token that can be used to paginate backwards with.

Type:str
end

A token that can be used to paginate forwards with.

Type:str
events_before

A list of room events that happened just before the requested event, in reverse-chronological order.

Type:List[Event]
event

Details of the requested event.

Type:Event
events_after

A list of room events that happened just after the requested event, in chronological order.

Type:List[Event]
state

The state of the room at the last event returned.

Type:List[Event]
classmethod from_dict(parsed_dict, room_id)[source]
class nio.responses.RoomContextError(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]

Response representing a unsuccessful room context request.

Storage

Nio storage module.

This module contains storage classes that are used to store encryption devices, encryption keys and the trust state of devices.

The module contains three store implementations one using a Sqlite database and plaintext files to store keys and the truststate of devices, one that uses a pure Sqlite database and one that stores the Sqlite database in memory.

User provided store types can be implemented by overriding the methods provided in the MatrixStore base class.

class nio.store.MatrixStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Storage class for matrix state.

add_outgoing_key_request(key_request)[source]

Add an outgoing key request to the store.

blacklist_device(device)[source]

Mark a device as blacklisted.

Parameters:device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was blacklisted, False otherwise, e.g. if the device was already blacklisted.

delete_encrypted_room(room)[source]

Delete the a encrypted room from the store.

ignore_device(device)[source]

Mark a device as ignored.

Parameters:device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was ignored, False otherwise, e.g. if the device was already ignored.

ignore_devices(devices)[source]

Mark a list of devices as ignored.

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

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

Check if a device is blacklisted.

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

Check if a device is ignored.

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

Check if a device is verified.

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

Load the Olm account from the database.

Returns:
OlmAccount object, or None if it wasn’t found for the
current device_id.
load_device_keys()[source]

Load all the device keys from the database.

Returns DeviceStore containing the OlmDevices with the device keys.

load_encrypted_rooms()[source]

Load the set of encrypted rooms for this account.

Returns:Set containing room ids of encrypted rooms.
load_inbound_group_sessions()[source]

Load all Olm sessions from the database.

Returns:GroupSessionStore object, containing all the loaded sessions.
load_outgoing_key_requests()[source]

Load the set of outgoing key requests for this account.

Returns:Set containing request ids of key requests.
load_sessions()[source]

Load all Olm sessions from the database.

Returns:SessionStore object, containing all the loaded sessions.
remove_outgoing_key_request(key_request)[source]

Remove an active outgoing key request from the store.

save_account(account)[source]

Save the provided Olm account to the database.

Parameters:account (OlmAccount) – The olm account that will be pickled and saved in the database.
save_device_keys(device_keys)[source]

Save the provided device keys to the database.

Parameters:device_keys (Dict[str, Dict[str, OlmDevice]]) – A dictionary containing a mapping from a user id to a dictionary containing a mapping of a device id to a OlmDevice.
save_encrypted_rooms(rooms)[source]

Save the set of room ids for this account.

save_inbound_group_session(session)[source]

Save the provided Megolm inbound group session to the database.

Parameters:session (InboundGroupSession) – The session to save.
save_session(sender_key, session)[source]

Save the provided Olm session to the database.

Parameters:
  • curve_key (str) – The curve key that owns the Olm session.
  • session (Session) – The Olm session that will be pickled and saved in the database.
save_sync_token(token)[source]

Save the given token

unblacklist_device(device)[source]

Unmark a device as blacklisted.

Parameters:device (OlmDevice) – The device that will be unmarked as blacklisted
unignore_device(device)[source]

Unmark a device as ignored.

Parameters:device (OlmDevice) – The device that will be marked as blacklisted

Returns True if the device was unignored, False otherwise, e.g. if the device wasn’t ignored in the first place.

unverify_device(device)[source]

Unmark a device as verified.

Parameters:device (OlmDevice) – The device that will be unmarked as verified

Returns True if the device was unverified, False otherwise, e.g. if the device wasn’t verified.

verify_device(device)[source]

Mark a device as verified.

Parameters:device (OlmDevice) – The device that will be marked as verified

Returns True if the device was verified, False otherwise, e.g. if the device was already verified.

class nio.store.DefaultStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Bases: nio.store.database.MatrixStore

The default nio Matrix Store.

This store uses an Sqlite database as the main storage format while device trust state is stored in plaintext files using a format similar to the ssh known_hosts file format. The files will be created in the same directory as the main Sqlite database.

One such file is created for each of the 3 valid states (verified, blacklisted, ignored). If a device isn’t found in any of those files the verification state is considered to be unset.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.
  • device_id (str) – The device id of the user’s device.
  • store_path (str) – The path where the store should be stored.
  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.
  • database_name (str, optional) – The file-name of the database that should be used.
class nio.store.SqliteStore(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]

Bases: nio.store.database.MatrixStore

The Sqlite only nio Matrix Store.

This store uses an Sqlite database as the main storage format as well as the store format for the trust state.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.
  • device_id (str) – The device id of the user’s device.
  • store_path (str) – The path where the store should be stored.
  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.
  • database_name (str, optional) – The file-name of the database that should be used.
class nio.store.SqliteMemoryStore(user_id, device_id, pickle_key='')[source]

Bases: nio.store.database.SqliteStore

The Sqlite only nio Matrix Store.

This store uses an Sqlite database as the main storage format as well as the store format for the trust state. The Sqlite database will be stored only in memory and all the data will be lost after the object is deleted.

Parameters:
  • user_id (str) – The fully-qualified ID of the user that owns the store.
  • device_id (str) – The device id of the user’s device.
  • pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.

Encryption

nio encryption module.

Encryption is handled mostly transparently to the user.

The main thing users need to worry about is device verification.

While device verification is handled in the Client classes of nio the classes that are used to introspect OlmDevices or device authentication sessions are documented here.

class nio.crypto.DeviceStore[source]

A store that holds olm devices in memory.

The DeviceStore class implements the iter method, devices can be iterated over normaly using:

>>> for device in device_store:
...    print(device.user_id, device.device_id)

To get only non-deleted devices of a user the active_user_devices method can be used:

>>> for device in device_store.active_user_devices("@bob:example.org"):
...    print(device.user_id, device.device_id)
active_user_devices(user_id)[source]

Get all the non-deleted devices of a user.

Parameters:user_id (str) – The user for which we would like to get the devices for.

This returns an iterator over all the non-deleted devices of the given user.

add(device)[source]

Add the given device to the store.

Parameters:device (OlmDevice) – The device that should be added to the store.

Returns True if the device was added to the store, False if it already was in the store.

device_from_sender_key(user_id, sender_key)[source]

Get a non-deleted device of a user with the matching sender key.

Parameters:
  • user_id (str) – The user id of the device owner.
  • sender_key (str) – The encryption key that is owned by the device,
  • a curve25519 public key. (usually) –
items()[source]

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

users

Get the list of users that the device store knows about.

values()[source]

List of devices in the form of a dict(device_id, OlmDevice).

class nio.crypto.OlmDevice(user_id: str, device_id: str, keys: Dict[str, str], display_name: str = '', deleted: bool = False, trust_state: nio.crypto.sessions.TrustState = <TrustState.unset: 0>)[source]

Class holding info about users Olm devices.

OlmDevices represent user devices with which we can communicate in an encrypted manner. To do so an OlmDevice needs to have its trust state set. The trust state can be set to one of “verified”, “ignored”, or “blacklisted”.

Note that the trust state should never be moddified directly on an OlmDevice, all the attributes here are read only.

The trust state can be changed by pasing the OlmDevice to a nio Client or a MatrixStore class.

user_id

The id of the user that the device belongs to.

Type:str
device_id

The device id that combined with the user id uniquely identifies the device.

Type:str
keys

A dictionary containing the type and the public part of this devices encryption keys.

Type:Dict
display_name

The human readable name of this device.

Type:str
deleted

A boolean signaling if this device has been deleted by its owner.

Type:bool
trust_state

The trust state of this device.

Type:TrustState
as_dict()[source]

Convert the OlmDevice into a dictionary.

blacklisted

Is the device blacklisted.

curve25519

The curve25519 key of the device.

ed25519

The ed25519 fingerprint key of the device.

id

The device id.

Same as the device_id attribute.

ignored

Is the device ignored.

verified

Is the device verified.

class nio.crypto.TrustState[source]

The device trust state.

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

class nio.crypto.Sas(own_user, own_device, own_fp_key, other_olm_device, transaction_id=None, short_auth_string=None, mac_methods=None)[source]

Matrix Short Authentication String class.

This class implements a state machine to handle device verification using short authentication strings.

we_started_it

Is true if the verification process was started by us, otherwise false.

Type:bool
sas_accepted

Is true if we accepted that the short authentication string matches on both devices.

Type:bool
Parameters:
  • own_user (str) – The user id of our own user.
  • own_device (str) – The device id of our own user.
  • own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.
  • other_olm_device (OlmDevice) – The OlmDevice which we would like to verify.
  • transaction_id (str, optional) – A string that will uniquely identify this verification process. A random and unique string will be generated if one isn’t provided.
  • short_auth_string (List[str], optional) – A list of valid short authentication methods that the client would like to allow for this authentication session. By default the ‘emoji’ and ‘decimal’ methods are allowed.
accept_sas()[source]

Accept the short authentication string.

accept_verification()[source]

Create a content dictionary to accept the verification offer.

cancel()[source]

Cancel the authentication process.

canceled

Is the verification request canceled.

classmethod from_key_verification_start(own_user, own_device, own_fp_key, other_olm_device, event)[source]

Create a SAS object from a KeyVerificationStart event.

Parameters:
  • own_user (str) – The user id of our own user.
  • own_device (str) – The device id of our own user.
  • own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.
  • other_olm_device (OlmDevice) – The Olm device of the other user that should be verified.
  • event (KeyVerificationStart) – The event that we received from the other device to start the key verification process.
get_cancellation()[source]

Create a dictionary containing our verification cancellation.

get_decimals()[source]

Get the decimal short authentication string.

Returns a tuple that contains three 4 digit integer numbers that represent the short authentication string.

get_emoji()[source]

Get the emoji short authentication string.

Returns a list of tuples that contain the emoji and the description of the emoji of the short authentication string.

get_mac()[source]

Create a dictionary containing our MAC.

receive_accept_event(event)[source]

Receive a KeyVerificationAccept event.

receive_key_event(event)[source]

Receive a KeyVerificationKey event.

receive_mac_event(event)[source]

Receive a KeyVerificationMac event.

Parameters:event (KeyVerificationMac) – The MAC event that was received for this SAS session.
reject_sas()[source]

Reject the authentication string.

share_key()[source]

Create a dictionary containing our public key.

start_verification()[source]

Create a content dictionary to start the verification.

timed_out

Did the verification process time out.

verified

Is the device verified and the request done.