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 (Union[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 (Union[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 (Union[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[Union[EventType, InternalEventType], List[Tuple[EventHandler, bool]]]
dispatchers: Dict[Type[dispatcher.Dispatcher], dispatcher.Dispatcher]
syncing_task: Optional[asyncio.Future]
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, **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.

Return type

None

property crypto: Optional[crypt.OlmMachine]

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

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

Optional[mautrix.types.MemberStateEventContent]

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: /joined_members 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: /members 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: /state 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=None)

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: GET /state/{eventType}/{stateKey} 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 (Optional[str]) – The key of the state to look up. Defaults to empty string.

Returns

The state event.

Return type

Union[mautrix.types.PowerLevelStateEventContent, mautrix.types.MemberStateEventContent, mautrix.types.AliasesStateEventContent, mautrix.types.CanonicalAliasStateEventContent, mautrix.types.RoomNameStateEventContent, mautrix.types.RoomAvatarStateEventContent, mautrix.types.RoomTopicStateEventContent, mautrix.types.RoomPinnedEventsStateEventContent, mautrix.types.RoomTombstoneStateEventContent, mautrix.types.RoomEncryptionStateEventContent, mautrix.types.event.state.RoomCreateStateEventContent, mautrix.types.event.state.SpaceChildStateEventContent, mautrix.types.event.state.SpaceParentStateEventContent, mautrix.types.Obj]

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: PUT /state/{eventType}/{stateKey} API reference

Parameters
Returns

The ID of the event that was sent.

Return type

mautrix.types.EventID

state_store: Optional[mautrix.client.StateStore]