mautrix.client mixins

The Client class itself is very small, most of the functionality on top of ClientAPI comes from mixins that it includes. In some cases it might be useful to extend from a mixin instead of the high-level client class (e.g. the appservice module’s IntentAPI extends StoreUpdatingAPI).

Syncer

class mautrix.client.Syncer

Bases: abc.ABC

__init__(sync_store)
Parameters

sync_store (mautrix.client.SyncStore) –

Return type

None

add_dispatcher(dispatcher_type)
Parameters

dispatcher_type (Type[mautrix.client.Dispatcher]) –

Return type

None

add_event_handler(event_type, handler, wait_sync=False)

Add a new event handler.

Parameters
  • event_type (mautrix.client.InternalEventType | mautrix.types.EventType) – The event type to add. If not specified, the handler will be called for all event types.

  • handler (Callable[[mautrix.types.Event], Awaitable[None]]) – The handler function to add.

  • wait_sync (bool) – Whether or not the handler should be awaited before the next sync request.

Return type

None

abstract async create_filter(filter_params)
Parameters

filter_params (mautrix.types.Filter) –

Return type

mautrix.types.FilterID

dispatch_event(event, source)

Send the given event to all applicable event handlers.

Parameters
  • event (mautrix.types.Event) – The event to send.

  • source (mautrix.client.SyncStream) – The sync stream the event was received in.

Return type

list[_asyncio.Task]

dispatch_internal_event(event_type, custom_type=None, **kwargs)
Parameters
  • event_type (mautrix.client.InternalEventType) –

  • custom_type (Optional[Any]) –

  • kwargs (Any) –

Return type

list[_asyncio.Task]

dispatch_manual_event(event_type, data, include_global_handlers=False, force_synchronous=False)
Parameters
  • event_type (mautrix.types.EventType | mautrix.client.InternalEventType) –

  • data (Any) –

  • include_global_handlers (bool) –

  • force_synchronous (bool) –

Return type

list[_asyncio.Task]

handle_sync(data)

Handle a /sync object.

Parameters

data (mautrix.types.JSON) – The data from a /sync request.

Return type

list[_asyncio.Task]

on(var)

Add a new event handler. This method is for decorator usage. Use add_event_handler() if you don’t use a decorator.

Parameters

var (Union[Callable[[mautrix.types.Event], Awaitable[None]], mautrix.types.EventType, mautrix.client.InternalEventType]) – Either the handler function or the event type to handle.

Returns

If var was the handler function, the handler function is returned.

If var was an event type, a function that takes the handler function as an argument is returned.

Return type

Union[Callable[[mautrix.types.Event], Awaitable[None]], Callable[[Callable[[mautrix.types.Event], Awaitable[None]]], Callable[[mautrix.types.Event], Awaitable[None]]]]

Examples

>>> from mautrix.client import Client
>>> cli = Client(...)
>>> @cli.on(EventType.ROOM_MESSAGE)
>>> def handler(event: MessageEvent) -> None:
...     pass
remove_dispatcher(dispatcher_type)
Parameters

dispatcher_type (Type[mautrix.client.Dispatcher]) –

Return type

None

remove_event_handler(event_type, handler)

Remove an event handler.

Parameters
  • handler (Callable[[mautrix.types.Event], Awaitable[None]]) – The handler function to remove.

  • event_type (mautrix.types.EventType | mautrix.client.InternalEventType) – The event type to remove the handler function from.

Return type

None

async run_internal_event(event_type, custom_type=None, **kwargs)
Parameters
  • event_type (mautrix.client.InternalEventType) –

  • custom_type (Optional[Any]) –

  • kwargs (Any) –

Return type

None

start(filter_data)

Start syncing with the server. Can be stopped with stop().

Parameters

filter_data (Optional[Union[mautrix.types.FilterID, mautrix.types.Filter]]) – The filter data or filter ID to use for syncing.

Return type

_asyncio.Future

stop()

Stop a sync started with start().

Return type

None

