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
- add_dispatcher(dispatcher_type)
- Parameters
dispatcher_type (Type[mautrix.client.Dispatcher]) –
- Return type
- 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
- abstract async create_filter(filter_params)
- Parameters
filter_params (mautrix.types.Filter) –
- Return type
- dispatch_event(event, source)
Send the given event to all applicable event handlers.
- Parameters
event (Event | None) – The event to send.
source (SyncStream) – The sync stream the event was received in.
- Return type
- 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
- 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
- async run_internal_event(event_type, custom_type=None, **kwargs)
- Parameters
event_type (mautrix.client.InternalEventType) –
custom_type (Optional[Any]) –
kwargs (Any) –
- Return type
- 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
- abstract async sync(since=None, timeout=30000, filter_id=None, full_state=False, set_presence=None)
- Parameters
since (Optional[mautrix.types.SyncToken]) –
timeout (int) –
filter_id (Optional[mautrix.types.FilterID]) –
full_state (bool) –
set_presence (Optional[mautrix.types.PresenceState]) –
- Return type
- log: TraceLogger
- mxid: UserID
- syncing_task: asyncio.Task | None
- 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 whenEncryptingAPI.crypto
is set.- event_type = EventType("m.room.encrypted", EventType.Class.MESSAGE)
- async handle(evt)
- Parameters
evt (mautrix.types.EncryptedEvent) –
- Return type
- 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 existingmautrix.api.HTTPAPI
instance, or provide thebase_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 thekwargs
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
- 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
room_id (mautrix.types.RoomID) – The room to encrypt the event to.
event_type (mautrix.types.EventType) – The type of event.
content (mautrix.types.EventContent) – The content of the event.
- Returns
The content of the encrypted event.
- Return type
- 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
room_id (mautrix.types.RoomID) – The room to send the message to.
event_type (mautrix.types.EventType) – The unencrypted event type.
content (mautrix.types.EventContent) – The unencrypted event content.
disable_encryption (bool) – Set to
True
if you want to force-send an unencrypted message.**kwargs – Additional parameters to pass to
ClientAPI.send_message_event()
.
- Returns
The ID of the event that was sent.
- Return type
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
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 existingmautrix.api.HTTPAPI
instance, or provide thebase_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 thekwargs
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
- 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 ofPOST /ban
.
- Return type
- async create_room(*args, **kwargs)
Create a new room with various configuration options.
See also: API reference
- Parameters
alias_localpart – The desired room alias local part. If this is included, a room alias will be created and mapped to the newly created room. The alias will belong on the same homeserver which created the room. For example, if this was set to “foo” and sent to the homeserver “example.com” the complete room alias would be
#foo:example.com
.visibility – A
public
visibility indicates that the room will be shown in the published room list. Aprivate
visibility will hide the room from the published room list. Defaults toprivate
. NB: This should not be confused withjoin_rules
which also uses the wordpublic
.preset – Convenience parameter for setting various default state events based on a preset. Defaults to private (invite-only).
name – If this is included, an
m.room.name
event will be sent into the room to indicate the name of the room. See Room Events for more information onm.room.name
.topic – If this is included, an
m.room.topic
event will be sent into the room to indicate the topic for the room. See Room Events for more information onm.room.topic
.is_direct – This flag makes the server set the
is_direct
flag on the m.room.member events sent to the users ininvite
andinvite_3pid
. See Direct Messaging for more information.invitees – A list of user IDs to invite to the room. This will tell the server to invite everyone in the list to the newly created room.
initial_state –
A list of state events to set in the new room. This allows the user to override the default state events set in the new room. The expected format of the state events are an object with type, state_key and content keys set.
Takes precedence over events set by
is_public
, but gets overriden byname
andtopic keys
.room_version – The room version to set for the room. If not provided, the homeserver will use its configured default.
creation_content – Extra keys, such as
m.federate
, to be added to them.room.create
event. The server will ignorecreator
androom_version
. Future versions of the specification may allow the server to ignore other keys.power_level_override – The power level content to override in the default power level event. This object is applied on top of the generated
m.room.power_levels
event content prior to it being sent to the room. Defaults to overriding nothing.beeper_auto_join_invites – A Beeper-specific extension which auto-joins all members in the invite array instead of sending invites.
custom_request_fields – Additional fields to put in the top-level /createRoom content. Non-custom fields take precedence over fields here.
- Returns
The ID of the newly created room.
- Raises
MatrixResponseError – If the response does not contain a
room_id
field.- Return type
- 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
room_id (mautrix.types.RoomID) – The room where the member event is going to be sent.
user_id (mautrix.types.UserID) – The user whose membership is changing.
content (mautrix.types.MemberStateEventContent) – The new member event content.
- Returns
The filled member event content.
- Return type
- 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
- 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 themembership
is the same as membership or is not the same asnot_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
- 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
- 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 ofPOST /invite
.
- Return type
- 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
- 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 ofPOST /join
.
- Returns
The ID of the room the user joined.
- Return type
- 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 optionalreason
. Like with other membership changes, a user can directly adjust the target member’s state by callingEventMethods.send_state_event()
withEventType.ROOM_MEMBER
as the event type and theuser_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 ofPOST /kick
.
- Return type
- async knock_room(room_id_or_alias, reason=None, servers=None)
Knock on a room, i.e. request to 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 knock on, or an alias pointing to the room.
reason (Optional[str]) – The reason for knocking on the room. This will be supplied as the
reason
on the updated m.room.member event.servers (Optional[list[str]]) – A list of servers to ask about the room ID to knock. Not applicable for aliases, as aliases already contain the necessary server information.
- Returns
The ID of the room the user knocked on.
- Return type
- 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 ofPOST /leave
.raise_not_in_room (bool) – Should errors about the user not being in the room be raised?
- Return type
- 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
andstate_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.
ensure_joined – Used by IntentAPI to determine if it should ensure the user is joined before sending the event.
**kwargs – Optional parameters to pass to the
HTTPAPI.request()
method. Used byIntentAPI
to pass the timestamp massaging field toAppServiceAPI.request()
.
- Returns
The ID of the event that was sent.
- Return type
- async unban_user(room_id, user_id, reason='', extra_content=None)
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
room_id (mautrix.types.RoomID) – The ID of the room from which the user should be unbanned.
user_id (mautrix.types.UserID) – The fully qualified user ID of the user being banned.
reason (str) – The reason the user has been unbanned. 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 unban (leave) event content. If a non-empty dict is passed, the unban will be created using the
PUT /state/m.room.member/...
endpoint instead ofPOST /unban
.
- Return type
- state_store: StateStore | None