API¶
This document details the API of nio.
Api¶
-
class
nio.
Api
[source]¶ Matrix API class.
Static methods reflecting the Matrix REST API.
-
static
content_repository_config
(access_token: str) → Tuple[str, str][source]¶ Get the content repository configuration, such as upload limits.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
-
static
delete_devices
(access_token: str, devices: List[str], auth_dict: Optional[Dict[str, str]] = None) → Tuple[str, str, str][source]¶ Delete a device.
This API endpoint uses the User-Interactive Authentication API.
This tells the server to delete the given devices and invalidate their associated access tokens.
Should first be called with no additional authentication information.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
devices (List[str]) – A list of devices which will be deleted.
auth_dict (Dict) – Additional authentication information for the user-interactive authentication API.
-
static
devices
(access_token: str) → Tuple[str, str][source]¶ Get the list of devices for the current user.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
-
static
discovery_info
() → Tuple[str, str][source]¶ Get discovery information about a domain.
Returns the HTTP method and HTTP path for the request.
-
static
download
(server_name: str, media_id: str, filename: Optional[str] = None, allow_remote: bool = True) → Tuple[str, str][source]¶ Get the content of a file from the content repository.
Returns the HTTP method and HTTP path for the request.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
static
encrypted_mxc_to_plumb
(mxc: str, key: str, hash: str, iv: str, homeserver: Optional[str] = None) → Optional[str][source]¶ Convert a matrix content URI to a encrypted mxc URI.
The return value of this function will have a URI schema of emxc://. The path of the URI will be converted just like the mxc_to_http() function does, but it will also contain query parameters that are necessary to decrypt the payload the URI is pointing to.
This function is useful to present a clickable URI that can be passed to a plumber program that will download and decrypt the content that the matrix content URI is pointing to.
The returned URI should never be converted to http and opened directly, as that would expose the decryption parameters to any middleman or ISP.
- Parameters
mxc (str) – The matrix content URI.
key (str) – The encryption key that can be used to decrypt the payload the URI is pointing to.
hash (str) – The hash of the payload.
iv (str) – The initial value needed to decrypt the payload.
-
static
get_presence
(access_token: str, user_id: str) → Tuple[str, str][source]¶ Get the given user’s presence state.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_id (str) – User id whose presence state to get.
-
static
join
(access_token, room_id)[source]¶ Join a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room identifier or alias to join.
-
static
joined_members
(access_token: str, room_id: str) → Tuple[str, str][source]¶ Get the list of joined members for a room.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – Room id of the room where the user is typing.
-
static
joined_rooms
(access_token: str) → Tuple[str, str][source]¶ Get the list of joined rooms for the logged in account.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
-
static
keys_claim
(access_token: str, user_set: Dict[str, Iterable[str]]) → Tuple[str, str, str][source]¶ Claim one-time keys for use in Olm pre-key messages.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_set (Dict[str, List[str]]) – The users and devices for which to claim one-time keys to be claimed. A map from user ID, to a list of device IDs.
-
static
keys_query
(access_token: str, user_set: Iterable[str], token: Optional[str] = None) → Tuple[str, str, str][source]¶ Query the current devices and identity keys for the given users.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_set (Set[str]) – The users for which the keys should be downloaded.
token (Optional[str]) – If the client is fetching keys as a result of a device update received in a sync request, this should be the ‘since’ token of that sync request, or any later sync token.
-
static
keys_upload
(access_token: str, key_dict: Dict[str, Any]) → Tuple[str, str, str][source]¶ Publish end-to-end encryption keys.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
key_dict (Dict) – The dictionary containing device and one-time keys that will be published to the server.
-
static
login
(user: str, password: Optional[str] = None, device_name: Optional[str] = '', device_id: Optional[str] = '', token: Optional[str] = None) → Tuple[str, str, str][source]¶ Authenticate the user.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
user (str) – The fully qualified user ID or just local part of the user ID, to log in.
password (str) – The user’s password.
device_name (str) – A display name to assign to a newly-created device. Ignored if device_id corresponds to a known device
device_id (str) – ID of the client device. If this does not correspond to a known client device, a new device will be created.
-
static
login_info
() → Tuple[str, str][source]¶ Get the homeserver’s supported login types
Returns the HTTP method and HTTP path for the request.
-
static
login_raw
(auth_dict: Dict[str, Any]) → Tuple[str, str, str][source]¶ Login to the homeserver using a raw dictionary.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
auth_dict (Dict[str, Any) –
The authentication dictionary containing the elements for the logon. See the example below and here
for detailed documentation
Example
>>> auth_dict = { >>> "type": "m.login.password", >>> "identifier": { >>> "type": "m.id.thirdparty", >>> "medium": "email", >>> "address": "testemail@mail.org" >>> }, >>> "password": "PASSWORDABCD", >>> "initial_device_display_name": "Test user" >>> }
-
static
logout
(access_token, all_devices=False)[source]¶ Logout the session.
Returns nothing.
- Parameters
access_token (str) – the access token to be used with the request.
all_devices (bool) – Logout all sessions from all devices if set to True.
-
static
mimetype_to_msgtype
(mimetype: str) → str[source]¶ Turn a mimetype into a matrix message type.
-
static
mxc_to_http
(mxc: str, homeserver: Optional[str] = None) → Optional[str][source]¶ Convert a matrix content URI to a HTTP URI.
-
static
profile_get
(user_id: str) → Tuple[str, str][source]¶ Get the combined profile information for a user.
Returns the HTTP method and HTTP path for the request.
- Parameters
user_id (str) – User id to get the profile for.
-
static
profile_get_avatar
(user_id)[source]¶ Get avatar URL.
Returns the HTTP method and HTTP path for the request.
- Parameters
user_id (str) – User id to get avatar for.
-
static
profile_get_displayname
(user_id)[source]¶ Get display name.
Returns the HTTP method and HTTP path for the request.
- Parameters
user_id (str) – User id to get display name for.
-
static
profile_set_avatar
(access_token, user_id, avatar_url)[source]¶ Set avatar url.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_id (str) – User id to set display name for.
avatar_url (str) – matrix content URI of the avatar to set.
-
static
profile_set_displayname
(access_token, user_id, display_name)[source]¶ Set display name.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_id (str) – User id to set display name for.
display_name (str) – Display name for user to set.
-
static
register
(user, password=None, device_name='', device_id='')[source]¶ Register a new user.
- Parameters
user (str) – The fully qualified user ID or just local part of the user ID, to log in.
password (str) – The user’s password.
device_name (str) – A display name to assign to a newly-created device. Ignored if device_id corresponds to a known device
device_id (str) – ID of the client device. If this does not correspond to a known client device, a new device will be created.
-
static
room_ban
(access_token: str, room_id: str, user_id: str, reason: Optional[str] = None) → Tuple[str, str, str][source]¶ Ban a user from a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that the user will be banned from.
user_id (str) – The user_id of the user that should be banned.
reason (str, optional) – A reason for which the user is banned.
-
static
room_context
(access_token, room_id, event_id, limit=None)[source]¶ Fetch a number of events that happened before and after an event. This allows clients to get the context surrounding an event.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room_id of the room that contains the event and its context.
event_id (str) – The event_id of the event that we wish to get the context for.
limit (int, optional) – The maximum number of events to request.
-
static
room_create
(access_token, visibility=<RoomVisibility.private: 'private'>, alias=None, name=None, topic=None, room_version=None, federate=True, is_direct=False, preset=None, invite=(), initial_state=(), power_level_override=None)[source]¶ Create a new room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to
RoomVisibility.private
.alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.
name (str, optional) – A name to set for the room.
topic (str, optional) – A topic to set for the room.
room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400
M_UNSUPPORTED_ROOM_VERSION
error will be returned.federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to
True
. Cannot be changed later.is_direct (bool) – If this should be considered a direct messaging room. If
True
, the server will set theis_direct
flag onm.room.member events
sent to the users ininvite
. Defaults toFalse
.preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the
visibility
:RoomVisibility.public
equates toRoomPreset.public_chat
, andRoomVisibility.private
equates to aRoomPreset.private_chat
.invite (list) – A list of user id to invite to the room.
initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediatly by having a
m.room.encryption
event dict.power_level_override (dict) – A
m.room.power_levels content
dict to override the default. The dict will be applied on top of the generatedm.room.power_levels
event before it is sent to the room.
-
static
room_forget
(access_token, room_id)[source]¶ Forget a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that will be forgotten.
-
static
room_get_event
(access_token: str, room_id: str, event_id: str) → Tuple[str, str][source]¶ Get a single event based on roomId/eventId.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room where the event is in.
event_id (str) – The event id to get.
-
static
room_get_state
(access_token, room_id)[source]¶ Fetch the current state for a room.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room where the state is fetched from.
-
static
room_get_state_event
(access_token, room_id, event_type, state_key='')[source]¶ Fetch a state event.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room where the state is fetched from.
event_type (str) – The type of the event that will be fetched.
state_key – The key of the state to look up. Defaults to an empty string.
-
static
room_invite
(access_token, room_id, user_id)[source]¶ Invite a user to a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that the user will be invited to.
user_id (str) – The user id of the user that should be invited.
-
static
room_kick
(access_token, room_id, user_id, reason=None)[source]¶ Kick a user from a room, or withdraw their invitation.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that the user will be kicked from.
user_id (str) – The user_id of the user that should be kicked.
reason (str, optional) – A reason for which the user is kicked.
-
static
room_leave
(access_token, room_id)[source]¶ Leave a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that will be left.
-
static
room_messages
(access_token: str, room_id: str, start: str, end: Optional[str] = None, direction: nio.api.MessageDirection = <MessageDirection.back: 0>, limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None)[source]¶ Get room messages.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – room id of the room for which to download the messages
start (str) – The token to start returning events from.
end (str) – The token to stop returning events at.
direction (MessageDirection) – The direction to return events from.
limit (int) – The maximum number of events to return.
message_filter (Optional[Dict[Any, Any]]) – A filter dict that should be used for this room messages request.
-
static
room_put_state
(access_token, room_id, event_type, body, state_key='')[source]¶ Send a state event.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room where the event will be sent to.
event_type (str) – The type of the event that will be sent.
body (Dict) – The body of the event. The fields in this object will vary depending on the type of event.
state_key – The key of the state to look up. Defaults to an empty string.
-
static
room_read_markers
(access_token: str, room_id: str, fully_read_event: str, read_event: Optional[str] = None) → Tuple[str, str, str][source]¶ Update fully read marker and optionally read marker for a room.
This sets the position of the read marker for a given room, and optionally the read receipt’s location.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – Room id of the room where the read markers should be updated
fully_read_event (str) – The event ID the read marker should be located at.
read_event (Optional[str]) – The event ID to set the read receipt location at.
-
static
room_redact
(access_token, room_id, event_id, tx_id, reason=None)[source]¶ Strip information out of an event.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that contains the event that will be redacted.
event_id (str) – The ID of the event that will be redacted.
tx_id (str/UUID, optional) – A transaction ID for this event.
reason (str, optional) – A description explaining why the event was redacted.
-
static
room_resolve_alias
(room_alias: str) → Tuple[str, str][source]¶ Resolve a room alias to a room ID.
Returns the HTTP method and HTTP path for the request.
- Parameters
room_alias (str) – The alias to resolve
-
static
room_send
(access_token, 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: str, room_id: str, user_id: str, typing_state: bool = True, timeout: int = 30000) → Tuple[str, str, str][source]¶ Send a typing notice to the server.
This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – Room id of the room where the user is typing.
user_id (str) – The user who has started to type.
typing_state (bool) – A flag representing whether the user started or stopped typing
timeout (int) – For how long should the new typing notice be valid for in milliseconds.
-
static
room_unban
(access_token: str, room_id: str, user_id: str) → Tuple[str, str, str][source]¶ Unban a user from a room.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – The room id of the room that the user will be unbanned from.
user_id (str) – The user_id of the user that should be unbanned.
-
static
set_presence
(access_token: str, user_id: str, presence: str, status_msg: Optional[str] = None)[source]¶ This API sets the given user’s presence state.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_id (str) – User id whose presence state to get.
presence (str) – The new presence state.
status_msg (str, optional) – The status message to attach to this state.
-
static
sync
(access_token: str, since: Optional[str] = None, timeout: Optional[int] = None, filter: Union[None, str, Dict[Any, Any]] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None) → Tuple[str, str][source]¶ Synchronise the client’s state with the latest state on the server.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
since (str) – The room id of the room where the event will be sent to.
timeout (int) – The maximum time to wait, in milliseconds, before returning this request.
filter (Union[None, str, Dict[Any, Any]) – A filter ID or dict that should be used for this sync request.
full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter.
set_presence (str, optinal) – Controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to “offline” then the client is not marked as being online when it uses this API. When set to “unavailable”, the client is marked as being idle. One of: [“offline”, “online”, “unavailable”]
-
static
thumbnail
(server_name: str, media_id: str, width: int, height: int, method=<ResizingMethod.scale: 'scale'>, allow_remote: bool = True) → Tuple[str, str][source]¶ Get the thumbnail of a file from the content repository.
Returns the HTTP method and HTTP path for the request.
Note: The actual thumbnail may be larger than the size specified.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
width (int) – The desired width of the thumbnail.
height (int) – The desired height of the thumbnail.
method (ResizingMethod) – The desired resizing method.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
static
to_canonical_json
(content_dict: Dict[Any, Any]) → str[source]¶ Turn a dictionary into a canonical json string.
-
static
to_device
(access_token: str, event_type: str, content: Dict[Any, Any], tx_id: Union[str, UUID]) → Tuple[str, str, str][source]¶ Send to-device events to a set of client devices.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
event_type (str) – The type of the event which will be sent.
content (Dict) – The messages to send. A map from user ID, to a map from device ID to message body. The device ID may also be *, meaning all known devices for the user.
tx_id (str) – The transaction ID for this event.
-
static
update_device
(access_token: str, device_id: str, content: Dict[str, str]) → Tuple[str, str, str][source]¶ Update the metadata of the given device.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
device_id (str) – The device for which the metadata will be updated.
content (Dict) – A dictionary of metadata values that will be updated for the device.
-
static
update_receipt_marker
(access_token: str, room_id: str, event_id: str, receipt_type: str = 'm.read') → Tuple[str, str][source]¶ Update the marker of given receipt_type to specified event_id.
Returns the HTTP method and HTTP path for the request.
- Parameters
access_token (str) – The access token to be used with the request.
room_id (str) – Room id of the room where the marker should be updated
event_id (str) – The event ID the read marker should be located at
receipt_type (str) – The type of receipt to send. Currently, only m.read is supported by the Matrix specification.
-
static
upload
(access_token: str, filename: Optional[str] = None) → Tuple[str, str, str][source]¶ Upload a file’s content to the content repository.
Returns the HTTP method, HTTP path and empty data for the request. The real data should be read from the file that should be uploaded.
Note: This requests also requires the Content-Type http header to be set.
- Parameters
access_token (str) – The access token to be used with the request.
filename (str) – The name of the file being uploaded
-
static
upload_filter
(access_token: str, user_id: str, event_fields: Optional[List[str]] = None, event_format: nio.api.EventFormat = <EventFormat.client: 'client'>, presence: Optional[Dict[str, Any]] = None, account_data: Optional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = None) → Tuple[str, str, str][source]¶ Upload a new filter definition to the homeserver.
Returns the HTTP method, HTTP path and data for the request.
- Parameters
access_token (str) – The access token to be used with the request.
user_id (str) – ID of the user uploading the filter.
event_fields (Optional[List[str]]) – List of event fields to include. If this list is absent then all fields are included. The entries may include ‘.’ characters to indicate sub-fields. A literal ‘.’ character in a field name may be escaped using a ‘’.
event_format (EventFormat) – The format to use for events.
presence (Dict[str, Any]) – The presence updates to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
account_data (Dict[str, Any]) – The user account data that isn’t associated with rooms to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
room (Dict[str, Any]) – Filters to be applied to room data. The dict corresponds to the RoomFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
-
static
nio Clients¶
-
class
nio.
ClientConfig
(store: Optional[Type[nio.store.database.MatrixStore]] = <class 'nio.store.database.DefaultStore'>, encryption_enabled: bool = True, store_name: str = '', pickle_key: str = 'DEFAULT_KEY', store_sync_tokens: bool = False)[source]¶ nio client configuration.
-
store
¶ The store that should be used for state storage.
- Type
MatrixStore, optional
-
store_name
¶ Filename that should be used for the store.
- Type
str, optional
-
encryption_enabled
¶ Should end to end encryption be used.
- Type
bool, optional
-
pickle_key
¶ A passphrase that will be used to encrypt end to end encryption keys.
- Type
str, optional
-
store_sync_tokens
¶ Should the client store and restore sync tokens.
- Type
bool, optional
Raises an ImportWarning if encryption_enabled is true but the dependencies for encryption aren’t installed.
-
store
¶ alias of
nio.store.database.DefaultStore
-
Client¶
-
class
nio.
Client
(user: str, device_id: Optional[str] = None, store_path: Optional[str] = '', config: Optional[nio.client.base_client.ClientConfig] = None)[source]¶ Matrix no-IO client.
-
access_token
¶ Token authorizing the user with the server. Is set after logging in.
- Type
str
-
user_id
¶ The full mxid of the current user. This is set after logging in.
- Type
str
-
next_batch
¶ The current sync token.
- Type
str
-
rooms
¶ A dictionary containing a mapping of room ids to MatrixRoom objects. All the rooms a user is joined to will be here after a sync.
- Type
Dict[str, MatrixRoom)
-
invited_rooms
¶ A dictionary containing a mapping of room ids to MatrixInvitedRoom objects. All the rooms a user is invited to will be here after a sync.
- Type
Dict[str, MatrixInvitedRoom)
- Parameters
user (str) – User that will be used to log in.
device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.
store_dir (str, optional) – The directory that should be used for state storeage.
config (ClientConfig, optional) – Configuration for the client.
-
add_ephemeral_callback
(callback: Callable[[nio.rooms.MatrixRoom, nio.events.ephemeral.EphemeralEvent], None], filter: Union[Type[nio.events.ephemeral.EphemeralEvent], Tuple[Type[nio.events.ephemeral.EphemeralEvent], …]]) → None[source]¶ Add a callback that will be executed on ephemeral room events.
- Parameters
callback (Callable[MatrixRoom, EphemeralEvent]) – A function that will be called if the event type in the filter argument is found in the ephemeral room event list.
filter –
(Union[Type[EphemeralEvent] – The event type or a tuple containing multiple types for which the function will be called.
Tuple[Type[EphemeralEvent] – The event type or a tuple containing multiple types for which the function will be called.
..]]) – The event type or a tuple containing multiple types for which the function will be called.
-
add_event_callback
(callback: Callable[[nio.rooms.MatrixRoom, nio.events.room_events.Event], None], filter: Union[Type[nio.events.room_events.Event], Tuple[Type[nio.events.room_events.Event], …]]) → None[source]¶ Add a callback that will be executed on room events.
The callback can be used on joined rooms as well as on invited rooms. The room parameter for the callback will have a different type depending on if the room is joined or invited.
- Parameters
callback (Callable[[MatrixRoom, Event], None]) – A function that will be called if the event type in the filter argument is found in a room timeline.
filter (Union[Type[Event], Tuple[Type[Event], ..]]) – The event type or a tuple containing multiple types for which the function will be called.
-
add_presence_callback
(callback: Callable[[nio.events.presence.PresenceEvent], None], filter: Union[Type, Tuple[Type]])[source]¶ Add a callback that will be executed on presence events.
- Parameters
callback (Callable[[PresenceEvent], None]) – A function that will be called if the event type in the filter argument is found in a the presence part of the sync response.
filter (Union[Type, Tuple[Type]]) – The event type or a tuple containing multiple types for which the function will be called.
-
add_room_account_data_callback
(callback: Callable[[nio.rooms.MatrixRoom, nio.events.account_data.AccountDataEvent], None], filter: Union[Type[nio.events.account_data.AccountDataEvent], Tuple[Type[nio.events.account_data.AccountDataEvent], …]]) → None[source]¶ Add a callback that will be executed on room account data events.
- Parameters
callback (Callable[[MatrixRoom, ToDeviceEvent], None]) – A function that will be called if the event type in the filter argument is found in the room account data event list.
filter –
(Union[Type[AccountDataEvent] – The event type or a tuple containing multiple types for which the function will be called.
Tuple[Type[AccountDataEvent – The event type or a tuple containing multiple types for which the function will be called.
..]]) – The event type or a tuple containing multiple types for which the function will be called.
-
add_to_device_callback
(callback: Callable[[nio.events.to_device.ToDeviceEvent], None], filter: Union[Type[nio.events.to_device.ToDeviceEvent], Tuple[Type[nio.events.to_device.ToDeviceEvent], …]]) → None[source]¶ Add a callback that will be executed on to-device events.
- Parameters
callback (Callable[[ToDeviceEvent], None]) – A function that will be called if the event type in the filter argument is found in a the to-device part of the sync response.
filter –
(Union[Type[ToDeviceEvent] – The event type or a tuple containing multiple types for which the function will be called.
Tuple[Type[ToDeviceEvent] – The event type or a tuple containing multiple types for which the function will be called.
..]]) – The event type or a tuple containing multiple types for which the function will be called.
-
blacklist_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Mark a device as blacklisted.
Devices on the blacklist will not receive room encryption keys and therefore won’t be able to decrypt messages coming from this client.
- Parameters
device (OlmDevice) – The device which should be added to the blacklist.
Returns true if the device was added, false if it was on the blacklist already.
Cancel a previously interrupted key share event.
This method is the counterpart to the continue_key_share() method. If a user choses not to verify a device and does not want to share room keys with such a device it should cancel the request with this method.
>>> client.cancel_key_share(room_key_request)
- Parameters
event (RoomKeyRequest) – The event which we would like to cancel.
- Returns
True if the request was cancelled, False otherwise.
- Return type
bool
-
confirm_key_verification
(transaction_id: str) → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Confirm that the short auth string of a key verification matches.
- Parameters
transaction_id (str) – The transaction id of the interactive key verification.
Returns a
ToDeviceMessage
that should be sent to to the homeserver.If the other user already confirmed the short auth string on their side this function will also verify the device that is partaking in the verification process.
Continue a previously interrupted key share event.
To handle room key requests properly client users need to add a callback for RoomKeyRequest:
>>> client.add_to_device_callback(callback, RoomKeyRequest)
This callback will be run only if a room key request needs user interaction, that is if a room key request is coming from an untrusted device.
After a user has verified the requesting device the key sharing can be continued using this method:
>>> client.continue_key_share(room_key_request)
- Parameters
event (RoomKeyRequest) – The event which we would like to continue.
If the key share event is continued successfully a to-device message will be queued up in the client.outgoing_to_device_messages list waiting to be sent out
- Returns
True if the request was continued, False otherwise.
- Return type
bool
-
create_key_verification
(device: nio.crypto.device.OlmDevice) → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Start a new key verification process with the given device.
- Parameters
device (OlmDevice) – The device which we would like to verify
Returns a
ToDeviceMessage
that should be sent to to the homeserver.
-
decrypt_event
(event: nio.events.room_events.MegolmEvent) → Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Try to decrypt an undecrypted megolm event.
- Parameters
event (MegolmEvent) – Event that should be decrypted.
Returns the decrypted event, raises EncryptionError if there was an error while decrypting.
-
property
device_store
¶ Store containing known devices.
Returns a
DeviceStore
holding all known olm devices.
-
encrypt
(room_id: str, message_type: str, content: Dict[Any, Any]) → Tuple[str, Dict[str, str]][source]¶ Encrypt a message to be sent to the provided room.
- Parameters
room_id (str) – The room id of the room where the message will be sent.
message_type (str) – The type of the message.
content (str) – The dictionary containing the content of the message.
Raises GroupEncryptionError if the group session for the provided room isn’t shared yet.
Raises MembersSyncError if the room is encrypted but the room members aren’t fully loaded due to member lazy loading.
Returns a tuple containing the new message type and the new encrypted content.
-
export_keys
(outfile: str, passphrase: str, count: int = 10000)[source]¶ Export all the Megolm decryption keys of this device.
The keys will be encrypted using the passphrase.
Note that this does not save other information such as the private identity keys of the device.
- Parameters
outfile (str) – The file to write the keys to.
passphrase (str) – The encryption passphrase.
count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.
-
get_active_key_requests
(user_id: str, device_id: str) → List[nio.events.to_device.RoomKeyRequest][source]¶ Get key requests from a device that are waiting for verification.
- Parameters
user_id (str) – The id of the user for which we would like to find the active key requests.
device_id (str) – The id of the device for which we would like to find the active key requests.
Example
>>> # A to-device callback that verifies devices that >>> # request room keys and continues the room key sharing process. >>> # Note that a single user/device can have multiple key requests >>> # queued up. >>> def key_share_cb(event): ... user_id = event.sender ... device_id = event.requesting_device_id ... device = client.device_store[user_id][device_id] ... client.verify_device(device) ... for request in client.get_active_key_requests( ... user_id, device_id): ... client.continue_key_share(request) >>> client.add_to_device_callback(key_share_cb)
- Returns
A list of actively waiting key requests from the given user.
- Return type
list
-
get_active_sas
(user_id, device_id)[source]¶ Find a non-canceled SAS verification object for the provided user.
- Parameters
user_id (str) – The user for which we should find a SAS verification object.
device_id (str) – The device_id for which we should find the SAS verification object.
Returns the object if it’s found, otherwise None.
-
get_missing_sessions
(room_id: str) → Dict[str, List[str]][source]¶ Get users and devices for wich we don’t have active Olm sessions.
- Parameters
room_id (str) – The room id of the room for which we should get the users with missing Olm sessions.
- Raises LocalProtocolError if the room with the provided room id is
not found or the room is not encrypted.
-
get_users_for_key_claiming
() → Dict[str, List[str]][source]¶ Get the content for a key claim request that needs to be made.
Returns a dictionary containing users as the keys and a list of devices for which we will claim one-time keys.
Raises a LocalProtocolError if no key claim request needs to be made.
-
ignore_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Mark a device as ignored.
Ignored devices will still receive room encryption keys, despire not being verified.
- Parameters
device (OlmDevice) – the device to ignore
Returns true if device is ignored, or false if it is already on the list of ignored devices.
-
import_keys
(infile: str, passphrase: str)[source]¶ Import Megolm decryption keys.
The keys will be added to the current instance as well as written to database.
- Parameters
infile (str) – The file containing the keys.
passphrase (str) – The decryption passphrase.
- Raises EncryptionError if the file is invalid or couldn’t be
decrypted.
Raises the usual file errors if the file couldn’t be opened.
-
invalidate_outbound_session
(room_id: str)[source]¶ Explicitely remove encryption keys for a room.
- Parameters
room_id (str) – Room id for the room the encryption keys should be removed.
-
property
key_verifications
¶ Key verifications that the client is participating in.
-
load_store
()[source]¶ Load the session store and olm account.
If the SqliteMemoryStore is set as the store a store path isn’t required, if no store path is provided and a store class that requires a path is used this method will be a no op.
This method does nothing if the store is already loaded.
- Raises LocalProtocolError if a store class, user_id and device_id are
not set.
-
property
logged_in
¶ Check if we are logged in.
Returns True if the client is logged in to the server, False otherwise.
Check if the clients Olm account is shared with the server.
Returns True if the Olm account is shared, False otherwise.
-
property
outgoing_key_requests
¶ Our active key requests that we made.
-
property
outgoing_to_device_messages
¶ To-device messages that we need to send out.
-
receive_response
(response: nio.responses.Response) → Union[None, Coroutine[Any, Any, None]][source]¶ Receive a Matrix Response and change the client state accordingly.
Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible.
- Parameters
response (Response) – the response that we wish the client to handle
-
restore_login
(user_id: str, device_id: str, access_token: str)[source]¶ Restore a previous login to the homeserver.
- Parameters
user_id (str) – The full mxid of the current user.
device_id (str) – An unique identifier that distinguishes this client instance.
access_token (str) – Token authorizing the user with the server.
-
room_contains_unverified
(room_id: str) → bool[source]¶ Check if a room contains unverified devices.
- Parameters
room_id (str) – Room id of the room that should be checked.
Returns True if the room contains unverified devices, false otherwise. Returns False if no Olm session is loaded or if the room isn’t encrypted.
-
room_devices
(room_id: str) → Dict[str, Dict[str, nio.crypto.device.OlmDevice]][source]¶ Get all Olm devices participating in a room.
- Parameters
room_id (str) – The id of the room for which we would like to collect all the devices.
Returns a dictionary holding the user as the key and a dictionary of the device id as the key and OlmDevice as the value.
Raises LocalProtocolError if no room is found with the given room_id.
-
property
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.
-
property
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.
-
property
should_upload_keys
¶ Check if the client should upload encryption keys.
Returns True if encryption keys need to be uploaded, false otherwise.
-
unblacklist_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Unmark a device as blacklisted.
- Parameters
device (OlmDevice) – The device which should be removed from the blacklist.
Returns true if the device was removed, false if it wasn’t on the blacklist and no removal happened.
-
unignore_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Unmark a device as ignored.
- Parameters
device (OlmDevice) – The device which should be removed from the list of ignored devices.
Returns true if the device was removed, false if it wasn’t on the list and no removal happened.
-
unverify_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Unmark a device as verified.
This method removes the device from the trusted devices and disables sharing room encryption keys with it. It also invalidates any encryption keys for rooms that the device takes part of.
- Parameters
device (OlmDevice) – The device which should be added to the trust list.
Returns true if the device was unverified, false if it was already unverified.
-
property
users_for_key_query
¶ Users for whom we should make a key query.
-
verify_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Mark a device as verified.
A device needs to be either trusted/ignored or blacklisted to either share room encryption keys with it or not. This method adds the device to the trusted devices and enables sharing room encryption keys with it.
- Parameters
device (OlmDevice) – The device which should be added to the trust list.
Returns true if the device was verified, false if it was already verified.
-
AsyncClient¶
-
class
nio.
AsyncClient
(homeserver: str, user: str = '', device_id: Optional[str] = '', store_path: Optional[str] = '', config: Optional[nio.client.async_client.AsyncClientConfig] = None, ssl: Optional[bool] = None, proxy: Optional[str] = None)[source]¶ Bases:
nio.client.base_client.Client
An async IO matrix client.
- Parameters
homeserver (str) – The URL of the homeserver which we want to connect to.
user (str, optional) – The user which will be used when we log in to the homeserver.
device_id (str, optional) – An unique identifier that distinguishes this client instance. If not set the server will provide one after log in.
store_path (str, optional) – The directory that should be used for state storage.
config (AsyncClientConfig, optional) – Configuration for the client.
ssl (bool/ssl.SSLContext, optional) – SSL validation mode. None for default SSL check (ssl.create_default_context() is used), False for skip SSL certificate validation connection.
proxy (str, optional) – The proxy that should be used for the HTTP connection.
-
synced
¶ An asyncio event that is fired every time the client successfully syncs with the server. Note, this event will only be fired if the sync_forever() method is used.
- Type
A simple example can be found bellow.
Example
>>> client = AsyncClient("https://example.org", "example") >>> login_response = loop.run_until_complete( >>> client.login("hunter1") >>> ) >>> asyncio.run(client.sync_forever(30000))
This example assumes a full sync on every run. If a sync token is provided for the since parameter of the sync_forever method full_state should be set to True as well.
Example
>>> asyncio.run( >>> client.sync_forever(30000, since="token123", >>> full_state=True) >>> )
The client can also be configured to store and restore the sync token automatically. The full_state argument should be set to True in that case as well.
Example
>>> config = ClientConfig(store_sync_tokens=True) >>> client = AsyncClient("https://example.org", "example", >>> store_path="/home/example", >>> config=config) >>> login_response = loop.run_until_complete( >>> client.login("hunter1") >>> ) >>> asyncio.run(client.sync_forever(30000, full_state=True))
-
accept_key_verification
(transaction_id: str, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError][source]¶ Accept a key verification start event.
Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
-
add_response_callback
(func: Coroutine[Any, Any, nio.responses.Response], cb_filter: Optional[Union[Tuple[Type], Type]] = None)[source]¶ Add a coroutine that will be called if a response is received.
- Parameters
func (Coroutine) – The coroutine that will be called with the response as the argument.
cb_filter (Type, optional) – A type or a tuple of types for which the callback should be called.
Example
>>> # A callback that will be called every time our `sync_forever` >>> # method succesfully syncs with the server. >>> async def sync_cb(response): ... print(f"We synced, token: {response.next_batch}") ... >>> client.add_response_callback(sync_cb, SyncResponse) >>> await client.sync_forever(30000)
-
cancel_key_verification
(transaction_id: str, reject: bool = False, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError][source]¶ Cancel a interactive key verification with the given device.
Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
reject (bool) – Is the cancelation reason because we’re rejecting the short auth string and mark it as mismatching or a normal user cancelation.
Raises a LocalProtocolError no verification process with the given transaction ID exists or if reject is True and the short auth string couldn’t be shown yet because plublic keys weren’t yet exchanged.
-
confirm_short_auth_string
(transaction_id: str, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError][source]¶ Confirm a short auth string and mark it as matching.
Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
-
content_repository_config
() → Union[nio.responses.ContentRepositoryConfigResponse, nio.responses.ContentRepositoryConfigError][source]¶ Get the content repository configuration, such as upload limits.
Calls receive_response() to update the client state if necessary.
Returns either a ContentRepositoryConfigResponse if the request was successful or a ContentRepositoryConfigError if there was an error with the request.
-
async
create_matrix_response
(response_class: Type, transport_response: aiohttp.client_reqrep.ClientResponse, data: Optional[Tuple[Any, …]] = None) → nio.responses.Response[source]¶ Transform a transport response into a nio matrix response.
Low-level function which is normally only used by other methods of this class.
- Parameters
response_class (Type) – The class that the requests belongs to.
transport_response (ClientResponse) – The underlying transport response that contains our response body.
data (Tuple, optional) – Extra data that is required to instantiate the response class.
Returns a subclass of Response depending on the type of the response_class argument.
-
delete_devices
(devices: List[str], auth: Optional[Dict[str, str]] = None) → Union[nio.responses.DeleteDevicesResponse, nio.responses.DeleteDevicesError][source]¶ Delete a list of devices.
This tells the server to delete the given devices and invalidate their associated access tokens.
Calls receive_response() to update the client state if necessary.
Returns either a DeleteDevicesResponse if the request was successful or a DeleteDevicesError if there was an error with the request.
This endpoint supports user-interactive auth, calling this method without an auth dictionary will return a DeleteDevicesAuthResponse which can be used to introspect the valid authentication methods that the server supports.
- Parameters
devices (List[str]) – A list of devices which will be deleted.
auth (Dict) – Additional authentication information for the user-interactive authentication API.
Example
>>> devices = ["QBUAZIFURK", "AUIECTSRND"] >>> auth = {"type": "m.login.password", ... "user": "example", ... "password": "hunter1"} >>> await client.delete_devices(devices, auth)
-
devices
() → Union[nio.responses.DevicesResponse, nio.responses.DevicesError][source]¶ Get the list of devices for the current user.
Calls receive_response() to update the client state if necessary.
Returns either a DevicesResponse if the request was successful or a DevicesError if there was an error with the request.
-
async
discovery_info
() → Union[nio.responses.DiscoveryInfoResponse, nio.responses.DiscoveryInfoError][source]¶ Get discovery information about current AsyncClient.homeserver.
Returns either a DiscoveryInfoResponse if the request was successful or a DiscoveryInfoError if there was an error with the request.
Some homeservers do not redirect requests to their main domain and instead require clients to use a specific URL for communication.
If the domain specified by the AsyncClient.homeserver URL implements the [.well-known](https://matrix.org/docs/spec/client_server/latest#id178), discovery mechanism, this method can be used to retrieve the actual homeserver URL from it.
Example
>>> client = AsyncClient(homeserver="https://example.org") >>> response = await client.discovery_info() >>> if isinstance(response, DiscoveryInfoResponse): >>> client.homeserver = response.homeserver_url
-
async
download
(server_name: str, media_id: str, filename: Optional[str] = None, allow_remote: bool = True) → Union[nio.responses.DownloadResponse, nio.responses.DownloadError][source]¶ Get the content of a file from the content repository.
This method ignores AsyncClient.config.request_timeout and uses 0.
Calls receive_response() to update the client state if necessary.
Returns either a DownloadResponse if the request was successful or a DownloadError if there was an error with the request.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
export_keys
(outfile: str, passphrase: str, count: int = 10000)[source]¶ Export all the Megolm decryption keys of this device.
The keys will be encrypted using the passphrase.
Note that this does not save other information such as the private identity keys of the device.
- Parameters
outfile (str) – The file to write the keys to.
passphrase (str) – The encryption passphrase.
count (int) – Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences.
-
async
get_avatar
(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetAvatarResponse, nio.responses.ProfileGetAvatarError][source]¶ Get a user’s avatar URL.
This queries the avatar matrix content URI of a user from the server. The currently logged in user is queried if no user is specified.
Calls receive_response() to update the client state if necessary.
Returns either a ProfileGetAvatarResponse if the request was successful or a ProfileGetAvatarError if there was an error with the request.
- Parameters
user_id (str) – User id of the user to get the avatar for.
-
async
get_displayname
(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetDisplayNameResponse, nio.responses.ProfileGetDisplayNameError][source]¶ Get a user’s display name.
This queries the display name of a user from the server. The currently logged in user is queried if no user is specified.
Calls receive_response() to update the client state if necessary.
Returns either a ProfileGetDisplayNameResponse if the request was successful or a ProfileGetDisplayNameError if there was an error with the request.
- Parameters
user_id (str) – User id of the user to get the display name for.
-
async
get_presence
(user_id: str) → Union[nio.responses.PresenceGetResponse, nio.responses.PresenceGetError][source]¶ Get a user’s presence state.
This queries the presence state of a user from the server.
Calls receive_response() to update the client state if necessary.
Returns either a PresenceGetResponse if the request was successful or a PresenceGetError if there was an error with the request.
- Parameters
user_id (str) – User id of the user to get the presence state for.
-
async
get_profile
(user_id: Optional[str] = None) → Union[nio.responses.ProfileGetResponse, nio.responses.ProfileGetError][source]¶ Get a user’s combined profile information.
This queries the display name and avatar matrix content URI of a user from the server. Additional profile information may be present. The currently logged in user is queried if no user is specified.
Calls receive_response() to update the client state if necessary.
Returns either a ProfileGetResponse if the request was successful or a ProfileGetError if there was an error with the request.
- Parameters
user_id (str) – User id of the user to get the profile for.
-
import_keys
(infile: str, passphrase: str)[source]¶ Import Megolm decryption keys.
The keys will be added to the current instance as well as written to database.
- Parameters
infile (str) – The file containing the keys.
passphrase (str) – The decryption passphrase.
- Raises EncryptionError if the file is invalid or couldn’t be
decrypted.
Raises the usual file errors if the file couldn’t be opened.
-
join
(room_id: str) → Union[nio.responses.JoinResponse, nio.responses.JoinError][source]¶ Join a room.
This tells the server to join the given room. If the room is not public, the user must be invited.
Calls receive_response() to update the client state if necessary.
Returns either a JoinResponse if the request was successful or a JoinError if there was an error with the request.
- Parameters
room_id – The room id or alias of the room to join.
-
joined_members
(room_id: str) → Union[nio.responses.JoinedMembersResponse, nio.responses.JoinedMembersError][source]¶ Get the list of joined members for a room.
Calls receive_response() to update the client state if necessary.
Returns either a JoinedMembersResponse if the request was successful or a JoinedMembersError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room for which we wan’t to request the joined member list.
-
joined_rooms
() → Union[nio.responses.JoinedRoomsResponse, nio.responses.JoinedRoomsError][source]¶ Get the list of joined rooms.
Calls receive_response() to update the client state if necessary.
Returns either a JoinedRoomsResponse if the request was successful or a JoinedRoomsError if there was an error with the request.
-
keys_claim
(user_set: Dict[str, Iterable[str]]) → Union[nio.responses.KeysClaimResponse, nio.responses.KeysClaimError][source]¶ Claim one-time keys for a set of user and device pairs.
Automatically called by sync_forever() and room_send().
Calls receive_response() to update the client state if necessary.
- Parameters
user_set (Dict[str, Iterator[str]]) – A dictionary maping from a user id to a iterator of device ids. If a user set for a specific room is required it can be obtained using the get_missing_sessions() method.
Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists or the room isn’t an encrypted room.
-
keys_query
() → Union[nio.responses.KeysQueryResponse, nio.responses.KeysQueryError][source]¶ Query the server for user keys.
This queries the server for device keys of users with which we share an encrypted room.
Automatically called by sync_forever() and room_send().
Calls receive_response() to update the client state if necessary.
Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded or if no key query needs to be performed.
-
keys_upload
() → Union[nio.responses.KeysUploadResponse, nio.responses.KeysUploadError][source]¶ Upload the E2E encryption keys.
This uploads the long lived session keys as well as the required amount of one-time keys.
Automatically called by sync_forever().
Calls receive_response() to update the client state if necessary.
Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded or if no encryption keys need to be uploaded.
-
async
login
(password: Optional[str] = None, device_name: Optional[str] = '', token: Optional[str] = None) → Union[nio.responses.LoginResponse, nio.responses.LoginError][source]¶ Login to the homeserver.
Calls receive_response() to update the client state if necessary.
- Parameters
password (str, optional) – The user’s password.
device_name (str) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.
token (str, optional) – A login token, for example provided by a single sign-on service.
Either a password or a token needs to be provided.
Returns either a LoginResponse if the request was successful or a LoginError if there was an error with the request.
-
async
login_info
() → Union[nio.responses.LoginInfoResponse, nio.responses.LoginInfoError][source]¶ Get the available login methods from the server
Returns either a LoginInfoResponse if the request was successful or a LoginInfoError if there was an error with the request.
-
async
login_raw
(auth_dict: Dict[str, Any]) → Union[nio.responses.LoginResponse, nio.responses.LoginError][source]¶ Login to the homeserver using a raw dictionary.
Calls receive_response() to update the client state if necessary.
- Parameters
auth_dict (Dict[str, Any]) –
The auth dictionary. See the example below and here
for detailed documentation
Example
>>> auth_dict = { >>> "type": "m.login.password", >>> "identifier": { >>> "type": "m.id.thirdparty", >>> "medium": "email", >>> "address": "testemail@mail.org" >>> }, >>> "password": "PASSWORDABCD", >>> "initial_device_display_name": "Test user" >>> }
Returns either a LoginResponse if the request was successful or a LoginError if there was an error with the request.
-
logout
(all_devices: bool = False) → Union[nio.responses.LogoutResponse, nio.responses.LogoutError][source]¶ Logout from the homeserver.
Calls receive_response() to update the client state if necessary.
Returns either ‘LogoutResponse’ if the request was successful or a Logouterror if there was an error with the request.
-
async
mxc_to_http
(mxc: str, homeserver: Optional[str] = None) → Optional[str][source]¶ Convert a matrix content URI to a HTTP URI.
-
async
parse_body
(transport_response: aiohttp.client_reqrep.ClientResponse) → Dict[Any, Any][source]¶ Parse the body of the response.
Low-level function which is normally only used by other methods of this class.
- Parameters
transport_response (ClientResponse) – The transport response that contains the body of the response.
Returns a dictionary representing the response.
-
async
receive_response
(response: nio.responses.Response) → None[source]¶ Receive a Matrix Response and change the client state accordingly.
Automatically called for all “high-level” methods of this API (each function documents calling it).
Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible.
- Parameters
response (Response) – the response that we wish the client to handle
-
async
register
(username, password, device_name='')[source]¶ Register with homeserver.
Calls receive_response() to update the client state if necessary.
- Parameters
username (str) – Username to register the new user as.
password (str) – New password for the user.
device_name (str) – A display name to assign to a newly-created device. Ignored if the logged in device corresponds to a known device.
Returns a ‘RegisterResponse’ if successful.
-
request_room_key
(event: nio.events.room_events.MegolmEvent, tx_id: Optional[str] = None) → Union[nio.responses.RoomKeyRequestResponse, nio.responses.RoomKeyRequestError][source]¶ Request a missing room key.
This sends out a message to other devices requesting a room key from them.
Calls receive_response() to update the client state if necessary.
Returns either a RoomKeyRequestResponse if the request was successful or a RoomKeyRequestError if there was an error with the request.
Raises a LocalProtocolError if the room key was already requested.
- Parameters
event (MegolmEvent) – An undecrypted MegolmEvent for which we would like to request the decryption key.
-
room_ban
(room_id: str, user_id: str, reason: Optional[str] = None) → Union[nio.responses.RoomBanResponse, nio.responses.RoomBanError][source]¶ Ban a user from a room.
When a user is banned from a room, they may not join it or be invited to it until they are unbanned. If they are currently in the room, they will be kicked or have their invitation withdrawn first.
Calls receive_response() to update the client state if necessary.
Returns either a RoomBanResponse if the request was successful or a RoomBanError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that the user will be banned from.
user_id (str) – The user_id of the user that should be banned.
reason (str, optional) – A reason for which the user is banned.
-
room_context
(room_id: str, event_id: str, limit: Optional[int] = None) → Union[nio.responses.RoomContextResponse, nio.responses.RoomContextError][source]¶ Fetch a number of events that happened before and after an event.
This allows clients to get the context surrounding an event.
Calls receive_response() to update the client state if necessary.
Returns either a RoomContextResponse if the request was successful or a RoomContextError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that contains the event and its context.
event_id (str) – The event_id of the event that we wish to get the context for.
limit (int, optional) – The maximum number of events to request.
-
room_create
(visibility: nio.api.RoomVisibility = <RoomVisibility.private: 'private'>, alias: Optional[str] = None, name: Optional[str] = None, topic: Optional[str] = None, room_version: Optional[str] = None, federate: bool = True, is_direct: bool = False, preset: Optional[nio.api.RoomPreset] = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Optional[Dict[str, Any]] = None) → Union[nio.responses.RoomCreateResponse, nio.responses.RoomCreateError][source]¶ Create a new room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomCreateResponse if the request was successful or a RoomCreateError if there was an error with the request.
- Parameters
visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to
RoomVisibility.private
.alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.
name (str, optional) – A name to set for the room.
topic (str, optional) – A topic to set for the room.
room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400
M_UNSUPPORTED_ROOM_VERSION
error will be returned.federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to
True
. Cannot be changed later.is_direct (bool) – If this should be considered a direct messaging room. If
True
, the server will set theis_direct
flag onm.room.member events
sent to the users ininvite
. Defaults toFalse
.preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the
visibility
:RoomVisibility.public
equates toRoomPreset.public_chat
, andRoomVisibility.private
equates to aRoomPreset.private_chat
.invite (list) – A list of user id to invite to the room.
initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediatly by having a
m.room.encryption
event dict.power_level_override (dict) – A
m.room.power_levels content
dict to override the default. The dict will be applied on top of the generatedm.room.power_levels
event before it is sent to the room.
-
room_forget
(room_id: str) → Union[nio.responses.RoomForgetResponse, nio.responses.RoomForgetError][source]¶ Forget a room.
This tells the server to forget the given room’s history for our user. If all users on a homeserver forget the room, the room will be eligible for deletion from that homeserver.
Calls receive_response() to update the client state if necessary.
Returns either a RoomForgetResponse if the request was successful or a RoomForgetError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room to forget.
-
room_get_event
(room_id: str, event_id: str) → Union[nio.responses.RoomGetEventResponse, nio.responses.RoomGetEventError][source]¶ Get a single event based on roomId/eventId.
Calls receive_response() to update the client state if necessary.
Returns either a RoomGetEventResponse if the request was successful or a RoomGetEventError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room where the event is in.
event_id (str) – The event id to get.
-
room_get_state
(room_id: str) → Union[nio.responses.RoomGetStateResponse, nio.responses.RoomGetStateError][source]¶ Fetch state for a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomGetStateResponse if the request was successful or a RoomGetStateError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room to fetch state from.
-
room_get_state_event
(room_id: str, event_type: str, state_key: str = '') → Union[nio.responses.RoomGetStateEventResponse, nio.responses.RoomGetStateEventError][source]¶ Fetch a state event from a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomGetStateEventResponse if the request was successful or a RoomGetStateEventError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room to fetch the event from.
event_type (str) – The type of the state to fetch.
state_key (str) – The key of the state event to fetch.
-
room_invite
(room_id: str, user_id: str) → Union[nio.responses.RoomInviteResponse, nio.responses.RoomInviteError][source]¶ Invite a user to a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomInviteResponse if the request was successful or a RoomInviteError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that the user will be invited to.
user_id (str) – The user id of the user that should be invited.
-
room_kick
(room_id: str, user_id: str, reason: Optional[str] = None) → Union[nio.responses.RoomKickResponse, nio.responses.RoomKickError][source]¶ Kick a user from a room, or withdraw their invitation.
Kicking a user adjusts their membership to “leave” with an optional reason.
Calls receive_response() to update the client state if necessary.
Returns either a RoomKickResponse if the request was successful or a RoomKickError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that the user will be kicked from.
user_id (str) – The user_id of the user that should be kicked.
reason (str, optional) – A reason for which the user is kicked.
-
room_leave
(room_id: str) → Union[nio.responses.RoomLeaveResponse, nio.responses.RoomLeaveError][source]¶ Leave a room or reject an invite.
This tells the server to leave the given room. If the user was only invited, the invite is rejected.
Calls receive_response() to update the client state if necessary.
Returns either a RoomLeaveResponse if the request was successful or a RoomLeaveError if there was an error with the request.
- Parameters
room_id – The room id of the room to leave.
-
room_messages
(room_id: str, start: str, end: Optional[str] = None, direction: nio.api.MessageDirection = <MessageDirection.back: 0>, limit: int = 10, message_filter: Optional[Dict[Any, Any]] = None) → Union[nio.responses.RoomMessagesResponse, nio.responses.RoomMessagesError][source]¶ Fetch a list of message and state events for a room.
It uses pagination query parameters to paginate history in the room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomMessagesResponse if the request was successful or a RoomMessagesResponse if there was an error with the request.
- Parameters
room_id (str) – The room id of the room for which we would like to fetch the messages.
start (str) – The token to start returning events from. This token can be obtained from a prev_batch token returned for each room by the sync API, or from a start or end token returned by a previous request to this endpoint.
end (str, optional) – The token to stop returning events at. This token can be obtained from a prev_batch token returned for each room by the sync endpoint, or from a start or end token returned by a previous request to this endpoint.
direction (MessageDirection, optional) – The direction to return events from. Defaults to MessageDirection.back.
limit (int, optional) – The maximum number of events to return. Defaults to 10.
message_filter (Optional[Dict[Any, Any]]) – A filter dict that should be used for this room messages request.
Example
>>> response = await client.room_messages(room_id, previous_batch) >>> next_response = await client.room_messages(room_id, ... response.end)
-
room_put_state
(room_id: str, event_type: str, content: Dict[Any, Any], state_key: str = '') → Union[nio.responses.RoomPutStateResponse, nio.responses.RoomPutStateError][source]¶ Send a state event to a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomPutStateResponse if the request was successful or a RoomPutStateError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room to send the event to.
event_type (str) – The type of the state to send.
content (Dict[Any, Any]) – The content of the event to be sent.
state_key (str) – The key of the state event to send.
-
room_read_markers
(room_id: str, fully_read_event: str, read_event: Optional[str] = None)[source]¶ Update the fully read marker (and optionally the read receipt) for a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomReadMarkersResponse if the request was successful or a RoomReadMarkersError if there was an error with the request.
This sets the position of the read markers.
fully_read_event is the latest event in the set of events that the user has either fully read or indicated they aren’t interested in. It permits the implementation of a “jump to first unread message” kind of feature. It is _private_ (not exposed to other room participants).
read_event is the most recent message the user has read and is also known as a _read receipt_. A read receipt being set on an event does not imply that all previous events have been seen. This happens in cases such as when a user comes back to a room after hundreds of messages have been sent and _only_ reads the most recent message. The read receipt is _public_ (exposed to other room participants).
If you want to set the read receipt, you _must_ set read_event.
- Parameters
room_id (str) – The room ID of the room where the read markers should be updated.
fully_read_event (str) – The event ID that the user has fully read up to.
read_event (Optional[str]) – The event ID to set the read receipt location at.
-
room_redact
(room_id: str, event_id: str, reason: Optional[str] = None, tx_id: Union[None, str, uuid.UUID] = None) → Union[nio.responses.RoomRedactResponse, nio.responses.RoomRedactError][source]¶ Strip information out of an event.
Calls receive_response() to update the client state if necessary.
Returns either a RoomRedactResponse if the request was successful or a RoomRedactError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that contains the event that will be redacted.
event_id (str) – The ID of the event that will be redacted.
tx_id (str/UUID, optional) – A transaction ID for this event.
reason (str, optional) – A description explaining why the event was redacted.
-
async
room_resolve_alias
(room_alias: str) → Union[nio.responses.RoomResolveAliasResponse, nio.responses.RoomResolveAliasError][source]¶ Resolve a room alias to a room ID.
Calls receive_response() to update the client state if necessary.
Returns either a RoomResolveAliasResponse if the request was successful or a `RoomResolveAliasError if there was an error with the request.
- Parameters
room_alias (str) – The alias to resolve
-
room_send
(room_id: str, message_type: str, content: Dict[Any, Any], tx_id: Optional[str] = None, ignore_unverified_devices: bool = False)[source]¶ Send a message to a room.
Calls receive_response() to update the client state if necessary.
- Parameters
room_id (str) – The room id of the room where the message should be sent to.
message_type (str) – A string identifying the type of the message.
content (Dict[Any, Any]) – A dictionary containing the content of the message.
tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.
ignore_unverified_devices (bool) – If the room is encrypted and contains unverified devices, the devices can be marked as ignored here. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.
If the room where the message should be sent is encrypted the message will be encrypted before sending.
This method also makes sure that the room members are fully synced and that keys are queried before sending messages to an encrypted room.
If the method can’t sync the state fully to send out an encrypted message after a couple of retries it raises SendRetryError.
Raises LocalProtocolError if the client isn’t logged in.
-
room_typing
(room_id: str, typing_state: bool = True, timeout: int = 30000) → Union[nio.responses.RoomTypingResponse, nio.responses.RoomTypingError][source]¶ Send a typing notice to the server.
This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.
Calls receive_response() to update the client state if necessary.
Returns either a RoomTypingResponse if the request was successful or a RoomTypingError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room where the user is typing.
typing_state (bool) – A flag representing whether the user started or stopped typing.
timeout (int) – For how long should the new typing notice be valid for in milliseconds.
-
room_unban
(room_id: str, user_id: str) → Union[nio.responses.RoomBanResponse, nio.responses.RoomBanError][source]¶ Unban a user from a room.
This allows them to be invited and join the room again.
Calls receive_response() to update the client state if necessary.
Returns either a RoomUnbanResponse if the request was successful or a RoomUnbanError if there was an error with the request.
- Parameters
room_id (str) – The room id of the room that the user will be unbanned from.
user_id (str) – The user_id of the user that should be unbanned.
-
async
run_response_callbacks
(responses: List[Union[nio.responses.Response, nio.responses.ErrorResponse]])[source]¶ Run the configured response callbacks for the given responses.
Low-level function which is normally only used by other methods of this class. Automatically called by sync_forever() and all functions calling receive_response().
-
async
send
(method: str, path: str, data: Union[None, str, pathlib.Path, bytes, Iterable[bytes], AsyncIterable[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None) → aiohttp.client_reqrep.ClientResponse[source]¶ Send a request to the homeserver.
This function does not call receive_response().
- Parameters
method (str) – The request method that should be used. One of get, post, put, delete.
path (str) – The URL path of the request.
data (str, optional) – Data that will be posted with the request.
headers (Dict[str,str] , optional) – Additional request headers that should be used with the request.
trace_context (Any, optional) – An object to use for the ClientSession TraceConfig context
timeout (int, optional) – How many seconds the request has before raising asyncio.TimeoutError. Overrides AsyncClient.config.request_timeout if not None.
-
send_to_device_messages
() → List[Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError]][source]¶ Send out outgoing to-device messages.
Automatically called by sync_forever().
-
set_avatar
(avatar_url: str) → Union[nio.responses.ProfileSetAvatarResponse, nio.responses.ProfileSetAvatarError][source]¶ Set the user’s avatar URL.
This tells the server to set the avatar of the currently logged in user to supplied matrix content URI.
Calls receive_response() to update the client state if necessary.
Returns either a ProfileSetAvatarResponse if the request was successful or a ProfileSetAvatarError if there was an error with the request.
- Parameters
avatar_url (str) – matrix content URI of the avatar to set.
-
set_displayname
(displayname: str) → Union[nio.responses.ProfileSetDisplayNameResponse, nio.responses.ProfileSetDisplayNameError][source]¶ Set user’s display name.
This tells the server to set display name of the currently logged in user to the supplied string.
Calls receive_response() to update the client state if necessary.
Returns either a ProfileSetDisplayNameResponse if the request was successful or a ProfileSetDisplayNameError if there was an error with the request.
- Parameters
displayname (str) – Display name to set.
-
async
set_presence
(presence: str, status_msg: str = None) → Union[nio.responses.PresenceSetResponse, nio.responses.PresenceSetError][source]¶ Set our user’s presence state.
This tells the server to set presence state of the currently logged in user to the supplied string.
Calls receive_response() to update the client state if necessary.
Returns either a PresenceSetResponse if the request was successful or a PresenceSetError if there was an error with the request.
- Parameters
presence (str) – The new presence state. One of: [“online”, “offline”, “unavailable”]
status_msg (str, optional) – The status message to attach to this state.
Share a group session with a room.
This method sends a group session to members of a room.
Automatically called by room_send().
Calls receive_response() to update the client state if necessary.
- Parameters
room_id (str) – The room id of the room where the message should be sent to.
ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.
Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists, the room isn’t an encrypted room or a key sharing request is already in flight for this room.
-
start_key_verification
(device: nio.crypto.device.OlmDevice, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError][source]¶ Start a interactive key verification with the given device.
Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.
- Parameters
device (OlmDevice) – An device with which we would like to start the interactive key verification process.
-
sync
(timeout: Optional[int] = 0, sync_filter: Union[None, str, Dict[Any, Any]] = None, since: Optional[str] = None, full_state: Optional[bool] = None, set_presence: Optional[str] = None) → Union[nio.responses.SyncResponse, nio.responses.SyncError][source]¶ Synchronise the client’s state with the latest state on the server.
In general you should use sync_forever() which handles additional tasks automatically (like sending encryption keys among others).
Calls receive_response() to update the client state if necessary.
- Parameters
timeout (int, optional) – The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If
0
, no timeout is applied. IfNone
, useAsyncClient.config.request_timeout
. If a timeout is applied and the server fails to return after 15 seconds of expected timeout, the client will timeout by itself.sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from
AsyncClient.upload_filter()
(preferred), or filter dict that should be used for this sync request.full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter.
since (str, optional) – A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call.
set_presence (str, optional) – The presence state. One of: [“online”, “offline”, “unavailable”]
Returns either a SyncResponse if the request was successful or a SyncError if there was an error with the request.
-
sync_forever
(timeout: Optional[int] = None, sync_filter: Union[None, str, Dict[Any, Any]] = None, since: Optional[str] = None, full_state: Optional[bool] = None, loop_sleep_time: Optional[int] = None, first_sync_filter: Union[None, str, Dict[Any, Any]] = None, set_presence: Optional[str] = None)[source]¶ Continuously sync with the configured homeserver.
This method calls the sync method in a loop. To react to events event callbacks should be configured.
The loop also makes sure to handle other required requests between syncs, including to_device messages and sending encryption keys if required. To react to the responses a response callback should be added.
- Parameters
timeout (int, optional) – The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If
0
, no timeout is applied. IfNone
,AsyncClient.config.request_timeout
is used. In any case,0
is always used for the first sync. If a timeout is applied and the server fails to return after 15 seconds of expected timeout, the client will timeout by itself.sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from
AsyncClient.upload_filter()
(preferred), or filter dict that should be used for sync requests.full_state (bool, optional) – Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter. This argument will be used only for the first sync request.
since (str, optional) – A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call. This argument will be used only for the first sync request, the subsequent sync requests will use the token from the last sync response.
loop_sleep_time (int, optional) – The sleep time, if any, between successful sync loop iterations in milliseconds.
first_sync_filter (Union[None, str, Dict[Any, Any]) – A filter ID that can be obtained from
AsyncClient.upload_filter()
(preferred), or filter dict to use for the first sync request only. If None (default), the sync_filter parameter’s value is used. To have no filtering for the first sync regardless of sync_filter’s value, pass {}.set_presence (str, optional) – The presence state. One of: [“online”, “offline”, “unavailable”]
-
async
thumbnail
(server_name: str, media_id: str, width: int, height: int, method: nio.api.ResizingMethod = <ResizingMethod.scale: 'scale'>, allow_remote: bool = True) → Union[nio.responses.ThumbnailResponse, nio.responses.ThumbnailError][source]¶ Get the thumbnail of a file from the content repository.
The actual thumbnail may be larger than the size specified. This method ignores AsyncClient.config.request_timeout and uses 0.
Calls receive_response() to update the client state if necessary.
Returns either a ThumbnailResponse if the request was successful or a ThumbnailError if there was an error with the request.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
width (int) – The desired width of the thumbnail.
height (int) – The desired height of the thumbnail.
method (ResizingMethod) – The desired resizing method.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
to_device
(message: nio.event_builders.direct_messages.ToDeviceMessage, tx_id: Optional[str] = None) → Union[nio.responses.ToDeviceResponse, nio.responses.ToDeviceError][source]¶ Send a to-device message.
Calls receive_response() to update the client state if necessary.
Returns either a ToDeviceResponse if the request was successful or a ToDeviceError if there was an error with the request.
- Parameters
message (ToDeviceMessage) – The message that should be sent out.
tx_id (str, optional) – The transaction ID for this message. Should be unique.
-
update_device
(device_id: str, content: Dict[str, str]) → Union[nio.responses.UpdateDeviceResponse, nio.responses.UpdateDeviceError][source]¶ Update the metadata of the given device.
Returns either a UpdateDeviceResponse if the request was successful or a UpdateDeviceError if there was an error with the request.
- Parameters
device_id (str) – The device for which the metadata will be updated.
content (Dict[str, str]) – A dictionary of metadata values that will be updated for the device.
Example
>>> device_id = "QBUAZIFURK" >>> content = {"display_name": "My new device"} >>> await client.update_device(device_id, content)
-
update_receipt_marker
(room_id: str, event_id: str, receipt_type: str = 'm.read') → None[source]¶ Update the marker of given the receipt_type to specified event_id.
Calls receive_response() to update the client state if necessary.
Returns either a UpdateReceiptMarkerResponse if the request was successful or a UpdateReceiptMarkerError if there was an error with the request.
- Parameters
room_id (str) – Room id of the room where the marker should be updated
event_id (str) – The event ID the read marker should be located at
receipt_type (str) – The type of receipt to send. Currently, only m.read is supported by the Matrix specification.
-
upload
(data_provider: Callable[[int, int], Union[str, pathlib.Path, bytes, Iterable[bytes], AsyncIterable[bytes], io.BufferedIOBase, aiofiles.threadpool.binary.AsyncBufferedReader]], content_type: str = 'application/octet-stream', filename: Optional[str] = None, encrypt: bool = False, monitor: Optional[nio.monitors.TransferMonitor] = None, filesize: Optional[int] = None) → Tuple[Union[nio.responses.UploadResponse, nio.responses.UploadError], Optional[Dict[str, Any]]][source]¶ Upload a file to the content repository.
This method ignores AsyncClient.config.request_timeout and uses 0.
Calls receive_response() to update the client state if necessary.
Returns a tuple containing:
Either a UploadResponse if the request was successful, or a UploadError if there was an error with the request
A dict with file decryption info if encrypt is
True
, elseNone
.
Raises a
TransferCancelledError
if a monitor is passed and itscancelled
property becomes set toTrue
.- Parameters
data_provider (Callable, SynchronousFile, AsyncFile) –
A function returning the data to upload or a file object. File objects must be opened in binary mode (
mode="r+b"
). Callables returning a path string, Path, async iterable or aiofiles open binary file object allow the file data to be read in an asynchronous and lazy way (without reading the entire file into memory). Returning a synchronous iterable or standard open binary file object will still allow the data to be read lazily, but not asynchronously.The function will be called again if the upload fails due to a server timeout, in which case it must restart from the beginning. Callables receive two arguments: the total number of 429 “Too many request” errors that occured, and the total number of server timeout exceptions that occured, thus cleanup operations can be performed for retries if necessary.
content_type (str) – The content MIME type of the file, e.g. “image/png”. Defaults to “application/octet-stream”, corresponding to a generic binary file. Custom values are ignored if encrypt is
True
.filename (str, optional) – The file’s original name.
encrypt (bool) – If the file’s content should be encrypted, necessary for files that will be sent to encrypted rooms. Defaults to
False
.monitor (TransferMonitor, optional) – If a
TransferMonitor
object is passed, it will be updated by this function while uploading. From this object, statistics such as currently transferred bytes or estimated remaining time can be gathered while the upload is running as a task; it also allows for pausing and cancelling.filesize (int, optional) – Size in bytes for the file to transfer. If left as
None
, some servers might refuse the upload.
It’s common to use this alongside
room_send()
. An example of uploading a plain text file follows, but the principle is the same for media, you just need to add an additional “info” key to the content. See the Matrix client-server spec for more details.Example
>>> file_stat = await aiofiles.stat("sample.py") >>> async with aiofiles.open("sample.py", "r+b") as f: >>> resp, maybe_keys = await client.upload( ... f, ... content_type="text/plain", ... filename="hello.py", ... filesize=file_stat.st_size() ... )
>>> await client.room_send( ... room_id="!myfaveroom:example.org", ... message_type="m.room.message", ... content = { ... "msgtype": "m.file", ... "url": resp.content_uri, ... "body": "descriptive title (like the filename)" ... } ... )
-
upload_filter
(user_id: Optional[str] = None, event_fields: Optional[List[str]] = None, event_format: nio.api.EventFormat = <EventFormat.client: 'client'>, presence: Optional[Dict[str, Any]] = None, account_data: Optional[Dict[str, Any]] = None, room: Optional[Dict[str, Any]] = None) → Union[nio.responses.UploadFilterResponse, nio.responses.UploadFilterError][source]¶ Upload a new filter definition to the homeserver.
Returns either a UploadFilterResponse if the request was successful or a UploadFilterError if there was an error with the request.
The filter ID from the successful responses can be used for the
AsyncClient.sync()
,AsyncClient.sync_forever()
andAsyncClient.room_messages()
methods.- Parameters
user_id (Optional[str]) – ID of the user uploading the filter. If not provider, the current logged in user’s ID is used.
event_fields (Optional[List[str]]) – List of event fields to include. If this list is absent then all fields are included. The entries may include ‘.’ characters to indicate sub-fields. A literal ‘.’ character in a field name may be escaped using a ‘’.
event_format (EventFormat) – The format to use for events.
presence (Dict[str, Any]) – The presence updates to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
account_data (Dict[str, Any]) – The user account data that isn’t associated with rooms to include. The dict corresponds to the EventFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
room (Dict[str, Any]) – Filters to be applied to room data. The dict corresponds to the RoomFilter type described in https://matrix.org/docs/spec/client_server/latest#id240
-
class
nio.
TransferMonitor
(total_size: int, on_transferred: Optional[Callable[[int], None]] = None, on_speed_changed: Optional[Callable[[float], None]] = None, speed_period: float = 10, _update_loop_sleep_time: float = 1)[source]¶ Bases:
object
Get statistics, pause or cancel a running upload.
A
TransferMonitor
object can be passed to theAsyncClient.upload()
methods; the methods will then update the object’s statistics while the transfer is running.The transfer can also be paused or cancelled using the object.
- Parameters
total_size (int) – Size in bytes of the data to transfer.
on_transferred (Callable[[int], None], optional) – A callback to call with the new value of
transferred
when it changes.on_speed_changed (Callable[[float], None], optional) – A callback to call with the new value of
average_speed
when it changes.speed_period (float, optional) – How many previous seconds are considered to calculate
average_speed
. Defaults to10
. Lower values makesaverage_speed
more accurate, but less smooth and more susceptible to speed fluctuations.
-
average_speed
¶ An average number of how many bytes are being transferred per second.
- Type
float
-
end_time
¶ The date when the transfer was completed, or
None
if it is still running.- Type
datetime, optional
-
pause
¶ Indicates to methods using this object if the transfer should be paused.
False
by default. At this time, servers don’t handle pausing uploads well and will end up dropping the connection after some time.- Type
bool
-
cancel
¶ When set to True, stop updating statistics and indicate to methods using this object that they should raise a
TransferCancelledError
.- Type
bool
-
average_speed
: float = 0.0¶
-
cancel
: bool = False¶
-
property
done
¶ Whether the transfer is finished.
-
end_time
: Optional[datetime.datetime] = None¶
-
on_speed_changed
: Optional[Callable[[float], None]] = None¶
-
on_transferred
: Optional[Callable[[int], None]] = None¶
-
pause
: bool = False¶
-
property
percent_done
¶ Percentage of completion for the transfer.
-
property
remaining
¶ Number of remaining bytes to transfer.
-
property
remaining_time
¶ Estimated remaining time to complete the transfer.
Returns None (for infinity) if the current transfer speed is 0 bytes/s, or the remaining time is so long it would cause an OverflowError.
-
speed_period
: float = 10¶
-
property
spent_time
¶ Time elapsed since the transfer started.
-
start_time
: datetime.datetime¶
-
total_size
: int¶
-
property
transferred
¶ Number of currently transferred bytes.
HttpClient¶
-
class
nio.
HttpClient
(homeserver: str, user: str = '', device_id: Optional[str] = '', store_path: Optional[str] = '', config: Optional[nio.client.base_client.ClientConfig] = None)[source]¶ Bases:
nio.client.base_client.Client
-
accept_key_verification
(transaction_id: str, tx_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Accept a key verification start event.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
-
cancel_key_verification
(transaction_id: str, tx_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Abort an interactive key verification.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
-
confirm_short_auth_string
(transaction_id: str, tx_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Confirm a short auth string and mark it as matching.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
transaction_id (str) – An transaction id of a valid key verification process.
-
connect
(transport_type: Optional[nio.http.TransportType] = <TransportType.HTTP: 0>) → bytes[source]¶
-
delete_devices
(devices: List[str], auth: Optional[Dict[str, str]] = None) → Tuple[uuid.UUID, bytes][source]¶
-
download
(server_name: str, media_id: str, filename: Optional[str] = None, allow_remote: bool = True) → Tuple[uuid.UUID, bytes][source]¶ Get the content of a file from the content repository.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
filename (str, optional) – A filename to be returned in the response by the server. If None (default), the original name of the file will be returned instead, if there is one.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
get_avatar
(user_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Get a user’s avatar URL.
This queries the avatar matrix content URI of a user from the server. The currently logged in user is queried if no user is specified.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
user_id (str) – User id of the user to get the avatar for.
-
get_displayname
(user_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Get a user’s display name.
This queries the display name of a user from the server. The currently logged in user is queried if no user is specified.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
user_id (str) – User id of the user to get the display name for.
-
get_profile
(user_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Get a user’s combined profile information.
This queries the display name and avatar matrix content URI of a user from the server. Additional profile information may be present. The currently logged in user is queried if no user is specified.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
user_id (str) – User id of the user to get the profile for.
-
join
(room_id: str) → Tuple[uuid.UUID, bytes][source]¶ Join a room.
This tells the server to join the given room. If the room is not public, the user must be invited.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
room_id – The room id or alias of the room to join.
-
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.
-
property
lag
¶
-
login
(password: str = None, device_name: Optional[str] = '', token: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶
-
login_info
() → Tuple[uuid.UUID, bytes][source]¶ Get the available login methods from the server
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
-
next_response
(max_events: int = 0) → Optional[Union[nio.http.TransportResponse, nio.responses.Response]][source]¶
-
parse_body
(transport_response: nio.http.TransportResponse) → Dict[Any, Any][source]¶ Parse the body of the response.
- Parameters
transport_response (TransportResponse) – The transport response that contains the body of the response.
Returns a dictionary representing the response.
-
request_room_key
(event: nio.events.room_events.MegolmEvent, tx_id: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Request a missing room key.
This sends out a message to other devices requesting a room key from them.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
event (str) – An undecrypted MegolmEvent for which we would like to request the decryption key.
-
room_create
(visibility: nio.api.RoomVisibility = <RoomVisibility.private: 'private'>, alias: Optional[str] = None, name: Optional[str] = None, topic: Optional[str] = None, room_version: Optional[str] = None, federate: bool = True, is_direct: bool = False, preset: Optional[nio.api.RoomPreset] = None, invite: Sequence[str] = (), initial_state: Sequence[Dict[str, Any]] = (), power_level_override: Optional[Dict[str, Any]] = None) → Tuple[uuid.UUID, bytes][source]¶ Create a new room.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
visibility (RoomVisibility) – whether to have the room published in the server’s room directory or not. Defaults to
RoomVisibility.private
.alias (str, optional) – The desired canonical alias local part. For example, if set to “foo” and the room is created on the “example.com” server, the room alias will be “#foo:example.com”.
name (str, optional) – A name to set for the room.
topic (str, optional) – A topic to set for the room.
room_version (str, optional) – The room version to set. If not specified, the homeserver will use its default setting. If a version not supported by the homeserver is specified, a 400
M_UNSUPPORTED_ROOM_VERSION
error will be returned.federate (bool) – Whether to allow users from other homeservers from joining the room. Defaults to
True
. Cannot be changed later.is_direct (bool) – If this should be considered a direct messaging room. If
True
, the server will set theis_direct
flag onm.room.member events
sent to the users ininvite
. Defaults toFalse
.preset (RoomPreset, optional) – The selected preset will set various rules for the room. If unspecified, the server will choose a preset from the
visibility
:RoomVisibility.public
equates toRoomPreset.public_chat
, andRoomVisibility.private
equates to aRoomPreset.private_chat
.invite (list) – A list of user id to invite to the room.
initial_state (list) – A list of state event dicts to send when the room is created. For example, a room could be made encrypted immediatly by having a
m.room.encryption
event dict.power_level_override (dict) – A
m.room.power_levels content
dict to override the default. The dict will be applied on top of the generatedm.room.power_levels
event before it is sent to the room.
-
room_forget
(room_id: str) → Tuple[uuid.UUID, bytes][source]¶ Forget a room.
This tells the server to forget the given room’s history for our user. If all users on a homeserver forget the room, the room will be eligible for deletion from that homeserver.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
room_id (str) – The room id of the room to forget.
-
room_leave
(room_id: str) → Tuple[uuid.UUID, bytes][source]¶ Leave a room or reject an invite.
This tells the server to leave the given room. If the user was only invited, the invite is rejected.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
room_id – The room id of the room to leave.
-
room_read_markers
(room_id: str, fully_read_event: str, read_event: Optional[str] = None) → Tuple[uuid.UUID, bytes][source]¶ Update the fully read marker (and optionally the read receipt) for a room.
Calls receive_response() to update the client state if necessary.
Returns either a RoomReadMarkersResponse if the request was successful or a RoomReadMarkersError if there was an error with the request.
This sets the position of the read markers.
fully_read_event is the latest event in the set of events that the user has either fully read or indicated they aren’t interested in. It permits the implementation of a “jump to first unread message” kind of feature. It is _private_ (not exposed to other room participants).
read_event is the most recent message the user has read and is also known as a _read receipt_. A read receipt being set on an event does not imply that all previous events have been seen. This happens in cases such as when a user comes back to a room after hundreds of messages have been sent and _only_ reads the most recent message. The read receipt is _public_ (exposed to other room participants).
If you want to set the read receipt, you _must_ set read_event.
- Parameters
room_id (str) – The room ID of the room where the read markers should be updated.
fully_read_event (str) – The event ID that the user has fully read up to.
read_event (Optional[str]) – The event ID to set the read receipt location at.
-
room_redact
(room_id, event_id, reason=None, tx_id=None)[source]¶ Strip information out of an event.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
room_id (str) – The room id of the room that contains the event that will be redacted.
event_id (str) – The ID of the event that will be redacted.
tx_id (str/UUID, optional) – A transaction ID for this event.
reason (str, optional) – A description explaining why the event was redacted.
-
room_typing
(room_id: str, typing_state: bool = True, timeout: int = 30000) → Tuple[uuid.UUID, bytes][source]¶ Send a typing notice to the server.
This tells the server that the user is typing for the next N milliseconds or that the user has stopped typing.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
room_id (str) – Room id of the room where the user is typing.
typing_state (bool) – A flag representing whether the user started or stopped typing
timeout (int) – For how long should the new typing notice be valid for in milliseconds.
-
set_avatar
(avatar_url: str) → Tuple[uuid.UUID, bytes][source]¶ Set the user’s avatar URL.
This tells the server to set avatar of the currently logged in user to supplied matrix content URI.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
avatar_url (str) – matrix content URI of the avatar to set.
-
set_displayname
(displayname: str) → Tuple[uuid.UUID, bytes][source]¶ Set the user’s display name.
This tells the server to set the display name of the currently logged in user to supplied string.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
displayname (str) – Display name to set.
Share a group session with a room.
This method sends a group session to members of a room.
- Parameters
room_id (str) – The room id of the room where the message should be sent to.
tx_id (str, optional) – The transaction ID of this event used to uniquely identify this message.
ignore_unverified_devices (bool) – Mark unverified devices as ignored. Ignored devices will still receive encryption keys for messages but they won’t be marked as verified.
Raises LocalProtocolError if the client isn’t logged in, if the session store isn’t loaded, no room with the given room id exists or the room isn’t an encrypted room.
-
start_key_verification
(device: OlmDevice, tx_id: Optional[str] = None) → Tuple[UUID, bytes][source]¶ Start a interactive key verification with the given device.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
device (OlmDevice) – An device with which we would like to start the interactive key verification process.
-
sync
(timeout: Optional[int] = None, filter: Optional[Dict[Any, Any]] = None, full_state: bool = False) → Tuple[uuid.UUID, bytes][source]¶
-
thumbnail
(server_name: str, media_id: str, width: int, height: int, method=<ResizingMethod.scale: 'scale'>, allow_remote: bool = True) → Tuple[uuid.UUID, bytes][source]¶ Get the thumbnail of a file from the content repository.
Note: The actual thumbnail may be larger than the size specified.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
server_name (str) – The server name from the mxc:// URI.
media_id (str) – The media ID from the mxc:// URI.
width (int) – The desired width of the thumbnail.
height (int) – The desired height of the thumbnail.
method (ResizingMethod) – The desired resizing method.
allow_remote (bool) – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
-
to_device
(message: ToDeviceMessage, tx_id: Optional[str] = None) → Tuple[UUID, bytes][source]¶ Send a message to a specific device.
Returns a unique uuid that identifies the request and the bytes that should be sent to the socket.
- Parameters
message (ToDeviceMessage) – The message that should be sent out.
tx_id (str, optional) – The transaction ID for this message. Should be unique.
-
Rooms¶
-
class
nio.rooms.
MatrixInvitedRoom
(room_id: str, own_user_id: str)[source]¶ Bases:
nio.rooms.MatrixRoom
-
handle_event
(event: nio.events.room_events.Event) → None[source]¶
-
handle_membership
(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.InviteMemberEvent]) → bool[source]¶ Handle a membership event for the invited room.
- Parameters
event (RoomMemberEvent) – The event that should be handled that updates the room state.
Returns True if the member list of the room has changed False otherwise.
-
-
class
nio.rooms.
MatrixRoom
(room_id: str, own_user_id: str, encrypted: bool = False)[source]¶ Bases:
object
Represents a Matrix room.
-
add_member
(user_id: str, display_name: Optional[str], avatar_url: Optional[str], invited: bool = False) → bool[source]¶
-
avatar_url
(user_id: str) → Optional[str][source]¶ Get avatar url for a user.
Returns a matrix content URI, or None if the user has no avatar.
-
property
display_name
¶ Calculate display name for a room.
Prefer returning the room name if it exists, falling back to a group-style name if not.
Follows: https://matrix.org/docs/spec/client_server/r0.6.0#id342
-
property
gen_avatar_url
¶ Get the calculated room’s avatar url.
Either the room’s avatar if one is set, or the avatar of the first user that’s not ourselves if the room is an unnamed group or has exactly two users.
-
group_name
() → str[source]¶ Return the group-style name of the room.
In other words, a display name based on the names of room members. This is used for ad-hoc groups of people (usually direct chats).
-
group_name_structure
() → Tuple[bool, List[str], int][source]¶ Get if room is empty, ID for listed users and the N others count.
-
handle_account_data
(event: nio.events.account_data.AccountDataEvent) → None[source]¶
-
handle_ephemeral_event
(event: nio.events.ephemeral.EphemeralEvent) → None[source]¶
-
handle_event
(event: nio.events.room_events.Event) → None[source]¶
-
handle_membership
(event: Union[nio.events.room_events.RoomMemberEvent, nio.events.invite_events.InviteMemberEvent]) → bool[source]¶ Handle a membership event for the room.
- Parameters
event (RoomMemberEvent) – The event that should be handled that updates the room state.
Returns True if the member list of the room has changed False otherwise.
-
property
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.
-
property
is_named
¶ Determine whether a room is named.
A named room is a room with either the name or a canonical alias set.
-
property
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.
-
property
member_count
¶
-
named_room_name
() → Optional[str][source]¶ Return the name of the room if it’s a named room, otherwise None.
-
update_summary
(summary: nio.responses.RoomSummary) → None[source]¶
-
-
class
nio.rooms.
MatrixUser
(user_id: str, display_name: Optional[str] = None, avatar_url: Optional[str] = None, power_level: int = 0, invited: bool = False, presence: str = 'offline', last_active_ago: Optional[int] = None, currently_active: Optional[bool] = None, status_msg: Optional[str] = None)[source]¶ Bases:
object
-
property
disambiguated_name
¶
-
property
name
¶
-
property
Events¶
Nio Events Module.
The model of conversation history exposed by a Matrix server can be considered as a list of events. The server ‘linearises’ the eventually-consistent event graph of events into an ‘event stream’ at any given point in time:
Nio contains clases for most known Matrix Event types.
-
class
nio.events.misc.
BadEvent
(source: Dict[str, Any], event_id: str, sender: str, server_timestamp: int, type: str)[source]¶ Bases:
object
An event that failed event schema and type validation.
This type of event will be created if the event has a valid core structure but failed validation for the given event type.
The event can still be inspected with the source attribute.
-
source
¶ The source dictionary of the event. This allows access to all the event fields in a non-secure way.
- Type
dict
-
event_id
¶ A globally unique event identifier.
- Type
str
-
sender
¶ The fully-qualified ID of the user who sent this event.
- Type
str
-
server_timestamp
¶ Timestamp in milliseconds on originating homeserver when this event was sent.
- Type
int
-
type
¶ The claimed type of the event.
- Type
str
-
decrypted
¶ A flag signaling if the event was decrypted.
- Type
bool
-
verified
¶ A flag signaling if the event is verified, is True if the event was sent from a verified device.
- Type
bool
-
sender_key
¶ The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
session_id
¶ The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
transaction_id
¶ The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.
- Type
str, optional
-
-
class
nio.events.misc.
UnknownBadEvent
(source: Dict[str, Any], transaction_id: Optional[str] = None)[source]¶ Bases:
object
An event that doesn’t have the minimal necessary structure.
This type of event will be created if we can’t find the event_id, sender, origin server timestamp or event type.
The event can still be inspected with the source attribute.
-
source
¶ The source dictionary of the event. This allows access to all the event fields in a non-secure way.
- Type
dict
-
decrypted
¶ A flag signaling if the event was decrypted.
- Type
bool
-
verified
¶ A flag signaling if the event is verified, is True if the event was sent from a verified device.
- Type
bool
-
sender_key
¶ The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
session_id
¶ The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
transaction_id
¶ The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.
- Type
str, optional
-
Room Events¶
-
class
nio.events.room_events.
CallAnswerEvent
(source: Dict[str, Any], call_id: str, version: int, answer: Dict[str, Any])[source]¶ Bases:
nio.events.room_events.CallEvent
Event representing the answer to a VoIP call.
This event is sent by the callee when they wish to answer the call.
-
answer
¶ The session description object. A dictionary containing the keys “type” which must be “answer” for this event and “sdp” which contains the SDP text of the session description.
- Type
dict
-
answer
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
CallCandidatesEvent
(source: Dict[str, Any], call_id: str, version: int, candidates: List[Dict[str, Any]])[source]¶ Bases:
nio.events.room_events.CallEvent
Call event holding additional VoIP ICE candidates.
This event is sent by callers after sending an invite and by the callee after answering. Its purpose is to give the other party additional ICE candidates to try using to communicate.
- Parameters
candidates (list) – A list of dictionaries describing the candidates.
-
candidates
: List[Dict[str, Any]]¶
-
class
nio.events.room_events.
CallEvent
(source: Dict[str, Any], call_id: str, version: int)[source]¶ Bases:
nio.events.room_events.Event
Base Class for Matrix call signalling events.
-
call_id
¶ The unique identifier of the call.
- Type
str
-
version
¶ The version of the VoIP specification this message adheres to.
- Type
int
-
call_id
: str¶
-
static
parse_event
(event_dict)[source]¶ Parse a Matrix event and create a higher level event object.
This function parses the type of the Matrix event and produces a higher level CallEvent object representing the parsed event.
The event structure is checked for correctness and the event fields are type checked. If this validation process fails for an event an BadEvent will be produced.
If the type of the event is now known an UnknownEvent will be produced.
- Parameters
event_dict (dict) – The raw matrix event dictionary.
-
version
: int¶
-
-
class
nio.events.room_events.
CallHangupEvent
(source: Dict[str, Any], call_id: str, version: int)[source]¶ Bases:
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.
-
call_id
: str¶
-
event_id
: str¶
-
classmethod
from_dict
(event_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
version
: int¶
-
-
class
nio.events.room_events.
CallInviteEvent
(source: Dict[str, Any], call_id: str, version: int, lifetime: int, offer: Dict[str, Any])[source]¶ Bases:
nio.events.room_events.CallEvent
Event representing an invitation to a VoIP call.
This event is sent by a caller when they wish to establish a call.
-
lifetime
¶ The time in milliseconds that the invite is valid for.
- Type
integer
-
offer
¶ The session description object. A dictionary containing the keys “type” which must be “offer” for this event and “sdp” which contains the SDP text of the session description.
- Type
dict
-
property
expired
¶ Property marking if the invite event expired.
-
classmethod
from_dict
(event_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
lifetime
: int¶
-
offer
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
DefaultLevels
(ban: int = 50, invite: int = 50, kick: int = 50, redact: int = 50, state_default: int = 0, events_default: int = 0, users_default: int = 0)[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
-
ban
: int = 50¶
-
events_default
: int = 0¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create a DefaultLevels object from a dictionary.
This creates the DefaultLevels object from a dictionary containing a m.room.power_levels event. The event structure isn’t checked in this method.
This shouldn’t be used directly, the PowerLevelsEvent method will call this method to construct the DefaultLevels object.
-
invite
: int = 50¶
-
kick
: int = 50¶
-
redact
: int = 50¶
-
state_default
: int = 0¶
-
users_default
: int = 0¶
-
-
class
nio.events.room_events.
Event
(source: Dict[str, Any])[source]¶ Bases:
object
Matrix Event class.
This is the base event class, most events inherit from this class.
-
source
¶ The source dictionary of the event. This allows access to all the event fields in a non-secure way.
- Type
dict
-
event_id
¶ A globally unique event identifier.
- Type
str
-
sender
¶ The fully-qualified ID of the user who sent this event.
- Type
str
-
server_timestamp
¶ Timestamp in milliseconds on originating homeserver when this event was sent.
- Type
int
-
decrypted
¶ A flag signaling if the event was decrypted.
- Type
bool
-
verified
¶ A flag signaling if the event is verified, is True if the event was sent from a verified device.
- Type
bool
-
sender_key
¶ The public key of the sender that was used to establish the encrypted session. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
session_id
¶ The unique identifier of the session that was used to decrypt the message. Is only set if decrypted is True, otherwise None.
- Type
str, optional
-
transaction_id
¶ The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.
- Type
str, optional
-
decrypted
: bool = False¶
-
event_id
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
classmethod
parse_decrypted_event
(event_dict: Dict[Any, Any]) → Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Parse a decrypted event and create a higher level event object.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
classmethod
parse_encrypted_event
(event_dict)[source]¶ Parse an encrypted event.
Encrypted events may have different fields depending on the algorithm that was used to encrypt them.
This function checks the algorithm of the event and produces a higher level event from the provided dictionary.
- Parameters
event_dict (dict) – The dictionary representation of the encrypted event.
Returns None if the algorithm of the event is unknown.
-
classmethod
parse_event
(event_dict: Dict[Any, Any]) → Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Parse a Matrix event and create a higher level event object.
This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.
The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.
If the type of the event is now known an UnknownEvent will be produced.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
sender_key
: Optional[str] = None¶
-
server_timestamp
: int¶
-
session_id
: Optional[str] = None¶
-
source
: Dict[str, Any]¶
-
transaction_id
: Optional[str] = None¶
-
verified
: bool = False¶
-
-
class
nio.events.room_events.
MegolmEvent
(source: Dict[str, Any], device_id: str, ciphertext: str, algorithm: str, room_id: str = '')[source]¶ Bases:
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
-
algorithm
: str¶
-
as_key_request
(user_id: str, requesting_device_id: str, request_id: Optional[str] = None, device_id: Optional[str] = None) → nio.event_builders.direct_messages.RoomKeyRequestMessage[source]¶ Make a to-device message for a room key request.
MegolmEvents are presented to library users only if the library fails to decrypt the event because of a missing session key.
A missing key can be requested later on by sending a key request, this method creates a ToDeviceMessage that can be sent out if such a request should be made.
- Parameters
user_id (str) – The user id of the user that should receive the key request.
requesting_device_id (str) – The device id of the user that is requesting the key.
request_id (str, optional) – A unique string identifying the request. Defaults to the session id of the missing megolm session.
device_id (str, optional) – The device id of the device that should receive the request. Defaults to all the users devices.
-
ciphertext
: str¶
-
device_id
: str¶
-
classmethod
from_dict
(event_dict)[source]¶ Create a MegolmEvent from a dictionary.
- Parameters
event_dict (Dict) – Dictionary containing the event.
Returns a MegolmEvent if the event_dict contains a valid event or a BadEvent if it’s invalid.
-
room_id
: str = ''¶
-
-
class
nio.events.room_events.
PowerLevels
(defaults: nio.events.room_events.DefaultLevels = <factory>, users: Dict[str, int] = <factory>, events: Dict[str, int] = <factory>)[source]¶ Bases:
object
Class holding information of room power levels.
-
defaults
¶ The default power levels of the room.
- Type
-
users
¶ The power levels for specific users. This is a mapping from user_id to power level for that user.
- Type
dict
-
events
¶ The level required to send specific event types. This is a mapping from event type to power level required.
- Type
dict
-
can_user_ban
(user_id: str, target_user_id: Optional[str] = None) → bool[source]¶ Return whether a user has enough power to ban another.
If
target_user_id
isNone
, returns whetheruser_id
has enough power to ban anyone with a lower power level than that user.
-
can_user_invite
(user_id: str) → bool[source]¶ Return whether a user has enough power to invite others.
-
can_user_kick
(user_id: str, target_user_id: Optional[str] = None) → bool[source]¶ Return whether a user has enough power to kick another.
If
target_user_id
isNone
, returns whetheruser_id
has enough power to kick anyone with a lower power level than that user.
-
can_user_redact
(user_id: str) → bool[source]¶ Return whether a user has enough power to react other user’s events.
-
can_user_send_message
(user_id: str, event_type: str = 'm.room.message') → bool[source]¶ Return whether a user has enough power to send certain message events.
- Parameters
user_id (str) – The user to check the power of.
event_type (str) – The type of matrix message event to check the required power of, m.room.message by default.
-
can_user_send_state
(user_id: str, event_type: str) → bool[source]¶ Return whether a user has enough power to send certain state events.
- Parameters
user_id (str) – The user to check the power of.
event_type (str) – The type of matrix state event to check the required power of, e.g. m.room.encryption.
-
defaults
: nio.events.room_events.DefaultLevels¶
-
events
: Dict[str, int]¶
-
get_message_event_required_level
(event_type: str) → int[source]¶ Get required power level to send a certain type of message event.
Returns an integer representing the required power level.
- Parameters
event_type (str) – The type of matrix message event we want the required level for, e.g. m.room.message.
-
get_state_event_required_level
(event_type: str) → int[source]¶ Get required power level to send a certain type of state event.
Returns an integer representing the required power level.
- Parameters
event_type (str) – The type of matrix state event we want the required level for, e.g. m.room.name or m.room.topic.
-
get_user_level
(user_id: str) → int[source]¶ Get the power level of a user.
Returns an integer representing the user’s power level.
- Parameters
user_id (str) – The fully-qualified ID of the user for whom we would like to get the power level.
-
update
(new_levels)[source]¶ Update the power levels object with new levels.
- Parameters
new_levels (PowerLevels) – A new PowerLevels object that we received from a newer PowerLevelsEvent.
-
users
: Dict[str, int]¶
-
-
class
nio.events.room_events.
PowerLevelsEvent
(source: Dict[str, Any], power_levels: nio.events.room_events.PowerLevels)[source]¶ Bases:
nio.events.room_events.Event
Class representing a m.room.power_levels event.
This event specifies the minimum level a user must have in order to perform a certain action. It also specifies the levels of each user in the room.
-
power_levels
¶ The PowerLevels object holding information of the power levels of the room.
- Type
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
power_levels
: nio.events.room_events.PowerLevels¶
-
-
class
nio.events.room_events.
RedactedEvent
(source: Dict[str, Any], type: str, redacter: str, reason: Optional[str])[source]¶ Bases:
nio.events.room_events.Event
An event that has been redacted.
-
type
¶ The type of the event that has been redacted.
- Type
str
-
redacter
¶ The fully-qualified ID of the user who redacted the event.
- Type
str
-
reason
¶ A string describing why the event was redacted, can be None.
- Type
str, optional
-
property
event_type
¶ Type of the event.
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RedactedEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
reason
: Optional[str]¶
-
redacter
: str¶
-
type
: str¶
-
-
class
nio.events.room_events.
RedactionEvent
(source: Dict[str, Any], redacts: str, reason: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.Event
An event signaling that another event has been redacted.
Events can be redacted by either room or server administrators. Redacting an event means that all keys not required by the protocol are stripped off.
-
redacts
¶ The event id of the event that has been redacted.
- Type
str
-
reason
¶ A string describing why the event was redacted, can be None.
- Type
str, optional
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RedactionEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
reason
: Optional[str] = None¶
-
redacts
: str¶
-
-
class
nio.events.room_events.
RoomAliasEvent
(source: Dict[str, Any], canonical_alias: str)[source]¶ Bases:
nio.events.room_events.Event
An event informing us about which alias should be preferred.
-
canonical_alias
¶ The alias that is considered canonical.
- Type
str
-
canonical_alias
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomAliasEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
-
class
nio.events.room_events.
RoomAvatarEvent
(source: Dict[str, Any], avatar_url: str)[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
-
avatar_url
: str¶
-
-
class
nio.events.room_events.
RoomCreateEvent
(source: Dict[str, Any], creator: str, federate: bool = True, room_version: str = '1')[source]¶ Bases:
nio.events.room_events.Event
The first event in a room, signaling that the room was created.
-
creator
¶ The fully-qualified ID of the user who created the room.
- Type
str
-
federate
¶ A boolean flag telling us whether users on other homeservers are able to join this room.
- Type
bool
-
room_version
¶ The version of the room. Different room versions will have different event formats. Clients shouldn’t worry about this too much unless they want to perform room upgrades.
- Type
str
-
creator
: str¶
-
federate
: bool = True¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomCreateEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
room_version
: str = '1'¶
-
-
class
nio.events.room_events.
RoomEncryptedAudio
(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, thumbnail_url: Optional[str] = None, thumbnail_key: Optional[Dict] = None, thumbnail_hashes: Optional[Dict] = None, thumbnail_iv: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.RoomEncryptedMedia
A room message containing an audio clip where the file is encrypted.
-
body
: str¶
-
hashes
: Dict[str, Any]¶
-
iv
: str¶
-
key
: Dict[str, Any]¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomEncryptedFile
(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, thumbnail_url: Optional[str] = None, thumbnail_key: Optional[Dict] = None, thumbnail_hashes: Optional[Dict] = None, thumbnail_iv: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.RoomEncryptedMedia
A room message containing a generic encrypted file.
-
body
: str¶
-
hashes
: Dict[str, Any]¶
-
iv
: str¶
-
key
: Dict[str, Any]¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomEncryptedImage
(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, thumbnail_url: Optional[str] = None, thumbnail_key: Optional[Dict] = None, thumbnail_hashes: Optional[Dict] = None, thumbnail_iv: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.RoomEncryptedMedia
A room message containing an image where the file is encrypted.
-
body
: str¶
-
hashes
: Dict[str, Any]¶
-
iv
: str¶
-
key
: Dict[str, Any]¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomEncryptedMedia
(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, thumbnail_url: Optional[str] = None, thumbnail_key: Optional[Dict] = None, thumbnail_hashes: Optional[Dict] = None, thumbnail_iv: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.RoomMessage
Base class for encrypted room messages containing an URI.
-
url
¶ The URL of the file.
- Type
str
-
body
¶ The description of the message.
- Type
str
-
key
¶ The key that can be used to decrypt the file.
- Type
dict
-
hashes
¶ A mapping from an algorithm name to a hash of the ciphertext encoded as base64.
- Type
dict
-
iv
¶ The initialisation vector that was used to encrypt the file.
- Type
str
-
thumbnail_url
¶ The URL of the thumbnail file.
- Type
str, optional
-
thumbnail_key
¶ The key that can be used to decrypt the thumbnail file.
- Type
dict, optional
-
thumbnail_hashes
¶ A mapping from an algorithm name to a hash of the thumbnail ciphertext encoded as base64.
- Type
dict, optional
-
thumbnail_iv
¶ The initialisation vector that was used to encrypt the thumbnail file.
- Type
str, optional
-
body
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
hashes
: Dict[str, Any]¶
-
iv
: str¶
-
key
: Dict[str, Any]¶
-
thumbnail_hashes
: Optional[Dict] = None¶
-
thumbnail_iv
: Optional[str] = None¶
-
thumbnail_key
: Optional[Dict] = None¶
-
thumbnail_url
: Optional[str] = None¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomEncryptedVideo
(source: Dict[str, Any], url: str, body: str, key: Dict[str, Any], hashes: Dict[str, Any], iv: str, thumbnail_url: Optional[str] = None, thumbnail_key: Optional[Dict] = None, thumbnail_hashes: Optional[Dict] = None, thumbnail_iv: Optional[str] = None)[source]¶ Bases:
nio.events.room_events.RoomEncryptedMedia
A room message containing a video clip where the file is encrypted.
-
body
: str¶
-
event_id
: str¶
-
hashes
: Dict[str, Any]¶
-
iv
: str¶
-
key
: Dict[str, Any]¶
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomEncryptionEvent
(source: Dict[str, Any])[source]¶ Bases:
nio.events.room_events.Event
An event signaling that encryption has been enabled in a room.
-
event_id
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
RoomGuestAccessEvent
(source: Dict[str, Any], guest_access: str = 'forbidden')[source]¶ Bases:
nio.events.room_events.Event
Event signaling whether guest users are allowed to join rooms.
-
guest_access
¶ A string describing the guest access policy of the room. Can be one of “can_join” or “forbidden”.
- Type
str
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomGuestAccessEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
guest_access
: str = 'forbidden'¶
-
-
class
nio.events.room_events.
RoomHistoryVisibilityEvent
(source: Dict[str, Any], history_visibility: str = 'shared')[source]¶ Bases:
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: Dict[Any, Any]) → Union[nio.events.room_events.RoomHistoryVisibilityEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
history_visibility
: str = 'shared'¶
-
class
nio.events.room_events.
RoomJoinRulesEvent
(source: Dict[str, Any], join_rule: str = 'invite')[source]¶ Bases:
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: Dict[Any, Any]) → Union[nio.events.room_events.RoomJoinRulesEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
join_rule
: str = 'invite'¶
-
-
class
nio.events.room_events.
RoomMemberEvent
(source: Dict[str, Any], state_key: str, membership: str, prev_membership: Optional[str], content: Dict[str, Any], prev_content: Optional[Dict[str, Any]] = None)[source]¶ Bases:
nio.events.room_events.Event
Class representing to an m.room.member event.
-
state_key
¶ The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.
- Type
str
-
membership
¶ The membership state of the user. One of “invite”, “join”, “leave”, “ban”.
- Type
str
-
prev_membership
¶ The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.
- Type
str, optional
-
content
¶ The content of the of the membership event.
- Type
dict
-
prev_content
¶ The content of a previous membership event that this one is overwriting.
- Type
dict, optional
-
content
: Dict[str, Any]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomMemberEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
membership
: str¶
-
prev_content
: Optional[Dict[str, Any]] = None¶
-
prev_membership
: Optional[str]¶
-
state_key
: str¶
-
-
class
nio.events.room_events.
RoomMessage
(source: Dict[str, Any])[source]¶ Bases:
nio.events.room_events.Event
Abstract room message class.
This class corespondents to a Matrix event of the m.room.message type. It is used when messages are sent to the room.
The class has one child class per msgtype.
-
event_id
: str¶
-
classmethod
parse_decrypted_event
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomMessage, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Parse a decrypted event and create a higher level event object.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
classmethod
parse_event
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomMessage, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Parse a Matrix event and create a higher level event object.
This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.
The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event an BadEvent will be produced.
If the type of the event is now known an UnknownEvent will be produced.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
RoomMessageAudio
(source: Dict[str, Any], url: str, body: str)[source]¶ Bases:
nio.events.room_events.RoomMessageMedia
A room message containing an audio clip.
-
body
: str¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomMessageEmote
(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]¶ Bases:
nio.events.room_events.RoomMessageFormatted
A room message coresponding to the m.emote msgtype.
This message is similar to m.text except that the sender is ‘performing’ the action contained in the body key, similar to /me in IRC.
-
body
¶ The textual body of the message.
- Type
str
-
formatted_body
¶ The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.
- Type
str, optional
-
format
¶ The format used in the formatted_body. This specifies how the formatted_body should be interpreted.
- Type
str, optional
-
body
: str¶
-
format
: Optional[str]¶
-
formatted_body
: Optional[str]¶
-
-
class
nio.events.room_events.
RoomMessageFile
(source: Dict[str, Any], url: str, body: str)[source]¶ Bases:
nio.events.room_events.RoomMessageMedia
A room message containing a generic file.
-
body
: str¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomMessageFormatted
(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]¶ Bases:
nio.events.room_events.RoomMessage
Base abstract class for room messages that can have formatted bodies.
-
body
¶ The textual body of the message.
- Type
str
-
formatted_body
¶ The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.
- Type
str, optional
-
format
¶ The format used in the formatted_body. This specifies how the formatted_body should be interpreted.
- Type
str, optional
-
body
: str¶
-
format
: Optional[str]¶
-
formatted_body
: Optional[str]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomMessage, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
-
class
nio.events.room_events.
RoomMessageImage
(source: Dict[str, Any], url: str, body: str)[source]¶ Bases:
nio.events.room_events.RoomMessageMedia
A room message containing an image.
-
body
: str¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomMessageMedia
(source: Dict[str, Any], url: str, body: str)[source]¶ Bases:
nio.events.room_events.RoomMessage
Base class for room messages containing a URI.
-
url
¶ The URL of the file.
- Type
str
-
body
¶ The description of the message.
- Type
str
-
body
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
url
: str¶
-
-
class
nio.events.room_events.
RoomMessageNotice
(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]¶ Bases:
nio.events.room_events.RoomMessageFormatted
A room message corresponding to the m.notice msgtype.
Room notices are primarily intended for responses from automated clients.
-
body
¶ The textual body of the notice.
- Type
str
-
formatted_body
¶ The formatted version of the notice body. Can be None if the message doesn’t contain a formatted version of the body.
- Type
str, optional
-
format
¶ The format used in the formatted_body. This specifies how the formatted_body should be interpreted.
- Type
str, optional
-
body
: str¶
-
event_id
: str¶
-
format
: Optional[str]¶
-
formatted_body
: Optional[str]¶
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
RoomMessageText
(source: Dict[str, Any], body: str, formatted_body: Optional[str], format: Optional[str])[source]¶ Bases:
nio.events.room_events.RoomMessageFormatted
A room message corresponding to the m.text msgtype.
This message is the most basic message and is used to represent text.
-
body
¶ The textual body of the message.
- Type
str
-
formatted_body
¶ The formatted version of the body. Can be None if the message doesn’t contain a formatted version of the body.
- Type
str, optional
-
format
¶ The format used in the formatted_body. This specifies how the formatted_body should be interpreted.
- Type
str, optional
-
body
: str¶
-
event_id
: str¶
-
format
: Optional[str]¶
-
formatted_body
: Optional[str]¶
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
-
class
nio.events.room_events.
RoomMessageUnknown
(source: Dict[str, Any], msgtype: str, content: Dict[str, Any])[source]¶ Bases:
nio.events.room_events.RoomMessage
A m.room.message which we do not understand.
This event is created every time nio tries to parse a room message of an unknown msgtype. Since custom and extensible events are a feature of Matrix this allows clients to use custom messages but care should be taken that the clients will be responsible to validate and type check the content of the message.
-
msgtype
¶ The msgtype of the room message.
- Type
str
-
content
¶ The dictionary holding the content of the room message. The keys and values of this dictionary will differ depending on the msgtype.
- Type
dict
-
content
: Dict[str, Any]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → nio.events.room_events.RoomMessage[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
msgtype
: str¶
-
property
type
¶ Get the msgtype of the room message.
-
-
class
nio.events.room_events.
RoomMessageVideo
(source: Dict[str, Any], url: str, body: str)[source]¶ Bases:
nio.events.room_events.RoomMessageMedia
A room message containing a video clip.
-
body
: str¶
-
event_id
: str¶
-
sender
: str¶
-
server_timestamp
: int¶
-
source
: Dict[str, Any]¶
-
url
: str¶
-
-
class
nio.events.room_events.
RoomNameEvent
(source: Dict[str, Any], name: str)[source]¶ Bases:
nio.events.room_events.Event
Event holding the name of the room.
The room name is a human-friendly string designed to be displayed to the end-user. The room name is not unique, as multiple rooms can have the same room name set.
-
name
¶ The name of the room.
- Type
str
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomNameEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
name
: str¶
-
-
class
nio.events.room_events.
RoomTopicEvent
(source: Dict[str, Any], topic: str)[source]¶ Bases:
nio.events.room_events.Event
Event holding the topic of a room.
A topic is a short message detailing what is currently being discussed in the room. It can also be used as a way to display extra information about the room, which may not be suitable for the room name.
-
topic
¶ The topic of the room.
- Type
str
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.room_events.RoomTopicEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
topic
: str¶
-
-
class
nio.events.room_events.
UnknownEncryptedEvent
(source: Dict[str, Any], type: str, algorithm: str)[source]¶ Bases:
nio.events.room_events.Event
An encrypted event which we don’t know how to decrypt.
This event is created every time nio tries to parse an event encrypted event that was encrypted using an unknown algorithm.
-
type
¶ The type of the event.
- Type
str
-
algorithm
¶ The algorithm of the event.
- Type
str
-
algorithm
: str¶
-
classmethod
from_dict
(event_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
type
: str¶
-
-
class
nio.events.room_events.
UnknownEvent
(source: Dict[str, Any], type: str)[source]¶ Bases:
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.
-
type
: str¶
-
Invite Room Events¶
Matrix Invite Events.
Events for invited rooms will have a stripped down version of their counterparts for joined rooms.
Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.
These events help set up the state of an invited room so more information can be displayed to users if they are invited to a room.
-
class
nio.events.invite_events.
InviteAliasEvent
(source: Dict, sender: str, canonical_alias: str)[source]¶ Bases:
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
-
canonical_alias
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.invite_events.InviteAliasEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an InviteEvent from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
-
class
nio.events.invite_events.
InviteEvent
(source: Dict, sender: str)[source]¶ Bases:
object
Matrix Event class for events in invited rooms.
Events for invited rooms will have a stripped down version of their counterparts for joined rooms.
Such events will be missing the event id and origin server timestamp. Since all of the events in an invited room will be state events they will never be encrypted.
-
source
¶ The source dictionary of the event. This allows access to all the event fields in a non-secure way.
- Type
dict
-
sender
¶ The fully-qualified ID of the user who sent this event.
- Type
str
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an InviteEvent from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
classmethod
parse_event
(event_dict: Dict[Any, Any]) → Optional[Union[nio.events.invite_events.InviteEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]][source]¶ Parse a Matrix invite event and create a higher level event object.
This function parses the type of the Matrix event and produces a higher level event object representing the parsed event.
The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
source
: Dict¶
-
-
class
nio.events.invite_events.
InviteMemberEvent
(source: Dict, sender: str, state_key: str, membership: str, prev_membership: str, content: dict, prev_content: dict = <factory>)[source]¶ Bases:
nio.events.invite_events.InviteEvent
Class representing to an m.room.member event in an invited room.
-
state_key
¶ The user_id this membership event relates to. In all cases except for when membership is join, the user ID in the sender attribute does not need to match the user ID in the state_key.
- Type
str
-
membership
¶ The membership state of the user. One of “invite”, “join”, “leave”, “ban”.
- Type
str
-
prev_membership
¶ The previous membership state that this one is overwriting. Can be None in which case the membership state is assumed to have been “leave”.
- Type
str, optional
-
content
¶ The content of the of the membership event.
- Type
dict
-
prev_content
¶ The content of a previous membership event that this one is overwriting.
- Type
dict, optional
-
content
: dict¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.events.invite_events.InviteMemberEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an InviteEvent from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
membership
: str¶
-
prev_content
: dict¶
-
prev_membership
: str¶
-
state_key
: str¶
-
-
class
nio.events.invite_events.
InviteNameEvent
(source: Dict, sender: str, name: str)[source]¶ Bases:
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: Dict[Any, Any]) → Union[nio.events.invite_events.InviteNameEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent][source]¶ Create an InviteEvent from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
name
: str¶
-
To-device Events¶
nio to-device events.
To-device events are events that are sent dirrectly between two devices instead of normally sending events in a room.
To-device events can be sent to a specific device of a user or to all devices of a user.
-
class
nio.events.to_device.
BaseRoomKeyRequest
(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str)[source]¶ Bases:
nio.events.to_device.ToDeviceEvent
Base class for room key requests. requesting_device_id (str): The id of the device that is requesting the
key.
request_id (str): A unique identifier for the request.
-
classmethod
parse_event
(event_dict)[source]¶ Parse a to-device event and create a higher level event object.
This function parses the type of the to-device event and produces a higher level event object representing the parsed event.
The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
request_id
: str¶
-
requesting_device_id
: str¶
-
classmethod
-
class
nio.events.to_device.
DummyEvent
(source: Dict[str, Any], sender: str, sender_key: str, sender_device: str)[source]¶ Bases:
nio.events.to_device.ToDeviceEvent
Event containing a dummy message.
This event type is used start a new Olm session with a device. The event has no content.
-
sender
¶ The sender of the event.
- Type
str
-
sender_key
¶ The key of the sender that sent the event.
- Type
str
-
classmethod
from_dict
(event_dict, sender, sender_key)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
sender_device
: str¶
-
sender_key
: str¶
-
-
class
nio.events.to_device.
EncryptedToDeviceEvent
(source: Dict[str, Any], sender: str)[source]¶ Bases:
nio.events.to_device.ToDeviceEvent
-
sender
: str¶
-
source
: Dict[str, Any]¶
-
-
class
nio.events.to_device.
ForwardedRoomKeyEvent
(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]¶ Bases:
nio.events.to_device.RoomKeyEvent
Event containing a room key that got forwarded to us.
-
sender
¶ The sender of the event.
- Type
str
-
sender_key
¶ The key of the sender that sent the event.
- Type
str
-
room_id
¶ The room ID of the room to which the session key belongs to.
- Type
str
-
session_id
¶ The session id of the session key.
- Type
str
-
algorithm
¶ The algorithm of the session key.
- Type
str
-
algorithm
: 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.
-
room_id
: str¶
-
sender_key
: str¶
-
session_id
: str¶
-
-
class
nio.events.to_device.
KeyVerificationAccept
(source: Dict[str, Any], sender: str, transaction_id: str, commitment: str, key_agreement_protocol: str, hash: str, message_authentication_code: str, short_authentication_string: List[str])[source]¶ Bases:
nio.events.common.KeyVerificationAcceptMixin
,nio.events.to_device.KeyVerificationEvent
Event signaling that the SAS verification start has been accepted.
-
commitment
¶ The commitment value of the verification process.
- Type
str
-
key_agreement_protocol
¶ The key agreement protocol the device is choosing to use
- Type
str
-
hash
¶ A list of strings specifying the hash methods the sending device understands.
- Type
str
-
message_authentication_code
¶ The message authentication code the device is choosing to use.
- Type
str
-
short_authentication_string
¶ A list of strings specifying the SAS methods that can be used in the verification process.
- Type
list
-
commitment
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
hash
: str¶
-
key_agreement_protocol
: str¶
-
message_authentication_code
: str¶
-
short_authentication_string
: List[str]¶
-
-
class
nio.events.to_device.
KeyVerificationCancel
(source: Dict[str, Any], sender: str, transaction_id: str, code: str, reason: str)[source]¶ Bases:
nio.events.common.KeyVerificationCancelMixin
,nio.events.to_device.KeyVerificationEvent
Event signaling that a key verification process has been canceled.
-
code
¶ The error code for why the process/request was canceled by the user.
- Type
str
-
reason
¶ A human readable description of the cancellation code.
- Type
str
-
code
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
reason
: str¶
-
-
class
nio.events.to_device.
KeyVerificationEvent
(source: Dict[str, Any], sender: str, transaction_id: str)[source]¶ Bases:
nio.events.common.KeyVerificationEventMixin
,nio.events.to_device.ToDeviceEvent
Base class for key verification events.
-
transaction_id
¶ An opaque identifier for the verification process. Must be unique with respect to the devices involved.
- Type
str
-
transaction_id
: str¶
-
-
class
nio.events.to_device.
KeyVerificationKey
(source: Dict[str, Any], sender: str, transaction_id: str, key: str)[source]¶ Bases:
nio.events.common.KeyVerificationKeyMixin
,nio.events.to_device.KeyVerificationEvent
Event carrying a key verification key.
After this event is received the short authentication string can be shown to the user.
-
key
¶ The device’s ephemeral public key, encoded as unpadded base64.
- Type
str
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
key
: str¶
-
-
class
nio.events.to_device.
KeyVerificationMac
(source: Dict[str, Any], sender: str, transaction_id: str, mac: Dict[str, str], keys: str)[source]¶ Bases:
nio.events.common.KeyVerificationMacMixin
,nio.events.to_device.KeyVerificationEvent
Event holding a message authentication code of the verification process.
After this event is received the device that we are verifying will be marked as verified given that we have accepted the short authentication string as well.
-
mac
¶ A map of the key ID to the MAC of the key, using the algorithm in the verification process. The MAC is encoded as unpadded base64.
- Type
dict
-
keys
¶ The MAC of the comma-separated, sorted, list of key IDs given in the mac property, encoded as unpadded base64.
- Type
str
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
keys
: str¶
-
mac
: Dict[str, str]¶
-
-
class
nio.events.to_device.
KeyVerificationStart
(source: Dict[str, Any], sender: str, transaction_id: str, from_device: str, method: str, key_agreement_protocols: List[str], hashes: List[str], message_authentication_codes: List[str], short_authentication_string: List[str])[source]¶ Bases:
nio.events.common.KeyVerificationStartMixin
,nio.events.to_device.KeyVerificationEvent
Event signaling the start of a SAS key verification process.
-
from_device
¶ The device ID which is initiating the process.
- Type
str
-
method
¶ The verification method to use.
- Type
str
-
key_agreement_protocols
¶ A list of strings specifying the key agreement protocols the sending device understands.
- Type
list
-
hashes
¶ A list of strings specifying the hash methods the sending device understands.
- Type
list
-
message_authentication_codes
¶ A list of strings specifying the message authentication codes that the sending device understands.
- Type
list
-
short_authentication_string
¶ A list of strings specifying the SAS methods the sending device (and the sending device’s user) understands.
- Type
list
-
from_device
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
hashes
: List[str]¶
-
key_agreement_protocols
: List[str]¶
-
message_authentication_codes
: List[str]¶
-
method
: str¶
-
short_authentication_string
: List[str]¶
-
-
class
nio.events.to_device.
OlmEvent
(source: Dict[str, Any], sender: str, sender_key: str, ciphertext: Dict[str, Any], transaction_id: Optional[str] = None)[source]¶ Bases:
nio.events.to_device.EncryptedToDeviceEvent
An Olm encrypted event.
Olm events are used to exchange end to end encrypted messages between two devices. They will mostly contain encryption keys to establish a Megolm session for a room.
nio users will never see such an event under normal circumstances since decrypting this event will produce an event of another type.
-
sender
¶ The fully-qualified ID of the user who sent this event.
- Type
str
-
sender_key
¶ The public key of the sender that was used to establish the encrypted session.
- Type
str, optional
-
ciphertext
¶ The undecrypted ciphertext of the event.
- Type
Dict[str, Any]
-
transaction_id
¶ The unique identifier that was used when the message was sent. Is only set if the message was sent from our own device, otherwise None.
- Type
str, optional
-
ciphertext
: Dict[str, Any]¶
-
classmethod
from_dict
(event_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
sender_key
: str¶
-
transaction_id
: Optional[str] = None¶
-
-
class
nio.events.to_device.
RoomKeyEvent
(source: Dict[str, Any], sender: str, sender_key: str, room_id: str, session_id: str, algorithm: str)[source]¶ Bases:
nio.events.to_device.ToDeviceEvent
Event containing a megolm room key that got sent to us.
-
sender
¶ The sender of the event.
- Type
str
-
sender_key
¶ The key of the sender that sent the event.
- Type
str
-
room_id
¶ The room ID of the room to which the session key belongs to.
- Type
str
-
session_id
¶ The session id of the session key.
- Type
str
-
algorithm
¶ The algorithm of the session key.
- Type
str
-
algorithm
: str¶
-
classmethod
from_dict
(event_dict, sender, sender_key)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
room_id
: str¶
-
sender_key
: str¶
-
session_id
: str¶
-
-
class
nio.events.to_device.
RoomKeyRequest
(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str, algorithm: str, room_id: str, sender_key: str, session_id: str)[source]¶ Bases:
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'.
-
algorithm
: str¶
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
room_id
: str¶
-
sender_key
: str¶
-
session_id
: str¶
-
-
class
nio.events.to_device.
RoomKeyRequestCancellation
(source: Dict[str, Any], sender: str, requesting_device_id: str, request_id: str)[source]¶ Bases:
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.
-
request_id
: str¶
-
requesting_device_id
: str¶
-
sender
: str¶
-
source
: Dict[str, Any]¶
-
classmethod
-
class
nio.events.to_device.
ToDeviceEvent
(source: Dict[str, Any], sender: str)[source]¶ Bases:
object
Base Event class for events that are sent using the to-device endpoint.
-
source
¶ The source dictionary of the event. This allows access to all the event fields in a non-secure way.
- Type
dict
-
sender
¶ The fully-qualified ID of the user who sent this event.
- Type
str
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
classmethod
parse_encrypted_event
(event_dict)[source]¶ Parse an encrypted to-device event.
Encrypted events may have different fields depending on the algorithm that was used to encrypt them.
This function checks the algorithm of the event and produces a higher level event from the provided dictionary.
- Parameters
event_dict (dict) – The dictionary representation of the encrypted event.
Returns None if the algorithm of the event is unknown.
-
classmethod
parse_event
(event_dict: Dict) → Optional[Union[nio.events.to_device.ToDeviceEvent, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]][source]¶ Parse a to-device event and create a higher level event object.
This function parses the type of the to-device event and produces a higher level event object representing the parsed event.
The event structure is checked for correctness and the event fields are type-checked. If this validation process fails for an event None will be returned.
- Parameters
event_dict (dict) – The dictionary representation of the event.
-
sender
: str¶
-
source
: Dict[str, Any]¶
-
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.
-
classmethod
-
class
nio.events.ephemeral.
Receipt
(event_id: str, receipt_type: str, user_id: str, timestamp: int)[source]¶ Bases:
object
Receipt of a user acknowledging an event.
If receipt_type is “m.read”, then it is a read receipt and shows the last event that a user has read.
-
event_id
¶ the ID of the event being acknowleged
- Type
str
-
receipt_type
¶ the type of receipt being received; this is commonly “m.read” for read receipts.
- Type
str
-
user_id
¶ the ID of the user who is acknowledging the event.
- Type
str
-
timestamp
¶ The timestamp the receipt was sent at.
- Type
int
-
event_id
: str¶
-
receipt_type
: str¶
-
timestamp
: int¶
-
user_id
: str¶
-
-
class
nio.events.ephemeral.
ReceiptEvent
(receipts: List[nio.events.ephemeral.Receipt])[source]¶ Bases:
nio.events.ephemeral.EphemeralEvent
Informs the client of changes in the newest events seen by users.
A ReceiptEvent can contain multiple event_ids seen by many different users. At the time of writing, all Receipts have a receipt_type of “m.read” and are read receipts, but this may change in the future.
-
classmethod
from_dict
(parsed_dict)[source]¶ Create an Ephemeral event from a dictionary.
- Parameters
parsed_dict (dict) – The dictionary representation of the event.
-
receipts
: List[nio.events.ephemeral.Receipt]¶
-
classmethod
-
class
nio.events.ephemeral.
TypingNoticeEvent
(users: List)[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.
-
users
: List¶
-
Account Data¶
nio Account data events.
Clients can store custom config data for their account on their homeserver.
This account data will be synced between different devices and can persist across installations on a particular device.
-
class
nio.events.account_data.
AccountDataEvent
[source]¶ Bases:
object
Abstract class for account data events.
-
class
nio.events.account_data.
FullyReadEvent
(event_id: str)[source]¶ Bases:
nio.events.account_data.AccountDataEvent
Read marker location event.
The current location of the user’s read marker in a room. This event appears in the user’s room account data for the room the marker is applicable for.
-
event_id
¶ The event id the user’s read marker is located at in the room.
- Type
str
-
event_id
: str¶
-
-
class
nio.events.account_data.
TagEvent
(tags: Dict[str, Optional[Dict[str, float]]])[source]¶ Bases:
nio.events.account_data.AccountDataEvent
Event representing the tags of a room.
Room tags may include:
m.favourite for favourite rooms
m.lowpriority for low priority room
A tag may have an order between 0 and 1, indicating the room’s position towards other rooms with the same tag.
The tags of the room
- Type
Dict[str, Optional[Dict[str, float]]]
-
and their contents.
-
tags
: Dict[str, Optional[Dict[str, float]]]¶
-
class
nio.events.account_data.
UnknownAccountDataEvent
(type: str, content: Dict[str, Any])[source]¶ Bases:
nio.events.account_data.AccountDataEvent
Account data event of an unknown type.
-
type
¶ The type of the event.
- Type
str
-
content
¶ The content of the event.
- Type
Dict
-
content
: Dict[str, Any]¶
-
type
: str¶
-
Building events¶
Nio Event Builders Module.
This module provides classes to easily create event dictionaries that
can be used with the clients’s room_send()
method, or room_create()
’s
inital_state
argument.
It also provides classes for some direct events such as to-device messages.
-
class
nio.event_builders.
EventBuilder
[source]¶ Bases:
object
The base class for event builders, should not be instancied.
Direct messages¶
Matrix direct messages module.
This module contains classes that can be used to send direct events to a Matrix homeserver.
-
class
nio.event_builders.direct_messages.
DummyMessage
(type: str, recipient: str, recipient_device: str, content: Dict)[source]¶ Bases:
nio.event_builders.direct_messages.ToDeviceMessage
A dummy to-device mssage that is sent to restart a Olm session.
-
class
nio.event_builders.direct_messages.
RoomKeyRequestMessage
(type: str, recipient: str, recipient_device: str, content: Dict, request_id: str, session_id: str, room_id: str, algorithm: str)[source]¶ Bases:
nio.event_builders.direct_messages.ToDeviceMessage
A to-device message that requests room keys from other devices.
-
request_id
¶ The unique request id that identifies this key request.
- Type
str
-
session_id
¶ The session id that uniquely identifies the room key.
- Type
str
-
room_id
¶ The room id of the room that the key belongs to.
- Type
str
-
algorithm
¶ The algorithm of the room key.
- Type
str
-
-
class
nio.event_builders.direct_messages.
ToDeviceMessage
(type: str, recipient: str, recipient_device: str, content: Dict)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A to-device message that can be sent to the homeserver.
-
type
¶ The type of the message.
- Type
str
-
recipient
¶ The user to whom we should sent this message.
- Type
str
-
recipient_device
¶ The device id of the device that the message should be sent to.
- Type
str
-
content
¶ The content that should be sent to the user.
- Type
Dict[Any, Any]
-
State events¶
Matrix state events module.
This module contains classes that can be used to easily create room state event dicts.
For example, to turn on encryption in a room with the HttpClient
or
AsyncClient
, the EnableEncryptionBuilder
class can be used:
>>> event_dict = EnableEncryptionBuilder().as_dict()
>>> client.room_send(
... room_id = "!test:example.com",
... message_type = event_dict["type"],
... content = event_dict["content"],
... )
-
class
nio.event_builders.state_events.
ChangeGuestAccessBuilder
(access: str)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to allow or forbid guest accounts in a room.
-
access
¶ Whether guests can join the room. Can be
can_join
orforbidden
.- Type
str
-
-
class
nio.event_builders.state_events.
ChangeHistoryVisibilityBuilder
(visibility: str)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to set what can users see from the room history.
-
visibility
¶ Can be: -
invited
: users can’t see events that happened before theywere invited to the room
joined
: users can’t see events that happened before theyjoined or accepted an invitation to the room.
shared
: users that joined the room can see the entireroom’s history
world_readable
: anyone can see the entire room’s history,including users that aren’t part of the room.
- Type
str
-
-
class
nio.event_builders.state_events.
ChangeJoinRulesBuilder
(rule: str)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to change who can join a room.
-
rule
¶ Can be
public
, meaning any user can join; orinvite
, meaning users must be invited to join the room. The matrix specification also reservesknock
andprivate
rules, which are currently not implemented.- Type
str
-
-
class
nio.event_builders.state_events.
ChangeNameBuilder
(name: str)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to change a room’s name.
-
name
¶ The name to set. Must not exceed 255 characters. Can be empty to remove the room’s name.
- Type
str
-
-
class
nio.event_builders.state_events.
ChangeTopicBuilder
(topic: str)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to change a room’s topic.
-
topic
¶ The topic to set. Can be empty to remove the room’s topic.
- Type
str
-
-
class
nio.event_builders.state_events.
EnableEncryptionBuilder
(algorithm: str = 'm.megolm.v1.aes-sha2', rotation_ms: int = 604800000, rotation_msgs: int = 100)[source]¶ Bases:
nio.event_builders.event_builder.EventBuilder
A state event sent to enable encryption in a room.
-
algorithm
¶ The algorithm to use for encrypting messages. The default
m.megolm.v1.aes-sha2
should not be changed.- Type
str
-
rotation_ms
¶ How long in milliseconds an encrypted session should be used before changing it. The default
604800000
(a week) is recommended.- Type
int
-
rotation_msgs
¶ How many messages can be received in a room before changing the encrypted session. The default
100
is recommended.- Type
int
-
Exceptions¶
-
exception
nio.exceptions.
LocalProtocolError
[source]¶ Bases:
nio.exceptions.ProtocolError
-
exception
nio.exceptions.
LocalTransportError
[source]¶ Bases:
nio.exceptions.ProtocolError
-
exception
nio.exceptions.
OlmUnverifiedDeviceError
(unverified_device, *args)[source]¶ Bases:
nio.exceptions.OlmTrustError
-
exception
nio.exceptions.
RemoteProtocolError
[source]¶ Bases:
nio.exceptions.ProtocolError
-
exception
nio.exceptions.
RemoteTransportError
[source]¶ Bases:
nio.exceptions.ProtocolError
Responses¶
-
class
nio.responses.
ContentRepositoryConfigError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response for a unsuccessful content repository config request.
-
message
: str¶
-
-
class
nio.responses.
ContentRepositoryConfigResponse
(upload_size: Optional[int] = None)[source]¶ A response for a successful content repository config request.
-
upload_size
¶ The maximum file size in bytes for an upload. If None, the limit is unknown.
- Type
Optional[int]
-
classmethod
from_dict
(parsed_dict: dict) → Union[nio.responses.ContentRepositoryConfigResponse, nio.responses.ErrorResponse][source]¶
-
upload_size
: Optional[int] = None¶
-
-
class
nio.responses.
DeleteDevicesAuthResponse
(session: str, flows: Dict, params: Dict)[source]¶ -
flows
: Dict¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.DeleteDevicesAuthResponse, nio.responses.ErrorResponse][source]¶
-
params
: Dict¶
-
session
: str¶
-
-
class
nio.responses.
DeleteDevicesError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
Device
(id: str, display_name: str, last_seen_ip: str, last_seen_date: datetime.datetime)[source]¶ -
display_name
: str¶
-
id
: str¶
-
last_seen_date
: datetime.datetime¶
-
last_seen_ip
: str¶
-
-
class
nio.responses.
DeviceList
(changed: List[str], left: List[str])[source]¶ -
changed
: List[str]¶
-
left
: List[str]¶
-
-
class
nio.responses.
DeviceOneTimeKeyCount
(curve25519: int, signed_curve25519: int)[source]¶ -
curve25519
: int¶
-
signed_curve25519
: int¶
-
-
class
nio.responses.
DevicesError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
DevicesResponse
(devices: List[nio.responses.Device])[source]¶ -
devices
: List[nio.responses.Device]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.DevicesResponse, nio.responses.ErrorResponse][source]¶
-
-
class
nio.responses.
DiscoveryInfoError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
DiscoveryInfoResponse
(homeserver_url: str, identity_server_url: Optional[str] = None)[source]¶ A response for a successful discovery info request.
-
homeserver_url
¶ The base URL of the homeserver corresponding to the requested domain.
- Type
str
-
identity_server_url
¶ The base URL of the identity server corresponding to the requested domain, if any.
- Type
str, optional
-
classmethod
from_dict
(parsed_dict: Dict[str, Any]) → Union[nio.responses.DiscoveryInfoResponse, nio.responses.DiscoveryInfoError][source]¶
-
homeserver_url
: str¶
-
identity_server_url
: Optional[str] = None¶
-
-
class
nio.responses.
DownloadError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response representing a unsuccessful download request.
-
message
: str¶
-
-
class
nio.responses.
DownloadResponse
(body: bytes, content_type: str, filename: Optional[str])[source]¶ A response representing a successful download request.
-
body
: bytes¶
-
content_type
: str¶
-
filename
: Optional[str]¶
-
classmethod
from_data
(data: bytes, content_type: str, filename: Optional[str] = None) → Union[nio.responses.DownloadResponse, nio.responses.DownloadError][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.
ErrorResponse
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → nio.responses.ErrorResponse[source]¶
-
message
: str¶
-
retry_after_ms
: Optional[int] = None¶
-
soft_logout
: bool = False¶
-
status_code
: Optional[int] = None¶
-
classmethod
-
class
nio.responses.
FileResponse
(body: bytes, content_type: str, filename: Optional[str])[source]¶ A response representing a successful file content request.
-
body
¶ The file’s content in bytes.
- Type
bytes
-
content_type
¶ The content MIME type of the file, e.g. “image/png”.
- Type
str
-
filename
¶ The file’s name returned by the server.
- Type
str, optional
-
body
: bytes¶
-
content_type
: str¶
-
filename
: Optional[str]¶
-
-
class
nio.responses.
JoinError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
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.
JoinedMembersResponse
(members: List[nio.responses.RoomMember], room_id: str)[source]¶ -
classmethod
from_dict
(parsed_dict: Dict[Any, Any], room_id: str) → Union[nio.responses.JoinedMembersResponse, nio.responses.ErrorResponse][source]¶
-
members
: List[nio.responses.RoomMember]¶
-
room_id
: str¶
-
classmethod
-
class
nio.responses.
JoinedRoomsError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response representing an unsuccessful joined rooms query.
-
message
: str¶
-
-
class
nio.responses.
JoinedRoomsResponse
(rooms: List[str])[source]¶ A response containing a list of joined rooms.
-
rooms
¶ The rooms joined by the account.
- Type
List[str]
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.JoinedRoomsResponse, nio.responses.ErrorResponse][source]¶
-
rooms
: List[str]¶
-
-
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.
KeysClaimResponse
(one_time_keys: Dict[Any, Any], failures: Dict[Any, Any], room_id: str = '')[source]¶ -
failures
: Dict[Any, Any]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any], room_id: str = '') → Union[nio.responses.KeysClaimResponse, nio.responses.ErrorResponse][source]¶
-
one_time_keys
: Dict[Any, Any]¶
-
room_id
: str = ''¶
-
-
class
nio.responses.
KeysQueryError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
KeysQueryResponse
(device_keys: Dict, failures: Dict)[source]¶ -
changed
: Dict[str, Dict[str, Any]]¶
-
device_keys
: Dict¶
-
failures
: Dict¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.KeysQueryResponse, nio.responses.ErrorResponse][source]¶
-
-
class
nio.responses.
KeysUploadError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
KeysUploadResponse
(curve25519_count: int, signed_curve25519_count: int)[source]¶ -
curve25519_count
: int¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.KeysUploadResponse, nio.responses.ErrorResponse][source]¶
-
signed_curve25519_count
: int¶
-
-
class
nio.responses.
LoginError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
LoginInfoError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
LoginInfoResponse
(flows: List[str])[source]¶ -
flows
: List[str]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.LoginInfoResponse, nio.responses.ErrorResponse][source]¶
-
-
class
nio.responses.
LoginResponse
(user_id: str, device_id: str, access_token: str)[source]¶ -
access_token
: str¶
-
device_id
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.LoginResponse, nio.responses.ErrorResponse][source]¶
-
user_id
: str¶
-
-
class
nio.responses.
LogoutError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
LogoutResponse
[source]¶ -
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.LogoutResponse, nio.responses.ErrorResponse][source]¶ Create a response for logout response from server.
-
classmethod
-
class
nio.responses.
PresenceGetError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ Response representing a unsuccessful get presence request.
-
message
: str¶
-
-
class
nio.responses.
PresenceGetResponse
(user_id: str, presence: str, last_active_ago: Optional[int], currently_active: Optional[bool], status_msg: Optional[str])[source]¶ Response representing a successful get presence request.
-
user_id
¶ The user´s id
- Type
str
-
presence
¶ The user’s presence state. One of: [“online”, “offline”, “unavailable”]
- Type
str
-
last_active_ago
¶ The length of time in milliseconds since an action was performed by this user. None if not set.
- Type
int, optional
-
currently_active
¶ Whether the user is currently active. None if not set.
- Type
bool, optional
-
status_msg
¶ The state message for this user. None if not set.
- Type
str, optional
-
currently_active
: Optional[bool]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any], user_id: str) → Union[nio.responses.PresenceGetResponse, nio.responses.PresenceGetError][source]¶
-
last_active_ago
: Optional[int]¶
-
presence
: str¶
-
status_msg
: Optional[str]¶
-
user_id
: str¶
-
-
class
nio.responses.
PresenceSetError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ Response representing a unsuccessful set presence request.
-
message
: str¶
-
-
class
nio.responses.
PresenceSetResponse
[source]¶ Response representing a successful set presence request.
-
class
nio.responses.
ProfileGetAvatarError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
ProfileGetAvatarResponse
(avatar_url: Optional[str] = None)[source]¶ Response representing a successful get avatar request.
-
avatar_url
¶ The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.
- Type
str, optional
-
avatar_url
: Optional[str] = None¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.ProfileGetAvatarResponse, nio.responses.ErrorResponse][source]¶
-
-
class
nio.responses.
ProfileGetDisplayNameError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
ProfileGetDisplayNameResponse
(displayname: Optional[str] = None)[source]¶ Response representing a successful get display name request.
-
displayname
¶ The display name of the user. None if the user doesn’t have a display name.
- Type
str, optional
-
displayname
: Optional[str] = None¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.ProfileGetDisplayNameResponse, nio.responses.ErrorResponse][source]¶
-
-
class
nio.responses.
ProfileGetError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
ProfileGetResponse
(displayname: Optional[str] = None, avatar_url: Optional[str] = None, other_info: Dict[Any, Any] = <factory>)[source]¶ Response representing a successful get profile request.
-
displayname
¶ The display name of the user. None if the user doesn’t have a display name.
- Type
str, optional
-
avatar_url
¶ The matrix content URI for the user’s avatar. None if the user doesn’t have an avatar.
- Type
str, optional
-
other_info
¶ Contains any other information returned for the user’s profile.
- Type
dict
-
avatar_url
: Optional[str] = None¶
-
displayname
: Optional[str] = None¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.ProfileGetResponse, nio.responses.ErrorResponse][source]¶
-
other_info
: Dict[Any, Any]¶
-
-
class
nio.responses.
ProfileSetAvatarError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
ProfileSetDisplayNameError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
RegisterResponse
(user_id: str, device_id: str, access_token: str)[source]¶ -
access_token
: str¶
-
device_id
: str¶
-
user_id
: str¶
-
-
class
nio.responses.
Response
[source]¶ -
property
elapsed
¶
-
end_time
: Optional[float] = None¶
-
start_time
: Optional[float] = None¶
-
timeout
: int = 0¶
-
transport_response
: Optional[nio.http.TransportResponse] = None¶
-
uuid
: str = ''¶
-
property
-
class
nio.responses.
RoomBanError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
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.
-
class
nio.responses.
RoomContextResponse
(room_id: str, start: str, end: str, event: Optional[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]], 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]
-
events_after
¶ A list of room events that happened just after the requested event, in chronological order.
- Type
List[Event]
-
end
: str¶
-
event
: Optional[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]]¶
-
events_before
: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]]¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any], room_id: str) → Union[nio.responses.RoomContextResponse, nio.responses.ErrorResponse][source]¶
-
room_id
: str¶
-
start
: str¶
-
state
: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]]¶
-
-
class
nio.responses.
RoomCreateError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response representing a unsuccessful create room request.
-
message
: str¶
-
-
class
nio.responses.
RoomCreateResponse
(room_id: str)[source]¶ Response representing a successful create room request.
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.RoomCreateResponse, nio.responses.RoomCreateError][source]¶
-
room_id
: str¶
-
classmethod
-
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.
RoomForgetResponse
(room_id: str)[source]¶ Response representing a successful forget room request.
-
room_id
: str¶
-
-
class
nio.responses.
RoomGetEventError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response representing an unsuccessful room get event request.
-
message
: str¶
-
-
class
nio.responses.
RoomGetEventResponse
[source]¶ A response indicating successful room get event request.
-
event
: nio.events.room_events.Event = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=None)¶
-
classmethod
from_dict
(parsed_dict: Dict[str, Any]) → Union[nio.responses.RoomGetEventResponse, nio.responses.RoomGetEventError][source]¶
-
-
class
nio.responses.
RoomGetStateError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]¶ A response representing an unsuccessful room state query.
-
class
nio.responses.
RoomGetStateEventError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: str = '')[source]¶ A response representing an unsuccessful room state query.
-
class
nio.responses.
RoomGetStateEventResponse
(content: Dict, event_type: str, state_key: str, room_id: str)[source]¶ A response containing the content of a specific bit of room state.
-
content
¶ The content of the state event.
- Type
Dict
-
event_type
¶ The type of the state event.
- Type
str
-
state_key
¶ The key of the state event.
- Type
str
-
room_id
¶ The ID of the room that the state event comes from.
- Type
str
-
content
: Dict¶
-
event_type
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[str, Any], event_type: str, state_key: str, room_id: str) → Union[nio.responses.RoomGetStateEventResponse, nio.responses.RoomGetStateEventError][source]¶
-
room_id
: str¶
-
state_key
: str¶
-
-
class
nio.responses.
RoomGetStateResponse
(events: List, room_id: str)[source]¶ A response containing the state of a room.
-
events
¶ The events making up the room state.
- Type
List
-
room_id
¶ The ID of the room.
- Type
str
-
events
: List¶
-
classmethod
from_dict
(parsed_dict: List[Dict[Any, Any]], room_id: str) → Union[nio.responses.RoomGetStateResponse, nio.responses.RoomGetStateError][source]¶
-
room_id
: str¶
-
-
class
nio.responses.
RoomInfo
(timeline: nio.responses.Timeline, state: List, ephemeral: List, account_data: List, summary: Optional[nio.responses.RoomSummary] = None, unread_notifications: Optional[nio.responses.UnreadNotifications] = None)[source]¶ -
account_data
: List¶
-
ephemeral
: List¶
-
static
parse_account_data
(event_dict)[source]¶ Parse the account data dictionary and produce a list of events.
-
state
: List¶
-
summary
: Optional[nio.responses.RoomSummary] = None¶
-
timeline
: nio.responses.Timeline¶
-
unread_notifications
: Optional[nio.responses.UnreadNotifications] = None¶
-
-
class
nio.responses.
RoomInviteError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
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.
-
message
: str¶
-
-
class
nio.responses.
RoomKeyRequestResponse
(request_id: str, session_id: str, room_id: str, algorithm: str)[source]¶ Response representing a successful room key request.
-
request_id
¶ The id of the that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.
- Type
str
-
session_id
¶ The id of the session that we requested.
- Type
str
-
room_id
¶ The id of the room that the session belongs to.
- Type
str
-
algorithm
¶ The encryption algorithm of the session.
- Type
str
-
algorithm
: str¶
-
classmethod
from_dict
(_, request_id, session_id, room_id, algorithm)[source]¶ Create a RoomKeyRequestResponse from a json response.
- Parameters
parsed_dict (Dict) – The dictionary containing the json response.
request_id (str) – The id of that uniquely identifies this key request that was requested, if we receive a to_device event it will contain the same request id.
session_id (str) – The id of the session that we requested.
room_id (str) – The id of the room that the session belongs to.
algorithm (str) – The encryption algorithm of the session.
-
request_id
: str¶
-
room_id
: str¶
-
session_id
: str¶
-
-
class
nio.responses.
RoomKickError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
RoomLeaveError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
RoomMember
(user_id: str, display_name: str, avatar_url: str)[source]¶ -
avatar_url
: str¶
-
display_name
: str¶
-
user_id
: str¶
-
-
class
nio.responses.
RoomMessagesError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, room_id: 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]¶ -
chunk
: List[Union[nio.events.room_events.Event, nio.events.misc.BadEvent, nio.events.misc.UnknownBadEvent]]¶
-
end
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any], room_id: str) → Union[nio.responses.RoomMessagesResponse, nio.responses.ErrorResponse][source]¶
-
room_id
: str¶
-
start
: str¶
-
-
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]¶ A response representing an unsuccessful room state sending request.
-
class
nio.responses.
RoomPutStateResponse
(event_id: str, room_id: str)[source]¶ A response indicating successful sending of room state.
-
event_id
: str¶
-
room_id
: str¶
-
-
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.
RoomReadMarkersResponse
(room_id: str)[source]¶ A response representing a successful room read markers request.
-
room_id
: str¶
-
-
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.
RoomRedactResponse
(event_id: str, room_id: str)[source]¶ -
-
event_id
: str¶
-
room_id
: str¶
-
-
class
nio.responses.
RoomResolveAliasError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ A response representing an unsuccessful room alias query.
-
message
: str¶
-
-
class
nio.responses.
RoomResolveAliasResponse
(room_alias: str, room_id: str, servers: List[str])[source]¶ A response containing the result of resolving an alias.
-
room_alias
¶ The alias of the room.
- Type
str
-
room_id
¶ The resolved id of the room.
- Type
str
-
servers
¶ Servers participating in the room.
- Type
List[str]
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any], room_alias: str) → Union[nio.responses.RoomResolveAliasResponse, nio.responses.ErrorResponse][source]¶
-
room_alias
: str¶
-
room_id
: str¶
-
servers
: List[str]¶
-
-
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.
RoomSendResponse
(event_id: str, room_id: str)[source]¶ -
-
event_id
: str¶
-
room_id
: str¶
-
-
class
nio.responses.
RoomSummary
(invited_member_count: Optional[int] = None, joined_member_count: Optional[int] = None, heroes: Optional[List[str]] = None)[source]¶ -
heroes
: Optional[List[str]] = None¶
-
invited_member_count
: Optional[int] = None¶
-
joined_member_count
: Optional[int] = None¶
-
-
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.
RoomTypingResponse
(room_id: str)[source]¶ A response representing a successful room typing request.
-
room_id
: str¶
-
-
class
nio.responses.
RoomUnbanError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
Rooms
(invite: Dict[str, ForwardRef(‘InviteInfo’)], join: Dict[str, ForwardRef(‘RoomInfo’)], leave: Dict[str, ForwardRef(‘RoomInfo’)])[source]¶ -
invite
: Dict[str, nio.responses.InviteInfo]¶
-
join
: Dict[str, nio.responses.RoomInfo]¶
-
leave
: Dict[str, nio.responses.RoomInfo]¶
-
Response representing unsuccessful group sessions sharing request.
Response representing a successful group sessions sharing request.
The room id of the group session.
- Type
str
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]]
Create a response from the json dict the server returns.
- Parameters
parsed_dict (Dict) – The dict containing the raw json response.
room_id (str) – The room id of the room to which the group session belongs to.
users_shared_with (Set[Tuple[str, str]]) – A set containing a tuple of user id device id pairs with whom we shared the group session in this request.
-
room_id
: str¶
-
users_shared_with
: set¶
-
class
nio.responses.
SyncError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
SyncResponse
(next_batch: str, rooms: nio.responses.Rooms, device_key_count: nio.responses.DeviceOneTimeKeyCount, device_list: nio.responses.DeviceList, to_device_events: List[nio.events.to_device.ToDeviceEvent], presence_events: List[nio.events.presence.PresenceEvent])[source]¶ -
device_key_count
: nio.responses.DeviceOneTimeKeyCount¶
-
device_list
: nio.responses.DeviceList¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.SyncResponse, nio.responses.ErrorResponse][source]¶
-
next_batch
: str¶
-
presence_events
: List[nio.events.presence.PresenceEvent]¶
-
rooms
: nio.responses.Rooms¶
-
to_device_events
: List[nio.events.to_device.ToDeviceEvent]¶
-
-
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.
-
message
: str¶
-
-
class
nio.responses.
ThumbnailResponse
(body: bytes, content_type: str, filename: Optional[str])[source]¶ A response representing a successful thumbnail request.
-
body
: bytes¶
-
content_type
: str¶
-
filename
: Optional[str]¶
-
classmethod
from_data
(data: bytes, content_type: str, filename: Optional[str] = None) → Union[nio.responses.ThumbnailResponse, nio.responses.ThumbnailError][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.
Timeline
(events: List, limited: bool, prev_batch: str)[source]¶ -
events
: List¶
-
limited
: bool¶
-
prev_batch
: str¶
-
-
class
nio.responses.
ToDeviceError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False, to_device_message: Optional[nio.event_builders.direct_messages.ToDeviceMessage] = None)[source]¶ Response representing a unsuccessful room key request.
-
to_device_message
: Optional[nio.event_builders.direct_messages.ToDeviceMessage] = None¶
-
-
class
nio.responses.
ToDeviceResponse
(to_device_message: nio.event_builders.direct_messages.ToDeviceMessage)[source]¶ Response representing a successful room key request.
-
classmethod
from_dict
(parsed_dict, message)[source]¶ Create a ToDeviceResponse from a json response.
-
to_device_message
: nio.event_builders.direct_messages.ToDeviceMessage¶
-
classmethod
-
class
nio.responses.
UpdateDeviceError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
UpdateReceiptMarkerError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
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.
-
message
: str¶
-
-
class
nio.responses.
UploadFilterError
(message: str, status_code: Optional[int] = None, retry_after_ms: Optional[int] = None, soft_logout: bool = False)[source]¶ -
message
: str¶
-
-
class
nio.responses.
UploadFilterResponse
(filter_id: str)[source]¶ Response representing a successful filter upload request.
-
filter_id
¶ A filter ID that may be used in future requests to restrict which events are returned to the client.
- Type
str
-
filter_id
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.UploadFilterResponse, nio.responses.UploadFilterError][source]¶
-
-
class
nio.responses.
UploadResponse
(content_uri: str)[source]¶ A response representing a successful upload request.
-
content_uri
: str¶
-
classmethod
from_dict
(parsed_dict: Dict[Any, Any]) → Union[nio.responses.UploadResponse, nio.responses.ErrorResponse][source]¶
-
Storage¶
Nio storage module.
This module contains storage classes that are used to store encryption devices, encryption keys and the trust state of devices.
The module contains three store implementations one using a Sqlite database and plaintext files to store keys and the truststate of devices, one that uses a pure Sqlite database and one that stores the Sqlite database in memory.
User provided store types can be implemented by overriding the methods provided in the MatrixStore base class.
-
class
nio.store.
MatrixStore
(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]¶ Storage class for matrix state.
-
add_outgoing_key_request
(key_request: nio.crypto.key_request.OutgoingKeyRequest) → None[source]¶ Add an outgoing key request to the store.
-
blacklist_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Mark a device as blacklisted.
- Parameters
device (OlmDevice) – The device that will be marked as blacklisted
Returns True if the device was blacklisted, False otherwise, e.g. if the device was already blacklisted.
-
ignore_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Mark a device as ignored.
- Parameters
device (OlmDevice) – The device that will be marked as blacklisted
Returns True if the device was ignored, False otherwise, e.g. if the device was already ignored.
-
ignore_devices
(devices: List[nio.crypto.device.OlmDevice]) → None[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: nio.crypto.device.OlmDevice) → bool[source]¶ Check if a device is blacklisted.
- Parameters
device (OlmDevice) – The device that will be checked if it’s blacklisted.
-
is_device_ignored
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Check if a device is ignored.
- Parameters
device (OlmDevice) – The device that will be checked if it’s ignored.
-
is_device_verified
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Check if a device is verified.
- Parameters
device (OlmDevice) – The device that will be checked if it’s verified.
-
load_account
() → Optional[nio.crypto.sessions.OlmAccount][source]¶ Load the Olm account from the database.
- Returns
OlmAccount
object, orNone
if it wasn’t found for thecurrent device_id.
-
load_device_keys
() → nio.crypto.device.DeviceStore[source]¶ Load all the device keys from the database.
Returns DeviceStore containing the OlmDevices with the device keys.
-
load_encrypted_rooms
()[source]¶ Load the set of encrypted rooms for this account.
- Returns
Set
containing room ids of encrypted rooms.
-
load_inbound_group_sessions
() → nio.crypto.memorystores.GroupSessionStore[source]¶ Load all Olm sessions from the database.
- Returns
GroupSessionStore
object, containing all the loaded sessions.
-
load_outgoing_key_requests
()[source]¶ Load the set of outgoing key requests for this account.
- Returns
Set
containing request ids of key requests.
-
load_sessions
() → nio.crypto.memorystores.SessionStore[source]¶ Load all Olm sessions from the database.
- Returns
SessionStore
object, containing all the loaded sessions.
-
remove_outgoing_key_request
(key_request: nio.crypto.key_request.OutgoingKeyRequest) → None[source]¶ Remove an active outgoing key request from the store.
-
save_account
(account)[source]¶ Save the provided Olm account to the database.
- Parameters
account (OlmAccount) – The olm account that will be pickled and saved in the database.
-
save_device_keys
(device_keys)[source]¶ Save the provided device keys to the database.
- Parameters
device_keys (Dict[str, Dict[str, OlmDevice]]) – A dictionary containing a mapping from a user id to a dictionary containing a mapping of a device id to a OlmDevice.
-
save_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.
-
unblacklist_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Unmark a device as blacklisted.
- Parameters
device (OlmDevice) – The device that will be unmarked as blacklisted
-
unignore_device
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Unmark a device as ignored.
- Parameters
device (OlmDevice) – The device that will be marked as blacklisted
Returns True if the device was unignored, False otherwise, e.g. if the device wasn’t ignored in the first place.
-
-
class
nio.store.
DefaultStore
(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]¶ Bases:
nio.store.database.MatrixStore
The default nio Matrix Store.
This store uses an Sqlite database as the main storage format while device trust state is stored in plaintext files using a format similar to the ssh known_hosts file format. The files will be created in the same directory as the main Sqlite database.
One such file is created for each of the 3 valid states (verified, blacklisted, ignored). If a device isn’t found in any of those files the verification state is considered to be unset.
- Parameters
user_id (str) – The fully-qualified ID of the user that owns the store.
device_id (str) – The device id of the user’s device.
store_path (str) – The path where the store should be stored.
pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.
database_name (str, optional) – The file-name of the database that should be used.
-
class
nio.store.
SqliteStore
(user_id: str, device_id: str, store_path: str, pickle_key: str = '', database_name: str = '')[source]¶ Bases:
nio.store.database.MatrixStore
The Sqlite only nio Matrix Store.
This store uses an Sqlite database as the main storage format as well as the store format for the trust state.
- Parameters
user_id (str) – The fully-qualified ID of the user that owns the store.
device_id (str) – The device id of the user’s device.
store_path (str) – The path where the store should be stored.
pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.
database_name (str, optional) – The file-name of the database that should be used.
-
class
nio.store.
SqliteMemoryStore
(user_id, device_id, pickle_key='')[source]¶ Bases:
nio.store.database.SqliteStore
The Sqlite only nio Matrix Store.
This store uses an Sqlite database as the main storage format as well as the store format for the trust state. The Sqlite database will be stored only in memory and all the data will be lost after the object is deleted.
- Parameters
user_id (str) – The fully-qualified ID of the user that owns the store.
device_id (str) – The device id of the user’s device.
pickle_key (str, optional) – A passphrase that will be used to encrypt encryption keys while they are in storage.
Encryption¶
nio encryption module.
Encryption is handled mostly transparently to the user.
The main thing users need to worry about is device verification.
While device verification is handled in the Client classes of nio the classes that are used to introspect OlmDevices or device authentication sessions are documented here.
-
class
nio.crypto.
DeviceStore
[source]¶ A store that holds olm devices in memory.
The DeviceStore class implements the iter method, devices can be iterated over normaly using:
>>> for device in device_store: ... print(device.user_id, device.device_id)
To get only non-deleted devices of a user the active_user_devices method can be used:
>>> for device in device_store.active_user_devices("@bob:example.org"): ... print(device.user_id, device.device_id)
-
active_user_devices
(user_id: str) → Iterator[nio.crypto.device.OlmDevice][source]¶ Get all the non-deleted devices of a user.
- Parameters
user_id (str) – The user for which we would like to get the devices for.
This returns an iterator over all the non-deleted devices of the given user.
-
add
(device: nio.crypto.device.OlmDevice) → bool[source]¶ Add the given device to the store.
- Parameters
device (OlmDevice) – The device that should be added to the store.
Returns True if the device was added to the store, False if it already was in the store.
-
device_from_sender_key
(user_id: str, sender_key: str) → Optional[nio.crypto.device.OlmDevice][source]¶ Get a non-deleted device of a user with the matching sender key.
- Parameters
user_id (str) – The user id of the device owner.
sender_key (str) – The encryption key that is owned by the device,
a curve25519 public key. (usually) –
-
property
users
¶ Get the list of users that the device store knows about.
-
-
class
nio.crypto.
OlmDevice
(user_id: str, device_id: str, keys: Dict[str, str], display_name: str = '', deleted: bool = False, trust_state: nio.crypto.device.TrustState = <TrustState.unset: 0>)[source]¶ Class holding info about users Olm devices.
OlmDevices represent user devices with which we can communicate in an encrypted manner. To do so an OlmDevice needs to have its trust state set. The trust state can be set to one of “verified”, “ignored”, or “blacklisted”.
Note that the trust state should never be moddified directly on an OlmDevice, all the attributes here are read only.
The trust state can be changed by pasing the OlmDevice to a nio Client or a MatrixStore class.
-
user_id
¶ The id of the user that the device belongs to.
- Type
str
-
device_id
¶ The device id that combined with the user id uniquely identifies the device.
- Type
str
-
keys
¶ A dictionary containing the type and the public part of this devices encryption keys.
- Type
Dict
-
display_name
¶ The human readable name of this device.
- Type
str
-
deleted
¶ A boolean signaling if this device has been deleted by its owner.
- Type
bool
-
trust_state
¶ The trust state of this device.
- Type
-
property
blacklisted
¶ Is the device blacklisted.
-
property
curve25519
¶ The curve25519 key of the device.
-
property
ed25519
¶ The ed25519 fingerprint key of the device.
-
property
id
¶ The device id.
Same as the device_id attribute.
-
property
ignored
¶ Is the device ignored.
-
property
verified
¶ Is the device verified.
-
-
class
nio.crypto.
TrustState
(value)[source]¶ The device trust state.
An Enum holding differing values that a device trust state can be in.
-
class
nio.crypto.
Sas
(*args: Any, **kwargs: Any)[source]¶ Matrix Short Authentication String class.
This class implements a state machine to handle device verification using short authentication strings.
-
we_started_it
¶ Is true if the verification process was started by us, otherwise false.
- Type
bool
-
sas_accepted
¶ Is true if we accepted that the short authentication string matches on both devices.
- Type
bool
-
verified_devices
¶ The list of device ids that were verified during the verification process.
- Type
List[str]
- Parameters
own_user (str) – The user id of our own user.
own_device (str) – The device id of our own user.
own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.
other_olm_device (OlmDevice) – The OlmDevice which we would like to verify.
transaction_id (str, optional) – A string that will uniquely identify this verification process. A random and unique string will be generated if one isn’t provided.
short_auth_string (List[str], optional) – A list of valid short authentication methods that the client would like to allow for this authentication session. By default the ‘emoji’ and ‘decimal’ methods are allowed.
-
accept_verification
() → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Create a content dictionary to accept the verification offer.
-
property
canceled
¶ Is the verification request canceled.
-
classmethod
from_key_verification_start
(own_user: str, own_device: str, own_fp_key: str, other_olm_device: nio.crypto.device.OlmDevice, event: nio.events.to_device.KeyVerificationStart) → nio.crypto.sas.Sas[source]¶ Create a SAS object from a KeyVerificationStart event.
- Parameters
own_user (str) – The user id of our own user.
own_device (str) – The device id of our own user.
own_fp_key (str) – The fingerprint key of our own device that will be verified by the other client.
other_olm_device (OlmDevice) – The Olm device of the other user that should be verified.
event (KeyVerificationStart) – The event that we received from the other device to start the key verification process.
-
get_cancellation
() → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Create a dictionary containing our verification cancellation.
-
get_decimals
() → Tuple[int, …][source]¶ Get the decimal short authentication string.
Returns a tuple that contains three 4 digit integer numbers that represent the short authentication string.
-
get_emoji
() → List[Tuple[str, str]][source]¶ Get the emoji short authentication string.
Returns a list of tuples that contain the emoji and the description of the emoji of the short authentication string.
-
get_mac
() → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Create a dictionary containing our MAC.
-
receive_mac_event
(event)[source]¶ Receive a KeyVerificationMac event.
- Parameters
event (KeyVerificationMac) – The MAC event that was received for this SAS session.
Create a dictionary containing our public key.
-
start_verification
() → nio.event_builders.direct_messages.ToDeviceMessage[source]¶ Create a content dictionary to start the verification.
-
property
timed_out
¶ Did the verification process time out.
-
property
verified
¶ Is the device verified and the request done.
-