abstract async sync(since=None, timeout=30000, filter_id=None, full_state=False, set_presence=None)
Parameters
Return type

mautrix.types.JSON

loop: asyncio.AbstractEventLoop
log: TraceLogger
mxid: UserID
global_event_handlers: list[tuple[EventHandler, bool]]
event_handlers: dict[EventType | InternalEventType, list[tuple[EventHandler, bool]]]
dispatchers: dict[Type[dispatcher.Dispatcher], dispatcher.Dispatcher]
syncing_task: asyncio.Task | None
ignore_initial_sync: bool
ignore_first_sync: bool
presence: PresenceState
sync_store: SyncStore

DecryptionDispatcher

class mautrix.client.DecryptionDispatcher

Bases: mautrix.client.SimpleDispatcher

DecryptionDispatcher is a dispatcher that can be used with a client.Syncer to automatically decrypt events and dispatch the unencrypted versions for event handlers.

The easiest way to use this is with client.Client, which automatically registers this dispatcher when EncryptingAPI.crypto is set.

event_type = EventType("m.room.encrypted", EventType.Class.MESSAGE)
async handle(evt)
Parameters

evt (mautrix.types.EncryptedEvent) –

Return type

None

client: client.Client

EncryptingAPI

class mautrix.client.EncryptingAPI

Bases: mautrix.client.StoreUpdatingAPI

EncryptingAPI is a wrapper around StoreUpdatingAPI that automatically encrypts messages.

For automatic decryption, see DecryptionDispatcher.

__init__(*args, crypto_log=None, **kwargs)

Initialize a ClientAPI. You must either provide the api parameter with an existing mautrix.api.HTTPAPI instance, or provide the base_url and other arguments for creating it as kwargs.

Parameters
  • mxid – The Matrix ID of the user. This is used for things like setting profile metadata. Additionally, the homeserver domain is extracted from this string and used for setting aliases and such. This can be changed later using set_mxid.

  • device_id – The device ID corresponding to the access token used.

  • api – The mautrix.api.HTTPAPI instance to use. You can also pass the kwargs to create a HTTPAPI instance rather than creating the instance yourself.

  • kwargs – If api is not specified, then the arguments to pass when creating a HTTPAPI.

  • crypto_log (Optional[mautrix.util.logging.TraceLogger]) –

Return type

None

property crypto: crypt.OlmMachine | None

The crypto.OlmMachine to use for e2ee stuff.

property crypto_enabled: bool

True if both the olm machine and state store are set properly.

crypto_log: TraceLogger = <TraceLogger mau.client.crypto (WARNING)>
async encrypt(room_id, event_type, content)

Encrypt a message for the given room. Automatically creates and shares a group session if necessary.

Parameters
Returns

The content of the encrypted event.

Return type

mautrix.types.EncryptedMegolmEventContent

encryption_blacklist: set[EventType] = {EventType("m.reaction", EventType.Class.MESSAGE)}
async send_message_event(room_id, event_type, content, disable_encryption=False, **kwargs)

A wrapper around ClientAPI.send_message_event() that encrypts messages if the target room is encrypted.

Parameters
Returns

The ID of the event that was sent.

Return type

mautrix.types.EventID

async share_group_session(room_id)

Create and share a Megolm session for the given room.

Parameters

room_id (mautrix.types.RoomID) – The room to share the session for.

Return type

None

StoreUpdatingAPI

class mautrix.client.StoreUpdatingAPI

Bases: mautrix.client.ClientAPI

StoreUpdatingAPI is a wrapper around the medium-level ClientAPI that optionally updates a client state store with outgoing state events (after they’re successfully sent).

__init__(*args, state_store=None, **kwargs)

Initialize a ClientAPI. You must either provide the api parameter with an existing mautrix.api.HTTPAPI instance, or provide the base_url and other arguments for creating it as kwargs.

