mautrix.types

class mautrix.types.JSON

A union type that covers all JSON-serializable data.

alias of str | int | float | bool | None | Dict[str, JSON] | List[JSON]

class mautrix.types.UserID

A Matrix user ID (@user:example.com)

alias of str

class mautrix.types.EventID

A Matrix event ID ($base64 or $legacyid:example.com)

alias of str

class mautrix.types.RoomID

An internal Matrix room ID (!randomstring:example.com)

alias of str

class mautrix.types.RoomAlias

A Matrix room address (#alias:example.com)

alias of str

class mautrix.types.FilterID

A filter ID returned by POST /filter (mautrix.client.ClientAPI.create_filter())

alias of str

class mautrix.types.ContentURI

A Matrix content URI, used by the content repository.

alias of str

class mautrix.types.SyncToken

A next_batch token from a /sync response (mautrix.client.ClientAPI.sync())

alias of str

class mautrix.types.DeviceID

A Matrix device ID. Arbitrary, potentially client-specified string.

alias of str

class mautrix.types.SessionID

A Megolm session ID.

alias of str

class mautrix.types.SigningKey

A ed25519 public key as unpadded base64

alias of str

class mautrix.types.IdentityKey

A curve25519 public key as unpadded base64

alias of str

class mautrix.types.DiscoveryInformation

.well-known discovery information, as specified in the GET /.well-known/matrix/client endpoint

homeserver: DiscoveryServer | None
identity_server: DiscoveryServer | None
integrations: DiscoveryServer | None
class mautrix.types.DiscoveryIntegrations
managers: List[DiscoveryIntegrationServer]
class mautrix.types.DiscoveryIntegrationServer
ui_url: str | None
api_url: str | None
class mautrix.types.DiscoveryServer
base_url: str | None
class mautrix.types.LoginFlow

A login flow, as specified in the GET /login endpoint

type: LoginType
class mautrix.types.LoginFlowList
get_first_of_type(*types)
Parameters:

types (LoginType)

Return type:

LoginFlow | None

supports_type(*types)
Parameters:

types (LoginType)

Return type:

bool

flows: List[LoginFlow]
class mautrix.types.LoginResponse

The response for a login request, as specified in the POST /login endpoint

user_id: UserID
device_id: DeviceID
access_token: str
well_known: DiscoveryInformation
class mautrix.types.LoginType

A login type, as specified in the POST /login endpoint

PASSWORD: LoginType = <LoginType.PASSWORD: 'm.login.password'>
TOKEN: LoginType = <LoginType.TOKEN: 'm.login.token'>
SSO: LoginType = <LoginType.SSO: 'm.login.sso'>
APPSERVICE: LoginType = <LoginType.APPSERVICE: 'm.login.application_service'>
UNSTABLE_JWT: LoginType = <LoginType.UNSTABLE_JWT: 'org.matrix.login.jwt'>
DEVTURE_SHARED_SECRET: LoginType = <LoginType.DEVTURE_SHARED_SECRET: 'com.devture.shared_secret_auth'>
class mautrix.types.MatrixUserIdentifier

A client can identify a user using their Matrix ID. This can either be the fully qualified Matrix user ID, or just the localpart of the user ID.

user: str
type: UserIdentifierType
class mautrix.types.PhoneIdentifier

A client can identify a user using a phone number associated with the user’s account, where the phone number was previously associated using the /account/3pid API. The phone number can be passed in as entered by the user; the homeserver will be responsible for canonicalising it. If the client wishes to canonicalise the phone number, then it can use the m.id.thirdparty identifier type with a medium of msisdn instead.

country: str
phone: str
type: UserIdentifierType
class mautrix.types.ThirdPartyIdentifier

A client can identify a user using a 3PID associated with the user’s account on the homeserver, where the 3PID was previously associated using the /account/3pid API. See the 3PID Types Appendix for a list of Third-party ID media.

medium: str
address: str
type: UserIdentifierType
class mautrix.types.UserIdentifierType

A user identifier type, as specified in the Identifier types section of the login spec.

MATRIX_USER: UserIdentifierType = <UserIdentifierType.MATRIX_USER: 'm.id.user'>
THIRD_PARTY: UserIdentifierType = <UserIdentifierType.THIRD_PARTY: 'm.id.thirdparty'>
PHONE: UserIdentifierType = <UserIdentifierType.PHONE: 'm.id.phone'>
class mautrix.types.WhoamiResponse

The response for a whoami request, as specified in the GET /account/whoami endpoint

user_id: UserID
device_id: DeviceID | None
is_guest: bool
class mautrix.types.ClaimKeysResponse
one_time_keys: Dict[UserID, Dict[DeviceID, Dict[KeyID, Any]]]
failures: Dict[str, Any]
class mautrix.types.CrossSigner

A tuple containing a user ID and a signing key they own.

The key can either be a device-owned signing key, or one of the user’s cross-signing keys.

static __new__(_cls, user_id, key)

Create new instance of CrossSigner(user_id, key)

Parameters:
key: SigningKey

Alias for field number 1

user_id: UserID

Alias for field number 0

class mautrix.types.CrossSigningKeys
property first_ed25519_key: SigningKey | None
property first_key: SigningKey | None
first_key_with_algorithm(alg)
Parameters:

alg (EncryptionKeyAlgorithm)

Return type:

SigningKey | None

user_id: UserID
usage: List[CrossSigningUsage]
keys: Dict[KeyID, SigningKey]
signatures: Dict[UserID, Dict[KeyID, Signature]]
class mautrix.types.CrossSigningUsage
MASTER: CrossSigningUsage = <CrossSigningUsage.MASTER: 'master'>
SELF: CrossSigningUsage = <CrossSigningUsage.SELF: 'self_signing'>
USER: CrossSigningUsage = <CrossSigningUsage.USER: 'user_signing'>
class mautrix.types.DecryptedOlmEvent
keys: OlmEventKeys
recipient: UserID
recipient_keys: OlmEventKeys
sender_device: DeviceID | None
sender_key: IdentityKey
class mautrix.types.DeviceIdentity
user_id: UserID
device_id: DeviceID
identity_key: IdentityKey
signing_key: SigningKey
trust: TrustState
deleted: bool
name: str
class mautrix.types.DeviceKeys
property curve25519: IdentityKey | None
property ed25519: SigningKey | None
user_id: UserID
device_id: DeviceID
algorithms: List[EncryptionAlgorithm]
keys: Dict[KeyID, str]
signatures: Dict[UserID, Dict[KeyID, Signature]]
unsigned: UnsignedDeviceInfo
class mautrix.types.OlmEventKeys
ed25519: SigningKey
class mautrix.types.QueryKeysResponse
device_keys: Dict[UserID, Dict[DeviceID, DeviceKeys]]
master_keys: Dict[UserID, CrossSigningKeys]
self_signing_keys: Dict[UserID, CrossSigningKeys]
user_signing_keys: Dict[UserID, CrossSigningKeys]
failures: Dict[str, Any]
class mautrix.types.TOFUSigningKey

A tuple representing a single cross-signing key. The first value is the current key, and the second value is the first seen key. If the values don’t match, it means the key is not valid for trust-on-first-use.

static __new__(_cls, key, first)

Create new instance of TOFUSigningKey(key, first)

Parameters:
first: SigningKey

Alias for field number 1

key: SigningKey

Alias for field number 0

class mautrix.types.TrustState
__new__(value)
classmethod parse(val)
Parameters:

val (str)

Return type:

TrustState

BLACKLISTED = -100
UNVERIFIED = 0
UNKNOWN_DEVICE = 10
FORWARDED = 20
CROSS_SIGNED_UNTRUSTED = 50
CROSS_SIGNED_TOFU = 100
CROSS_SIGNED_TRUSTED = 200
VERIFIED = 300
class mautrix.types.UnsignedDeviceInfo
device_display_name: str | None
class mautrix.types.AccountDataEvent
classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (JSON)

Return type:

AccountDataEvent

static deserialize_content(data)
Parameters:

data (JSON)

Return type:

RoomTagAccountDataEventContent | Dict[UserID, List[RoomID]] | SecretStorageDefaultKeyEventContent | EncryptedAccountDataEventContent | KeyMetadata | Obj

content: RoomTagAccountDataEventContent | Dict[UserID, List[RoomID]] | SecretStorageDefaultKeyEventContent | EncryptedAccountDataEventContent | KeyMetadata | Obj
class mautrix.types.ASToDeviceEvent
to_user_id: UserID
to_device_id: DeviceID
class mautrix.types.AudioInfo

Information about an audio message.

duration: int
class mautrix.types.BaseEvent

Base event class. The only things an event must have are content and event type.

content: Obj
type: EventType
class mautrix.types.BaseFileInfo
mimetype: str
size: int
class mautrix.types.BaseMessageEventContent

Base event content for all m.room.message-type events.

msgtype: MessageType
body: str
external_url: str
class mautrix.types.BaseMessageEventContentFuncs

Base class for the contents of all message-type events (currently m.room.message and m.sticker). Contains relation helpers.

get_edit()
Return type:

EventID | None

get_reply_to()
Return type:

EventID | None

get_thread_parent()
Return type:

EventID | None

property relates_to: RelatesTo
serialize()
Return type:

JSON

set_edit(edits)
Parameters:

edits (EventID | MessageEvent)

Return type:

None

set_reply(reply_to, **kwargs)
Parameters:

reply_to (EventID | MessageEvent)

Return type:

None

set_thread_parent(thread_parent, last_event_in_thread=None, disable_reply_fallback=False, **kwargs)
Parameters:
Return type:

None

trim_reply_fallback()
Return type:

None

body: str
class mautrix.types.BaseRoomEvent

Base room event class. Room events must have a room ID, event ID, sender and timestamp in addition to the content and type in the base event.

room_id: RoomID
event_id: EventID
sender: UserID
timestamp: int
class mautrix.types.BaseUnsigned

Base unsigned information.

age: int
class mautrix.types.BatchSendEvent

Base event class for events sent via a batch send request.

sender: UserID
timestamp: int
content: Any
event_id: EventID | None
class mautrix.types.BatchSendStateEvent

State events to be used as initial state events on batch send events. These never need to be deserialized.

state_key: str
class mautrix.types.BeeperMessageStatusEvent
content: BeeperMessageStatusEventContent
class mautrix.types.BeeperMessageStatusEventContent
relates_to: RelatesTo
network: str
status: MessageStatus | None
reason: MessageStatusReason | None
error: str | None
message: str | None
last_retry: EventID | None
class mautrix.types.CallAnswerEventContent
call_id: str
version: int
answer: CallData
party_id: str | None
class mautrix.types.CallCandidate
candidate: str
sdp_m_line_index: int
sdp_mid: str
class mautrix.types.CallCandidatesEventContent
call_id: str
version: int
candidates: List[CallCandidate]
party_id: str | None
class mautrix.types.CallData
sdp: str
type: CallDataType
class mautrix.types.CallDataType
value: Any
class mautrix.types.CallEvent
classmethod deserialize(data, event_type=None)

Convert the given data parsed from JSON into an object of this type.

Parameters:
Return type:

CallEvent

content: T
class mautrix.types.CallHangupEventContent
call_id: str
version: int
reason: CallHangupReason
party_id: str | None
class mautrix.types.CallHangupReason
value: Any
class mautrix.types.CallInviteEventContent
call_id: str
lifetime: int
version: int
offer: CallData
party_id: str | None
invitee: UserID | None
class mautrix.types.CallNegotiateEventContent
call_id: str
version: int
lifetime: int
party_id: str
description: CallData
class mautrix.types.CallRejectEventContent
call_id: str
version: int
party_id: str
class mautrix.types.CallSelectAnswerEventContent
call_id: str
version: int
party_id: str
selected_party_id: str
class mautrix.types.CanonicalAliasStateEventContent

The content of a m.room.canonical_alias event (EventType.ROOM_CANONICAL_ALIAS).

This event is used to inform the room about which alias should be considered the canonical one, and which other aliases point to the room. This could be for display purposes or as suggestion to users which alias to use to advertise and access the room.

See also: m.room.canonical_alias in the spec

canonical_alias: RoomAlias
alt_aliases: List[RoomAlias]
class mautrix.types.EncryptedEvent

A m.room.encrypted event

property unsigned: BaseUnsigned
content: EncryptedEventContent
class mautrix.types.EncryptedFile
key: JSONWebKey
iv: str
hashes: Dict[str, str]
url: ContentURI | None
version: str
class mautrix.types.EncryptedMegolmEventContent

The content of an m.room.encrypted event

property device_id: DeviceID | None

Deprecated since version 0.17.0.

Matrix v1.3 deprecated the device_id and sender_key fields in megolm events.

property relates_to: RelatesTo
property sender_key: IdentityKey | None

Deprecated since version 0.17.0.

Matrix v1.3 deprecated the device_id and sender_key fields in megolm events.

ciphertext: str
session_id: SessionID
algorithm: EncryptionAlgorithm
class mautrix.types.EncryptedOlmEventContent
ciphertext: Dict[str, OlmCiphertext]
sender_key: IdentityKey
algorithm: EncryptionAlgorithm
class mautrix.types.EncryptionAlgorithm
OLM_V1: EncryptionAlgorithm = <EncryptionAlgorithm.OLM_V1: 'm.olm.v1.curve25519-aes-sha2'>
MEGOLM_V1: EncryptionAlgorithm = <EncryptionAlgorithm.MEGOLM_V1: 'm.megolm.v1.aes-sha2'>
class mautrix.types.EncryptionKeyAlgorithm
CURVE25519: EncryptionKeyAlgorithm = <EncryptionKeyAlgorithm.CURVE25519: 'curve25519'>
ED25519: EncryptionKeyAlgorithm = <EncryptionKeyAlgorithm.ED25519: 'ed25519'>
SIGNED_CURVE25519: EncryptionKeyAlgorithm = <EncryptionKeyAlgorithm.SIGNED_CURVE25519: 'signed_curve25519'>
class mautrix.types.EventType

An immutable enum-like class that represents a specific Matrix event type.

In addition to the plain event type string, this also includes the context that the event is used in (see: Class). Comparing EventType instances for equality will check both the type string and the class.

The idea behind the wrapper is that incoming event parsers will always create an EventType instance with the correct class, regardless of what the usual context for the event is. Then when the event is being handled, the type will not be equal to EventType instances with a different class. For example, if someone sends a non-state m.room.name event, checking if event.type == EventType.ROOM_NAME would return False, because the class would be different. Bugs caused by not checking the context of an event (especially state event vs message event) were very common in the past, and using a wrapper like this helps prevent them.

t: str
t_class: Class
ALL = EventType("__ALL__", EventType.Class.UNKNOWN)
BEEPER_MESSAGE_STATUS = EventType("com.beeper.message_send_status", EventType.Class.MESSAGE)
BEEPER_ROOM_KEY_ACK = EventType("com.beeper.room_key.ack", EventType.Class.TO_DEVICE)
CALL_ANSWER = EventType("m.call.answer", EventType.Class.MESSAGE)
CALL_CANDIDATES = EventType("m.call.candidates", EventType.Class.MESSAGE)
CALL_HANGUP = EventType("m.call.hangup", EventType.Class.MESSAGE)
CALL_INVITE = EventType("m.call.invite", EventType.Class.MESSAGE)
CALL_NEGOTIATE = EventType("m.call.negotiate", EventType.Class.MESSAGE)
CALL_REJECT = EventType("m.call.reject", EventType.Class.MESSAGE)
CALL_SELECT_ANSWER = EventType("m.call.select_answer", EventType.Class.MESSAGE)
CROSS_SIGNING_MASTER = EventType("m.cross_signing.master", EventType.Class.ACCOUNT_DATA)
CROSS_SIGNING_SELF_SIGNING = EventType("m.cross_signing.self_signing", EventType.Class.ACCOUNT_DATA)
CROSS_SIGNING_USER_SIGNING = EventType("m.cross_signing.user_signing", EventType.Class.ACCOUNT_DATA)
class Class

The context that an event type is used in.

__new__(value)
UNKNOWN = 'unknown'
STATE = 'state'

Room state events

MESSAGE = 'message'

Room message events, i.e. room events that are not state events

ACCOUNT_DATA = 'account_data'

Account data events, user-specific storage used for synchronizing info between clients. Can be global or room-specific.

EPHEMERAL = 'ephemeral'

Ephemeral events. Currently only typing notifications, read receipts and presence are in this class, as custom ephemeral events are not yet possible.

TO_DEVICE = 'to_device'

Device-to-device events, primarily used for exchanging encryption keys

DIRECT = EventType("m.direct", EventType.Class.ACCOUNT_DATA)
FORWARDED_ROOM_KEY = EventType("m.forwarded_room_key", EventType.Class.TO_DEVICE)
IGNORED_USER_LIST = EventType("m.ignored_user_list", EventType.Class.ACCOUNT_DATA)
MEGOLM_BACKUP_V1 = EventType("m.megolm_backup.v1", EventType.Class.ACCOUNT_DATA)
ORG_MATRIX_ROOM_KEY_WITHHELD = EventType("org.matrix.room_key.withheld", EventType.Class.TO_DEVICE)
PRESENCE = EventType("m.presence", EventType.Class.EPHEMERAL)
PUSH_RULES = EventType("m.push_rules", EventType.Class.ACCOUNT_DATA)
REACTION = EventType("m.reaction", EventType.Class.MESSAGE)
RECEIPT = EventType("m.receipt", EventType.Class.EPHEMERAL)
ROOM_AVATAR = EventType("m.room.avatar", EventType.Class.STATE)
ROOM_CANONICAL_ALIAS = EventType("m.room.canonical_alias", EventType.Class.STATE)
ROOM_CREATE = EventType("m.room.create", EventType.Class.STATE)
ROOM_ENCRYPTED = EventType("m.room.encrypted", EventType.Class.MESSAGE)
ROOM_ENCRYPTION = EventType("m.room.encryption", EventType.Class.STATE)
ROOM_HISTORY_VISIBILITY = EventType("m.room.history_visibility", EventType.Class.STATE)
ROOM_JOIN_RULES = EventType("m.room.join_rules", EventType.Class.STATE)
ROOM_KEY = EventType("m.room_key", EventType.Class.TO_DEVICE)
ROOM_KEY_REQUEST = EventType("m.room_key_request", EventType.Class.TO_DEVICE)
ROOM_KEY_WITHHELD = EventType("m.room_key.withheld", EventType.Class.TO_DEVICE)
ROOM_MEMBER = EventType("m.room.member", EventType.Class.STATE)
ROOM_MESSAGE = EventType("m.room.message", EventType.Class.MESSAGE)
ROOM_NAME = EventType("m.room.name", EventType.Class.STATE)
ROOM_PINNED_EVENTS = EventType("m.room.pinned_events", EventType.Class.STATE)
ROOM_POWER_LEVELS = EventType("m.room.power_levels", EventType.Class.STATE)
ROOM_REDACTION = EventType("m.room.redaction", EventType.Class.MESSAGE)
ROOM_TOMBSTONE = EventType("m.room.tombstone", EventType.Class.STATE)
ROOM_TOPIC = EventType("m.room.topic", EventType.Class.STATE)
SECRET_STORAGE_DEFAULT_KEY = EventType("m.secret_storage.default_key", EventType.Class.ACCOUNT_DATA)
SPACE_CHILD = EventType("m.space.child", EventType.Class.STATE)
SPACE_PARENT = EventType("m.space.parent", EventType.Class.STATE)
STICKER = EventType("m.sticker", EventType.Class.MESSAGE)
TAG = EventType("m.tag", EventType.Class.ACCOUNT_DATA)
TO_DEVICE_DUMMY = EventType("m.dummy", EventType.Class.TO_DEVICE)
TO_DEVICE_ENCRYPTED = EventType("m.room.encrypted", EventType.Class.TO_DEVICE)
TYPING = EventType("m.typing", EventType.Class.EPHEMERAL)
classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

Any

classmethod find(t, t_class=None)

Create a new EventType instance with the given type and class.

If an EventType instance with the same type string and class has been created before, or if no class is specified here, this will return the same instance instead of making a new one.

Examples

>>> from mautrix.client import Client
>>> from mautrix.types import EventType
>>> MY_CUSTOM_TYPE = EventType.find("com.example.custom_event", EventType.Class.STATE)
>>> client = Client(...)
>>> @client.on(MY_CUSTOM_TYPE)
... async def handle_event(evt): ...
Parameters:
  • t (str) – The type string.

  • t_class (Class | None) – The class of the event type.

Returns:

An EventType instance with the given parameters.

Return type:

EventType

property is_account_data: bool

A shortcut for type.t_class == EventType.Class.ACCOUNT_DATA

property is_ephemeral: bool

A shortcut for type.t_class == EventType.Class.EPHEMERAL

property is_message: bool

A shortcut for type.t_class == EventType.Class.MESSAGE

property is_state: bool

A shortcut for type.t_class == EventType.Class.STATE

property is_to_device: bool

A shortcut for type.t_class == EventType.Class.TO_DEVICE

json()

Serialize this object and dump the output as JSON.

Return type:

str

classmethod parse_json(data)

Parse the given string as JSON and deserialize the result into this type.

Parameters:

data (str)

Return type:

EventType

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

with_class(t_class)

Return a copy of this EventType with the given class. If the given class is the same as what this instance has, or if the given class is None, this returns self instead of making a copy.

Parameters:

t_class (Class | None)

Return type:

EventType

class mautrix.types.FileInfo

Information about a document message.

thumbnail_info: ThumbnailInfo | None
thumbnail_file: EncryptedFile | None
thumbnail_url: ContentURI | None
class mautrix.types.Format

A message format. Currently only org.matrix.custom.html is available. This will probably be deprecated when extensible events are implemented.

HTML: Format = <Format.HTML: 'org.matrix.custom.html'>
class mautrix.types.ForwardedRoomKeyEventContent
sender_key: IdentityKey
signing_key: SigningKey
forwarding_key_chain: List[str]
class mautrix.types.GenericEvent

An event class that contains all possible top-level event keys and uses generic Obj’s for object keys (content and unsigned)

content: Obj
type: EventType
room_id: RoomID | None
event_id: EventID | None
sender: UserID | None
timestamp: int | None
state_key: str | None
unsigned: Obj
redacts: EventID | None
class mautrix.types.ImageInfo

Information about an image message.

height: int
width: int
orientation: int
class mautrix.types.InReplyTo
event_id: EventID
class mautrix.types.JoinRule
__new__(value)
PUBLIC = 'public'
KNOCK = 'knock'
RESTRICTED = 'restricted'
INVITE = 'invite'
PRIVATE = 'private'
KNOCK_RESTRICTED = 'knock_restricted'
class mautrix.types.JoinRulesStateEventContent
join_rule: JoinRule
allow: List[JoinRestriction] | None
class mautrix.types.JSONWebKey
key: str
algorithm: str
extractable: bool
key_type: str
key_ops: List[str]
class mautrix.types.KeyID
classmethod curve25519(key_id)
Parameters:

key_id (IdentityKey)

Return type:

KeyID

classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

KeyID

classmethod ed25519(key_id)
Parameters:

key_id (SigningKey | DeviceID)

Return type:

KeyID

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

classmethod signed_curve25519(key_id)
Parameters:

key_id (IdentityKey)

Return type:

KeyID

algorithm: EncryptionKeyAlgorithm
key_id: str
class mautrix.types.KeyRequestAction
REQUEST: KeyRequestAction = <KeyRequestAction.REQUEST: 'request'>
CANCEL: KeyRequestAction = <KeyRequestAction.CANCEL: 'request_cancellation'>
class mautrix.types.LocationInfo

Information about a location message.

thumbnail_url: ContentURI | None
thumbnail_info: ThumbnailInfo | None
thumbnail_file: EncryptedFile | None
class mautrix.types.LocationMessageEventContent
geo_uri: str
info: LocationInfo
class mautrix.types.MediaMessageEventContent

The content of a media message event (m.image, m.audio, m.video, m.file)

static deserialize_info(data)
Parameters:

data (JSON)

Return type:

ImageInfo | VideoInfo | AudioInfo | FileInfo | Obj

url: ContentURI | None
info: ImageInfo | VideoInfo | AudioInfo | FileInfo | Obj | None
file: EncryptedFile | None
filename: str | None
class mautrix.types.Membership

The membership state of a user in a room as specified in section 8.4 Room membership of the spec.

__new__(value)
JOIN = 'join'
LEAVE = 'leave'
INVITE = 'invite'
BAN = 'ban'
KNOCK = 'knock'
class mautrix.types.MemberStateEventContent

The content of a membership event. Spec link

membership: Membership
avatar_url: ContentURI
displayname: str
is_direct: bool
reason: str
third_party_invite: JSON
class mautrix.types.MessageEvent

An m.room.message event

static deserialize_content(data)
Parameters:

data (JSON)

Return type:

TextMessageEventContent | MediaMessageEventContent | LocationMessageEventContent | Obj

content: TextMessageEventContent | MediaMessageEventContent | LocationMessageEventContent | Obj
unsigned: MessageUnsigned | None
class mautrix.types.MessageStatus
__new__(value)
SUCCESS = 'SUCCESS'
PENDING = 'PENDING'
RETRIABLE = 'FAIL_RETRIABLE'
FAIL = 'FAIL_PERMANENT'
class mautrix.types.MessageStatusReason
__new__(value)
property checkpoint_status
GENERIC_ERROR = 'm.event_not_handled'
UNSUPPORTED = 'com.beeper.unsupported_event'
UNDECRYPTABLE = 'com.beeper.undecryptable_event'
TOO_OLD = 'm.event_too_old'
NETWORK_ERROR = 'm.foreign_network_error'
NO_PERMISSION = 'm.no_permission'
class mautrix.types.MessageType

A message type.

property is_media: bool
property is_text: bool
TEXT: MessageType = <MessageType.TEXT: 'm.text'>
EMOTE: MessageType = <MessageType.EMOTE: 'm.emote'>
NOTICE: MessageType = <MessageType.NOTICE: 'm.notice'>
IMAGE: MessageType = <MessageType.IMAGE: 'm.image'>
STICKER: MessageType = <MessageType.STICKER: 'm.sticker'>
VIDEO: MessageType = <MessageType.VIDEO: 'm.video'>
AUDIO: MessageType = <MessageType.AUDIO: 'm.audio'>
FILE: MessageType = <MessageType.FILE: 'm.file'>
LOCATION: MessageType = <MessageType.LOCATION: 'm.location'>
class mautrix.types.MessageUnsigned

Unsigned information sent with message events.

transaction_id: str
class mautrix.types.OlmCiphertext
body: str
type: OlmMsgType
class mautrix.types.OlmMsgType
serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

OlmMsgType

__new__(value)
PREKEY = 0
MESSAGE = 1
class mautrix.types.PowerLevelStateEventContent

The content of a power level event.

ensure_event_level(event_type, level)
Parameters:
Return type:

bool

ensure_user_level(user_id, level, create=None)
Parameters:
Return type:

bool

get_event_level(event_type)
Parameters:

event_type (EventType)

Return type:

int

get_user_level(user_id, create=None)
Parameters:
Return type:

int

set_event_level(event_type, level)
Parameters:
Return type:

None

set_user_level(user_id, level)
Parameters:
Return type:

None

users: Dict[UserID, int]
users_default: int
events: Dict[EventType, int]
events_default: int
notifications: NotificationPowerLevels
state_default: int
invite: int
kick: int
ban: int
redact: int
class mautrix.types.PresenceEvent
sender: UserID
content: PresenceEventContent
class mautrix.types.PresenceEventContent
presence: PresenceState
last_active_ago: int
status_msg: str
currently_active: bool
class mautrix.types.PresenceState
__new__(value)
ONLINE = 'online'
OFFLINE = 'offline'
UNAVAILABLE = 'unavailable'
class mautrix.types.ReactionEvent

A m.reaction event

property unsigned: BaseUnsigned
content: ReactionEventContent
class mautrix.types.ReactionEventContent

The content of an m.reaction event

property relates_to: RelatesTo
class mautrix.types.ReceiptEvent
room_id: RoomID
content: Dict[EventID, Dict[ReceiptType, Dict[UserID, SingleReceiptEventContent]]]
class mautrix.types.ReceiptType
value: Any
class mautrix.types.RedactionEvent

A m.room.redaction event

property unsigned: BaseUnsigned
content: RedactionEventContent
redacts: EventID
class mautrix.types.RedactionEventContent

The content of an m.room.redaction event

reason: str
class mautrix.types.RelatesTo

Message relations. Used for reactions, edits and replies.

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

rel_type: RelationType
event_id: EventID | None
key: str | None
is_falling_back: bool | None
in_reply_to: InReplyTo | None
class mautrix.types.RelationType
ANNOTATION: RelationType = <RelationType.ANNOTATION: 'm.annotation'>
REFERENCE: RelationType = <RelationType.REFERENCE: 'm.reference'>
REPLACE: RelationType = <RelationType.REPLACE: 'm.replace'>
THREAD: RelationType = <RelationType.THREAD: 'm.thread'>
class mautrix.types.RequestedKeyInfo
algorithm: EncryptionAlgorithm
room_id: RoomID
sender_key: IdentityKey
session_id: SessionID
class mautrix.types.RoomAvatarStateEventContent
url: ContentURI | None
class mautrix.types.RoomCreateStateEventContent
property supports_creator_power: bool
room_version: str
federate: bool
predecessor: RoomPredecessor | None
type: RoomType | None
additional_creators: List[UserID] | None
class mautrix.types.RoomEncryptionStateEventContent
algorithm: EncryptionAlgorithm
rotation_period_ms: int
rotation_period_msgs: int
class mautrix.types.RoomKeyEventContent
algorithm: EncryptionAlgorithm
room_id: RoomID
session_id: SessionID
session_key: str
beeper_max_age_ms: int | None
beeper_max_messages: int | None
beeper_is_scheduled: bool | None
class mautrix.types.RoomKeyRequestEventContent
action: KeyRequestAction
requesting_device_id: DeviceID
request_id: str
body: RequestedKeyInfo | None
class mautrix.types.RoomKeyWithheldCode
BLACKLISTED: RoomKeyWithheldCode = <RoomKeyWithheldCode.BLACKLISTED: 'm.blacklisted'>
UNVERIFIED: RoomKeyWithheldCode = <RoomKeyWithheldCode.UNVERIFIED: 'm.unverified'>
UNAUTHORIZED: RoomKeyWithheldCode = <RoomKeyWithheldCode.UNAUTHORIZED: 'm.unauthorised'>
UNAVAILABLE: RoomKeyWithheldCode = <RoomKeyWithheldCode.UNAVAILABLE: 'm.unavailable'>
NO_OLM_SESSION: RoomKeyWithheldCode = <RoomKeyWithheldCode.NO_OLM_SESSION: 'm.no_olm'>
BEEPER_REDACTED: RoomKeyWithheldCode = <RoomKeyWithheldCode.BEEPER_REDACTED: 'com.beeper.redacted'>
class mautrix.types.RoomKeyWithheldEventContent
algorithm: EncryptionAlgorithm
sender_key: IdentityKey
code: RoomKeyWithheldCode
reason: str | None
room_id: RoomID | None
session_id: SessionID | None
class mautrix.types.RoomNameStateEventContent
name: str
class mautrix.types.RoomPinnedEventsStateEventContent
pinned: List[EventID]
class mautrix.types.RoomPredecessor
room_id: RoomID
event_id: EventID
class mautrix.types.RoomTagAccountDataEventContent
tags: Dict[str, RoomTagInfo]
class mautrix.types.RoomTagInfo
order: int | float | str
class mautrix.types.RoomTombstoneStateEventContent
body: str
replacement_room: RoomID
class mautrix.types.RoomTopicStateEventContent
topic: str
class mautrix.types.RoomType
value: Any
class mautrix.types.SecretStorageDefaultKeyEventContent
key: str
class mautrix.types.SingleReceiptEventContent
ts: int
class mautrix.types.SpaceChildStateEventContent
via: List[str]
order: str
suggested: bool
class mautrix.types.SpaceParentStateEventContent
via: List[str]
canonical: bool
class mautrix.types.StateEvent

A room state event.

classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (JSON)

Return type:

StateEvent

static deserialize_content(data)
Parameters:

data (JSON)

Return type:

PowerLevelStateEventContent | MemberStateEventContent | CanonicalAliasStateEventContent | RoomNameStateEventContent | RoomAvatarStateEventContent | RoomTopicStateEventContent | RoomPinnedEventsStateEventContent | RoomTombstoneStateEventContent | RoomEncryptionStateEventContent | RoomCreateStateEventContent | SpaceChildStateEventContent | SpaceParentStateEventContent | JoinRulesStateEventContent | Obj

property prev_content: PowerLevelStateEventContent | MemberStateEventContent | CanonicalAliasStateEventContent | RoomNameStateEventContent | RoomAvatarStateEventContent | RoomTopicStateEventContent | RoomPinnedEventsStateEventContent | RoomTombstoneStateEventContent | RoomEncryptionStateEventContent | RoomCreateStateEventContent | SpaceChildStateEventContent | SpaceParentStateEventContent | JoinRulesStateEventContent | Obj
state_key: str
content: PowerLevelStateEventContent | MemberStateEventContent | CanonicalAliasStateEventContent | RoomNameStateEventContent | RoomAvatarStateEventContent | RoomTopicStateEventContent | RoomPinnedEventsStateEventContent | RoomTombstoneStateEventContent | RoomEncryptionStateEventContent | RoomCreateStateEventContent | SpaceChildStateEventContent | SpaceParentStateEventContent | JoinRulesStateEventContent | Obj
unsigned: StateUnsigned | None
class mautrix.types.StateUnsigned
invite_room_state: List[StrippedStateEvent] | None
class mautrix.types.StrippedStateEvent

Stripped state events included with some invite events.

classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (JSON)

Return type:

StrippedStateEvent

property prev_content: PowerLevelStateEventContent | MemberStateEventContent | CanonicalAliasStateEventContent | RoomNameStateEventContent | RoomAvatarStateEventContent | RoomTopicStateEventContent | RoomPinnedEventsStateEventContent | RoomTombstoneStateEventContent | RoomEncryptionStateEventContent | RoomCreateStateEventContent | SpaceChildStateEventContent | SpaceParentStateEventContent | JoinRulesStateEventContent | Obj
content: PowerLevelStateEventContent | MemberStateEventContent | CanonicalAliasStateEventContent | RoomNameStateEventContent | RoomAvatarStateEventContent | RoomTopicStateEventContent | RoomPinnedEventsStateEventContent | RoomTombstoneStateEventContent | RoomEncryptionStateEventContent | RoomCreateStateEventContent | SpaceChildStateEventContent | SpaceParentStateEventContent | JoinRulesStateEventContent | Obj
room_id: RoomID
sender: UserID
type: EventType
state_key: str
unsigned: StrippedStateUnsigned | None
class mautrix.types.TextMessageEventContent

The content of a text message event (m.text, m.notice, m.emote)

ensure_has_html()
Return type:

None

formatted(format)
Parameters:

format (Format)

Return type:

str | None

trim_reply_fallback()
Return type:

None

format: Format
formatted_body: str
class mautrix.types.ThumbnailInfo

Information about the thumbnail for a document, video, image or location.

height: int
width: int
orientation: int
class mautrix.types.ToDeviceEvent
classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (JSON)

Return type:

ToDeviceEvent

static deserialize_content(data)
Parameters:

data (JSON)

Return type:

Obj | EncryptedOlmEventContent | RoomKeyWithheldEventContent | RoomKeyEventContent | RoomKeyRequestEventContent | ForwardedRoomKeyEventContent | BeeperRoomKeyAckEventContent

sender: UserID
content: Obj | EncryptedOlmEventContent | RoomKeyWithheldEventContent | RoomKeyEventContent | RoomKeyRequestEventContent | ForwardedRoomKeyEventContent | BeeperRoomKeyAckEventContent
class mautrix.types.TypingEvent
room_id: RoomID
content: TypingEventContent
class mautrix.types.TypingEventContent
user_ids: List[UserID]
class mautrix.types.VideoInfo

Information about a video message.

duration: int
orientation: int
class mautrix.types.EventFilter

Event filter object, as specified in the create filter endpoint.

limit: int
not_senders: List[UserID]
not_types: List[EventType]
senders: List[UserID]
types: List[EventType]
class mautrix.types.Filter

Base filter object, as specified in the create filter endpoint.

event_fields: List[str]
event_format: EventFormat
presence: EventFilter
account_data: EventFilter
room: RoomFilter
class mautrix.types.RoomEventFilter

Room event filter object, as specified in the create filter endpoint.

lazy_load_members: bool
include_redundant_members: bool
not_rooms: List[RoomID]
rooms: List[RoomID]
contains_url: bool
class mautrix.types.RoomFilter

Room filter object, as specified in the create filter endpoint.

not_rooms: List[RoomID]
rooms: List[RoomID]
ephemeral: RoomEventFilter
include_leave: bool
state: StateFilter
timeline: RoomEventFilter
account_data: RoomEventFilter
class mautrix.types.StateFilter

State event filter object, as specified in the create filter endpoint. Currently this is the same as RoomEventFilter.

class mautrix.types.IdentifierType

The type qualifier for entities in a Matrix URI.

property sigil: str

The sigil of the identifier, used in Matrix events, matrix.to URLs and other places

property uri_type_qualifier: str

The type qualifier of the identifier, only used in matrix: URIs.

classmethod from_sigil(sigil)

Get the IdentifierType corresponding to the given sigil.

Parameters:

sigil (str)

Return type:

IdentifierType

classmethod from_uri_type_qualifier(uri_type_qualifier)

Get the IdentifierType corresponding to the given matrix: URI type qualifier.

Parameters:

uri_type_qualifier (str)

Return type:

IdentifierType

EVENT = '$'
USER = '@'
ROOM_ALIAS = '#'
ROOM_ID = '!'
class mautrix.types.MatrixURI

A container for Matrix URI data. Supports parsing and generating both matrix: URIs and https://matrix.to URLs with the same interface.

URI_BY_DEFAULT: ClassVar[bool] = False
__init__()

Internal initializer for MatrixURI, external users should use either build() or parse().

Return type:

None

classmethod build(part1, part2=None, via=None, action=None)

Construct a MatrixURI instance using an identifier.

Parameters:
  • part1 (RoomID | UserID | RoomAlias) – The first part of the URI, a user ID, room ID, or room alias.

  • part2 (EventID | None) – The second part of the URI. Only event IDs are allowed, and only allowed when the first part is a room ID or alias.

  • via (list[str] | None) – Servers that know about the resource. Important for room ID links.

  • action (URIAction | None) – The intent for what clients should do with the URI.

Returns:

The constructed MatrixURI.

Raises:

ValueError – if one of the identifiers doesn’t have a valid sigil.

Return type:

MatrixURI

Examples

>>> from mautrix.types import MatrixURI, UserID, RoomAlias, EventID
>>> MatrixURI.build(UserID("@user:example.com")).matrix_to_url
'https://matrix.to/#/%40user%3Aexample.com'
>>> MatrixURI.build(UserID("@user:example.com")).matrix_uri
'matrix:u/user:example.com'
>>> # Picks the format based on the URI_BY_DEFAULT field.
>>> # The default value will be changed to True in a later release.
>>> str(MatrixURI.build(UserID("@user:example.com")))
'https://matrix.to/#/%40user%3Aexample.com'
>>> MatrixURI.build(RoomAlias("#room:example.com"), EventID("$abc123")).matrix_uri
'matrix:r/room:example.com/e/abc123'
property event_id: EventID | None

Get the event ID from this parsed URI.

Returns:

The event ID in this URI, or None if this is not a link to an event in a room.

property matrix_to_url: str

Convert this parsed URI into a https://matrix.to URL.

Returns:

The link as a matrix.to URL.

property matrix_uri: str

Convert this parsed URI into a matrix: URI.

Returns:

The link as a matrix: URI.

classmethod parse(url)

Parse a matrix: URI or https://matrix.to URL into parts.

Parameters:

url (str | URL) – The URI to parse, either as a string or a yarl.URL instance.

Returns:

The parsed data.

Raises:
  • ValueError – if yarl fails to parse the given URL string.

  • MatrixURIError – if the URL isn’t valid in the Matrix spec.

Return type:

MatrixURI

Examples

>>> from mautrix.types import MatrixURI
>>> MatrixURI.parse("https://matrix.to/#/@user:example.com").user_id
'@user:example.com'
>>> MatrixURI.parse("https://matrix.to/#/#room:example.com/$abc123").event_id
'$abc123'
>>> MatrixURI.parse("matrix:r/room:example.com/e/abc123").event_id
'$abc123'
property room_alias: RoomAlias | None

Get the room alias from this parsed URI.

Returns:

The room alias in this URI, or None if this is not a link to a room (or event).

property room_id: RoomID | None

Get the room ID from this parsed URI.

Returns:

The room ID in this URI, or None if this is not a link to a room (or event).

classmethod try_parse(url)

Try to parse a matrix: URI or https://matrix.to URL into parts. If parsing fails, return None instead of throwing an error.

Parameters:

url (str | URL) – The URI to parse, either as a string or a yarl.URL instance.

Returns:

The parsed data, or None if parsing failed.

Return type:

MatrixURI | None

property user_id: UserID | None

Get the user ID from this parsed URI.

Returns:

The user ID in this URI, or None if this is not a link to a user.

via: list[str] | None
action: URIAction | None
exception mautrix.types.MatrixURIError

Raised by MatrixURI.parse() when parsing a URI fails.

class mautrix.types.URIAction

Represents an intent for what the client should do with a Matrix URI.

value: Any
class mautrix.types.MediaCreateResponse

Matrix media create response including MSC3870

content_uri: ContentURI
unused_expired_at: int | None
unstable_upload_url: str | None
class mautrix.types.MediaRepoConfig

Matrix media repo config. See GET /_matrix/media/v3/config.

upload_size: int
class mautrix.types.MXOpenGraph

Matrix URL preview response. See GET /_matrix/media/v3/preview_url.

title: str
description: str
image: OpenGraphImage
video: OpenGraphVideo
audio: OpenGraphAudio
class mautrix.types.OpenGraphAudio
url: ContentURI
mimetype: str
class mautrix.types.OpenGraphImage
url: ContentURI
mimetype: str
height: int
width: int
size: int
class mautrix.types.OpenGraphVideo
url: ContentURI
mimetype: str
height: int
width: int
size: int
class mautrix.types.BatchSendResponse
state_event_ids: List[EventID]
event_ids: List[EventID]
insertion_event_id: EventID
batch_event_id: EventID
next_batch_id: BatchID
base_insertion_event_id: EventID | None
class mautrix.types.BeeperBatchSendResponse
event_ids: List[EventID]
class mautrix.types.DeviceLists
changed: List[UserID]
left: List[UserID]
class mautrix.types.DeviceOTKCount
signed_curve25519: int
curve25519: int
class mautrix.types.EventContext
end: SyncToken
start: SyncToken
event: Event
events_after: List[Event]
events_before: List[Event]
state: List[StateEvent]
class mautrix.types.PaginatedMessages

PaginatedMessages(start, end, events)

static __new__(_cls, start, end, events)

Create new instance of PaginatedMessages(start, end, events)

Parameters:
end: SyncToken

Alias for field number 1

events: List[Event]

Alias for field number 2

start: SyncToken

Alias for field number 0

class mautrix.types.PaginationDirection

Pagination direction used in various endpoints that support pagination.

FORWARD = 'f'
BACKWARD = 'b'
class mautrix.types.RoomAliasInfo

Room alias query result, as specified in the alias resolve endpoint

room_id: RoomID
servers: List[str]
class mautrix.types.RoomCreatePreset

Room creation preset, as specified in the createRoom endpoint

PRIVATE = 'private_chat'
TRUSTED_PRIVATE = 'trusted_private_chat'
PUBLIC = 'public_chat'
class mautrix.types.RoomDirectoryResponse
chunk: List[PublicRoomInfo]
next_batch: DirectoryPaginationToken
prev_batch: DirectoryPaginationToken
total_room_count_estimate: int
class mautrix.types.RoomDirectoryVisibility

Room directory visibility, as specified in the createRoom endpoint

PRIVATE = 'private'
PUBLIC = 'public'
class mautrix.types.PushActionDict
set_tweak: str | None
value: str | None
class mautrix.types.PushActionType
value: Any
class mautrix.types.PushCondition
kind: PushConditionKind
key: str | None
pattern: str | None
operator: PushOperator
class mautrix.types.PushConditionKind
value: Any
class mautrix.types.PushOperator
value: Any
class mautrix.types.PushRule
rule_id: RoomID | UserID | str
default: bool
enabled: bool
actions: List[PushActionDict | PushActionType]
conditions: List[PushCondition]
pattern: str | None
class mautrix.types.PushRuleKind
value: Any
class mautrix.types.PushRuleScope
value: Any
class mautrix.types.Member
membership: Membership
avatar_url: ContentURI
displayname: str
class mautrix.types.User
user_id: UserID
avatar_url: ContentURI
displayname: str
class mautrix.types.UserSearchResults

UserSearchResults(results, limit)

static __new__(_cls, results, limit)

Create new instance of UserSearchResults(results, limit)

Parameters:
limit: int

Alias for field number 1

results: List[User]

Alias for field number 0

class mautrix.types.ExtensibleEnum
static __new__(cls, value)
Parameters:
Return type:

ExtensibleEnum

classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

Any

property key: str
serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

value: Any
class mautrix.types.Lst
classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (list[JSON])

Return type:

Lst

serialize()

Convert this object into objects directly serializable with json.

Return type:

list[JSON]

class mautrix.types.Obj
classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (dict[str, JSON])

Return type:

Obj

get(key, default=None)
popitem()
serialize()

Convert this object into objects directly serializable with json.

Return type:

dict[str, JSON]

class mautrix.types.Serializable

Serializable is the base class for types with custom JSON serializers.

classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

SerializableSubtype

json()

Serialize this object and dump the output as JSON.

Return type:

str

classmethod parse_json(data)

Parse the given string as JSON and deserialize the result into this type.

Parameters:

data (str | bytes)

Return type:

SerializableSubtype

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

class mautrix.types.SerializableAttrs

An abstract Serializable that assumes the subclass is an attrs dataclass.

Examples

>>> from attr import dataclass
>>> from mautrix.types import SerializableAttrs
>>> @dataclass
... class Foo(SerializableAttrs):
...     index: int
...     field: Optional[str] = None
classmethod deserialize(data)

Convert the given data parsed from JSON into an object of this type.

Parameters:

data (JSON)

Return type:

SerializableSubtype

get(item, default=None)
Parameters:
Return type:

Any

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

unrecognized_: Dict[str, JSON]
class mautrix.types.SerializableEnum

A simple Serializable implementation for Enums.

Examples

>>> class MyEnum(SerializableEnum):
...     FOO = "foo value"
...     BAR = "hmm"
>>> MyEnum.FOO.serialize()
"foo value"
>>> MyEnum.BAR.json()
'"hmm"'
serialize()

Convert this object into objects directly serializable with json, i.e. return the value set to this enum value.

Return type:

str

classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type, i.e. find the enum value for the given string using cls(raw).

Parameters:

raw (str)

Return type:

SerializableSubtype

__init__(_)

A fake __init__ to stop the type checker from complaining. Enum’s __new__ overrides this.

Return type:

None

exception mautrix.types.SerializerError

SerializerErrors are raised if something goes wrong during serialization or deserialization.

mautrix.types.deserializer(elem_type)

Define a custom deserialization function for a given type hint.

Parameters:

elem_type (Type[T]) – The type hint to define the deserializer for.

Returns:

Decorator for the function. The decorator will simply add the function to a map of deserializers and return the function.

Return type:

Callable[[Deserializer], Deserializer]

Examples

>>> from datetime import datetime
>>> from mautrix.types import deserializer, JSON
>>> @deserializer(datetime)
... def deserialize_datetime(data: JSON) -> datetime:
...     return datetime.fromtimestamp(data)
mautrix.types.field(default=NOTHING, factory=None, json=None, flatten=False, hidden=False, ignore_errors=False, omit_empty=True, omit_default=False, metadata=None, **kwargs)

A wrapper around attr.ib() to conveniently add SerializableAttrs metadata fields.

Parameters:
  • default (Any) – Same as attr.ib, the default value for the field.

  • factory (Callable[[], Any] | None) – Same as attr.ib, a factory function that creates the default value.

  • json (str | None) – The JSON key used for de/serializing the object.

  • flatten (bool) – Set to flatten subfields inside this field to be a part of the parent object in serialized objects. When deserializing, the input data will be deserialized into both the parent and child fields, so the classes should ignore unknown keys.

  • hidden (bool) – Set to always omit the key from serialized objects.

  • ignore_errors (bool) – Set to ignore type errors while deserializing.

  • omit_empty (bool) – Set to omit the key from serialized objects if the value is None.

  • omit_default (bool) – Set to omit the key from serialized objects if the value is equal to the default.

  • metadata (Dict[str, Any] | None) – Additional metadata for attr.ib.

  • **kwargs – Additional keyword arguments for attr.ib.

Returns:

The decorator function returned by attr.ib.

Examples

>>> from attr import dataclass
>>> from mautrix.types import SerializableAttrs, field
>>> @dataclass
... class SomeData(SerializableAttrs):
...     my_field: str = field(json="com.example.namespaced_field", default="hi")
...
>>> SomeData().serialize()
{'com.example.namespaced_field': 'hi'}
>>> SomeData.deserialize({"com.example.namespaced_field": "hmm"})
SomeData(my_field='hmm')
mautrix.types.serializer(elem_type)

Define a custom serialization function for the given type.

Parameters:

elem_type (Type[T]) – The type to define the serializer for.

Returns:

Decorator for the function. The decorator will simply add the function to a map of deserializers and return the function.

Return type:

Callable[[Serializer], Serializer]

Examples

>>> from datetime import datetime
>>> from mautrix.types import serializer, JSON
>>> @serializer(datetime)
... def serialize_datetime(dt: datetime) -> JSON:
...     return dt.timestamp()
class mautrix.types.SpecVersions
R010 = Version(format=VersionFormat.LEGACY, major=0, minor=1, patch=0, raw='r0.1.0')
R020 = Version(format=VersionFormat.LEGACY, major=0, minor=2, patch=0, raw='r0.2.0')
R030 = Version(format=VersionFormat.LEGACY, major=0, minor=3, patch=0, raw='r0.3.0')
R040 = Version(format=VersionFormat.LEGACY, major=0, minor=4, patch=0, raw='r0.4.0')
R050 = Version(format=VersionFormat.LEGACY, major=0, minor=5, patch=0, raw='r0.5.0')
R060 = Version(format=VersionFormat.LEGACY, major=0, minor=6, patch=0, raw='r0.6.0')
R061 = Version(format=VersionFormat.LEGACY, major=0, minor=6, patch=1, raw='r0.6.1')
V11 = Version(format=VersionFormat.MODERN, major=1, minor=1, patch=0, raw='v1.1')
V110 = Version(format=VersionFormat.MODERN, major=1, minor=10, patch=0, raw='v1.10')
V111 = Version(format=VersionFormat.MODERN, major=1, minor=11, patch=0, raw='v1.11')
V12 = Version(format=VersionFormat.MODERN, major=1, minor=2, patch=0, raw='v1.2')
V13 = Version(format=VersionFormat.MODERN, major=1, minor=3, patch=0, raw='v1.3')
V14 = Version(format=VersionFormat.MODERN, major=1, minor=4, patch=0, raw='v1.4')
V15 = Version(format=VersionFormat.MODERN, major=1, minor=5, patch=0, raw='v1.5')
V16 = Version(format=VersionFormat.MODERN, major=1, minor=6, patch=0, raw='v1.6')
V17 = Version(format=VersionFormat.MODERN, major=1, minor=7, patch=0, raw='v1.7')
V18 = Version(format=VersionFormat.MODERN, major=1, minor=8, patch=0, raw='v1.8')
V19 = Version(format=VersionFormat.MODERN, major=1, minor=9, patch=0, raw='v1.9')
class mautrix.types.Version
classmethod deserialize(raw)

Convert the given data parsed from JSON into an object of this type.

Parameters:

raw (JSON)

Return type:

Version

serialize()

Convert this object into objects directly serializable with json.

Return type:

JSON

format: VersionFormat
major: int
minor: int
patch: int
raw: str
class mautrix.types.VersionFormat
__new__(value)
UNKNOWN = -1
LEGACY = 0
MODERN = 1
class mautrix.types.VersionsResponse
property has_legacy_versions: bool

Check if the response contains any legacy (r0.x.y) versions.

Deprecated since version 0.16.10: supports_at_least() and supports() methods are now preferred.

property has_modern_versions: bool

Check if the response contains any modern (v1.1 or higher) versions.

Deprecated since version 0.16.10: supports_at_least() and supports() methods are now preferred.

property latest_version: Version
supports(thing)

Check if the versions response contains the given spec version or unstable feature.

Parameters:

thing (Version | str) – The spec version (as a Version or string) or unstable feature name (as a string) to check.

Returns:

True if the exact version or unstable feature is supported, False if it’s not supported, None for unstable features which are not included in the response at all.

Return type:

bool | None

supports_at_least(version)

Check if the versions response contains the given spec version or any higher version.

Parameters:

version (Version | str) – The spec version as a Version or a string.

Returns:

True if a version equal to or higher than the given version is found, False otherwise.

Return type:

bool

versions: List[Version]
unstable_features: Dict[str, bool]