Parameters
  • mxid – The Matrix ID of the user. This is used for things like setting profile metadata. Additionally, the homeserver domain is extracted from this string and used for setting aliases and such. This can be changed later using set_mxid.

  • device_id – The device ID corresponding to the access token used.

  • api – The mautrix.api.HTTPAPI instance to use. You can also pass the kwargs to create a HTTPAPI instance rather than creating the instance yourself.

  • kwargs – If api is not specified, then the arguments to pass when creating a HTTPAPI.

  • state_store (Optional[mautrix.client.StateStore]) –

Return type

None

async ban_user(room_id, user_id, reason='', extra_content=None)

Ban a user in the room. If the user is currently in the room, also kick them. When a user is banned from a room, they may not join it or be invited to it until they are unbanned. The caller must have the required power level in order to perform this operation.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room from which the user should be banned.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the user being banned.

  • reason (str) – The reason the user has been kicked. This will be supplied as the reason on the target’s updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the ban event content. If a non-empty dict is passed, the ban will be created using the PUT /state/m.room.member/... endpoint instead of POST /ban.

Return type

None

async fill_member_event(room_id, user_id, content)

Fill a membership event content that is going to be sent in send_member_event().

This is used to set default fields like the displayname and avatar, which are usually set by the server in the sugar membership endpoints like /join and /invite, but are not set automatically when sending member events manually.

This implementation in StoreUpdatingAPI will first try to call the default implementation (which calls fill_member_event_callback). If that doesn’t return anything, this will try to get the profile from the current member event, and then fall back to fetching the global profile from the server.

Parameters
Returns

The filled member event content.

Return type

mautrix.types.MemberStateEventContent | None

async get_joined_members(room_id)

Get a user ID -> member info map for a room. The current user must be in the room for it to work, unless it is an Application Service in which case any of the AS’s users must be in the room. This API is primarily for Application Services and should be faster to respond than /members as it can be implemented more efficiently on the server.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room to get the members of.

Returns

A dictionary from user IDs to Member info objects.

Return type

dict[mautrix.types.UserID, mautrix.types.Member]

async get_members(room_id, at=None, membership=None, not_membership=None)

Get the list of members for a room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to get the member events for.

  • at (Optional[mautrix.types.SyncToken]) – The point in time (pagination token) to return members for in the room. This token can be obtained from a prev_batch token returned for each room by the sync API. Defaults to the current state of the room, as determined by the server.

  • membership (Optional[mautrix.types.Membership]) – The kind of membership to filter for. Defaults to no filtering if unspecified. When specified alongside not_membership, the two parameters create an ‘or’ condition: either the membership is the same as membership or is not the same as not_membership.

  • not_membership (Optional[mautrix.types.Membership]) – The kind of membership to exclude from the results. Defaults to no filtering if unspecified.

Returns

A list of most recent member events for each user.

Return type

list[mautrix.types.StateEvent]

async get_state(room_id)

Get the state events for the current state of a room.

See also: API reference

Parameters

room_id (mautrix.types.RoomID) – The ID of the room to look up the state for.

Returns

A list of state events with the most recent of each event_type/state_key pair.

Return type

list[mautrix.types.StateEvent]

async get_state_event(room_id, event_type, state_key='')

Looks up the contents of a state event in a room. If the user is joined to the room then the state is taken from the current state of the room. If the user has left the room then the state is taken from the state of the room when they left.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to look up the state in.

  • event_type (mautrix.types.EventType) – The type of state to look up.

  • state_key (str) – The key of the state to look up. Defaults to empty string.

Returns

The state event.

Return type

mautrix.types.StateEventContent

async invite_user(room_id, user_id, reason=None, extra_content=None)

Invite a user to participate in a particular room. They do not start participating in the room until they actually join the room.

Only users currently in the room can invite other users to join that room.

If the user was invited to the room, the homeserver will add a m.room.member event to the room.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to which to invite the user.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the invitee.

  • reason (Optional[str]) – The reason the user was invited. This will be supplied as the reason on the m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the invite event content. If a non-empty dict is passed, the invite event will be created using the PUT /state/m.room.member/... endpoint instead of POST /invite.

Return type

None

async join_room(room_id_or_alias, servers=None, third_party_signed=None, max_retries=4)

Start participating in a room, i.e. join it by its ID or alias, with an optional list of servers to ask about the ID from.

See also: API reference

Parameters
  • room_id_or_alias (Union[mautrix.types.RoomID, mautrix.types.RoomAlias]) – The ID of the room to join, or an alias pointing to the room.

  • servers (Optional[list[str]]) – A list of servers to ask about the room ID to join. Not applicable for aliases, as aliases already contain the necessary server information.

  • third_party_signed (Optional[mautrix.types.JSON]) – A signature of an m.third_party_invite token to prove that this user owns a third party identity which has been invited to the room.

  • max_retries (int) – The maximum number of retries. Used to circumvent a Synapse bug with accepting invites over federation. 0 means only one join call will be attempted. See: matrix-org/synapse#2807

Returns

The ID of the room the user joined.

Return type

mautrix.types.RoomID

async join_room_by_id(room_id, third_party_signed=None, extra_content=None)

Start participating in a room, i.e. join it by its ID.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to join.

  • third_party_signed (Optional[mautrix.types.JSON]) – A signature of an m.third_party_invite token to prove that this user owns a third party identity which has been invited to the room.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the join event content. If a non-empty dict is passed, the join event will be created using the PUT /state/m.room.member/... endpoint instead of POST /join.

Returns

The ID of the room the user joined.

Return type

mautrix.types.RoomID

async kick_user(room_id, user_id, reason='', extra_content=None)

Kick a user from the room.

The caller must have the required power level in order to perform this operation.

Kicking a user adjusts the target member’s membership state to be leave with an optional reason. Like with other membership changes, a user can directly adjust the target member’s state by calling EventMethods.send_state_event() with EventType.ROOM_MEMBER as the event type and the user_id as the state key.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room from which the user should be kicked.

  • user_id (mautrix.types.UserID) – The fully qualified user ID of the user being kicked.

  • reason (str) – The reason the user has been kicked. This will be supplied as the reason on the target’s updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the kick event content. If a non-empty dict is passed, the kick event will be created using the PUT /state/m.room.member/... endpoint instead of POST /kick.

Return type

None

async leave_room(room_id, reason=None, extra_content=None, raise_not_in_room=False)

Stop participating in a particular room, i.e. leave the room.

If the user was already in the room, they will no longer be able to see new events in the room. If the room requires an invite to join, they will need to be re-invited before they can re-join.

If the user was invited to the room, but had not joined, this call serves to reject the invite.

The user will still be allowed to retrieve history from the room which they were previously allowed to see.

See also: API reference

Parameters
  • room_id (mautrix.types.RoomID) – The ID of the room to leave.

  • reason (Optional[str]) – The reason for leaving the room. This will be supplied as the reason on the updated m.room.member event.

  • extra_content (Optional[dict[str, mautrix.types.JSON]]) – Additional properties for the leave event content. If a non-empty dict is passed, the leave event will be created using the PUT /state/m.room.member/... endpoint instead of POST /leave.

  • raise_not_in_room (bool) – Should errors about the user not being in the room be raised?

Return type

None

async send_state_event(room_id, event_type, content, state_key='', **kwargs)

Send a state event to a room. State events with the same room_id, event_type and state_key will be overridden.

See also: API reference

Parameters
  • room_id (RoomID) – The ID of the room to set the state in.

  • event_type (EventType) – The type of state to send.

  • content (StateEventContent | dict[str, JSON]) – The content to send.

  • state_key (str) – The key for the state to send. Defaults to empty string.

  • **kwargs – Optional parameters to pass to the HTTPAPI.request() method. Used by IntentAPI to pass the timestamp massaging field to AppServiceAPI.request().

Returns

The ID of the event that was sent.

Return type

EventID

async unban_user(room_id, user_id)

Unban a user from the room. This allows them to be invited to the room, and join if they would otherwise be allowed to join according to its join rules. The caller must have the required power level in order to perform this operation.

See also: API reference

Parameters
Return type

None

state_store: StateStore | None