matrix
#
Description#
Matrix chat integration.
Note that libolm
and the [e2e]
module are only required if you want
E2E encryption support.
Unless you configure the extension to use the token of an existing trusted device, it is recommended that you mark the virtual device used by this integration as trusted through a device that is already trusted. You may encounter errors when sending or receiving messages on encrypted rooms if your user has some untrusted devices. The easiest way to mark the device as trusted is the following:
Configure the integration with your credentials and start Platypush.
Use the same credentials to log in through a Matrix app or web client (Element, Hydrogen, etc.) that has already been trusted.
You should see a notification that prompts you to review the untrusted devices logged in to your account. Dismiss it for now - that verification path is currently broken on the underlying library used by this integration.
Instead, select a room that you have already joined, select the list of users in the room and select yourself.
In the _Security_ section, you should see that at least one device is marked as unverified, and you can start the verification process by clicking on it.
Select “Verify through emoji”. A list of emojis should be prompted. Optionally, verify the logs of the application to check that you see the same list. Then confirm that you see the same emojis, and your device will be automatically marked as trusted.
All the URLs returned by actions and events on this plugin are in the
mxc://<server>/<media_id>
format. You can either convert them to HTTP
through the mxc_to_http()
method, or download them through the
download()
method.
Authentication requires user_id/password on the first login.
Afterward, session credentials are stored under
<$PLATYPUSH_WORKDIR>/matrix/credentials.json
(default:
~/.local/share/platypush/matrix/credentials.json
), and you can
remove the cleartext credentials from your configuration file.
Otherwise, if you already have an access_token
, you can set the
associated field instead of using password
. This may be required if
the user has 2FA enabled.
Configuration#
matrix:
# [Optional]
# Default Matrix instance base URL (default:
# ``https://matrix-client.matrix.org``).
# server_url: https://matrix-client.matrix.org # type=str
# [Optional]
# user_id, in the format ``@user:example.org``, or just
# the username if the account is hosted on the same server configured in
# the ``server_url``.
# user_id: # type=Optional[str]
# [Optional]
# User password.
# password: # type=Optional[str]
# [Optional]
# User access token.
# access_token: # type=Optional[str]
# [Optional]
# The name of this device/connection (default: ``platypush``).
# device_name: platypush # type=Optional[str]
# [Optional]
# Use an existing ``device_id`` for the sessions.
# device_id: # type=Optional[str]
# [Optional]
# The folder where downloaded media will be saved
# (default: ``~/Downloads``).
# download_path: # type=Optional[str]
# [Optional]
# Whether the account should automatically
# join rooms upon invite. If false, then you may want to implement your
# own logic in an event hook when a
# `MatrixRoomInviteEvent <https://docs.platypush.tech/platypush/events/matrix.html#platypush.message.event.matrix.MatrixRoomInviteEvent>`_ event is
# received, and call the `MatrixPlugin.join <https://docs.platypush.tech/platypush/plugins/matrix.html#platypush.plugins.matrix.MatrixPlugin.join>`_ method if required.
# autojoin_on_invite: True # type=bool
# [Optional]
# If set to True, the plugin will automatically
# trust the devices on encrypted rooms. Set this property to True
# only if you only plan to use a bot on trusted rooms. Note that if
# no automatic trust mechanism is set you may need to explicitly
# create your logic for trusting users - either with a hook when
# `MatrixSyncEvent <https://docs.platypush.tech/platypush/events/matrix.html#platypush.message.event.matrix.MatrixSyncEvent>`_ is
# received, or when a room is joined, or before sending a message.
# autotrust_devices: False # type=bool
# [Optional]
# Automatically trust devices with IDs
# IDs provided in this list.
# autotrust_devices_whitelist: # type=Optional[Collection[str]]
# [Optional]
# Automatically trust devices from the
# user IDs provided in this list.
# autotrust_users_whitelist: # type=Optional[Collection[str]]
# [Optional]
# Automatically trust devices on the
# room IDs provided in this list.
# autotrust_rooms_whitelist: # type=Optional[Collection[str]]
# [Optional]
# How often the `RunnablePlugin.loop <https://docs.platypush.tech/platypush/plugins/.html#platypush.plugins.RunnablePlugin.loop>`_ function should be
# executed (default: 15 seconds). *NOTE*: For back-compatibility
# reasons, the `poll_seconds` argument is also supported, but it's
# deprecated.
# poll_interval: 15 # type=Optional[float]
# [Optional]
# How long we should wait for any running
# threads/processes to stop before exiting (default: 5 seconds).
# stop_timeout: 5 # type=Optional[float]
# [Optional]
# If set to True then the plugin will not monitor
# for new events. This is useful if you want to run a plugin in
# stateless mode and only leverage its actions, without triggering any
# events. Defaults to False.
# disable_monitor: False # type=bool
Dependencies#
pip
pip install async_lru matrix-nio[e2e]
Alpine
apk add olm-dev
Debian
apt install libolm-devel python3-async-lru
Fedora
yum install libolm-devel python-async-lru
Arch Linux
pacman -S python-async-lru libolm
Triggered events#
Actions#
Module reference#
- class platypush.plugins.matrix.Credentials(server_url: str, user_id: str, access_token: str, device_id: str | None = None)[source]#
Bases:
object
- class platypush.plugins.matrix.MatrixPlugin(server_url: str = 'https://matrix-client.matrix.org', user_id: str | None = None, password: str | None = None, access_token: str | None = None, device_name: str | None = 'platypush', device_id: str | None = None, download_path: str | None = None, autojoin_on_invite: bool = True, autotrust_devices: bool = False, autotrust_devices_whitelist: Collection[str] | None = None, autotrust_users_whitelist: Collection[str] | None = None, autotrust_rooms_whitelist: Collection[str] | None = None, **kwargs)[source]#
Bases:
AsyncRunnablePlugin
Matrix chat integration.
Note that
libolm
and the[e2e]
module are only required if you want E2E encryption support.Unless you configure the extension to use the token of an existing trusted device, it is recommended that you mark the virtual device used by this integration as trusted through a device that is already trusted. You may encounter errors when sending or receiving messages on encrypted rooms if your user has some untrusted devices. The easiest way to mark the device as trusted is the following:
Configure the integration with your credentials and start Platypush.
Use the same credentials to log in through a Matrix app or web client (Element, Hydrogen, etc.) that has already been trusted.
You should see a notification that prompts you to review the untrusted devices logged in to your account. Dismiss it for now - that verification path is currently broken on the underlying library used by this integration.
Instead, select a room that you have already joined, select the list of users in the room and select yourself.
In the _Security_ section, you should see that at least one device is marked as unverified, and you can start the verification process by clicking on it.
Select “Verify through emoji”. A list of emojis should be prompted. Optionally, verify the logs of the application to check that you see the same list. Then confirm that you see the same emojis, and your device will be automatically marked as trusted.
All the URLs returned by actions and events on this plugin are in the
mxc://<server>/<media_id>
format. You can either convert them to HTTP through themxc_to_http()
method, or download them through thedownload()
method.- __init__(server_url: str = 'https://matrix-client.matrix.org', user_id: str | None = None, password: str | None = None, access_token: str | None = None, device_name: str | None = 'platypush', device_id: str | None = None, download_path: str | None = None, autojoin_on_invite: bool = True, autotrust_devices: bool = False, autotrust_devices_whitelist: Collection[str] | None = None, autotrust_users_whitelist: Collection[str] | None = None, autotrust_rooms_whitelist: Collection[str] | None = None, **kwargs)[source]#
Authentication requires user_id/password on the first login. Afterward, session credentials are stored under
<$PLATYPUSH_WORKDIR>/matrix/credentials.json
(default:~/.local/share/platypush/matrix/credentials.json
), and you can remove the cleartext credentials from your configuration file.Otherwise, if you already have an
access_token
, you can set the associated field instead of usingpassword
. This may be required if the user has 2FA enabled.- Parameters:
server_url – Default Matrix instance base URL (default:
https://matrix-client.matrix.org
).user_id – user_id, in the format
@user:example.org
, or just the username if the account is hosted on the same server configured in theserver_url
.password – User password.
access_token – User access token.
device_name – The name of this device/connection (default:
platypush
).device_id – Use an existing
device_id
for the sessions.download_path – The folder where downloaded media will be saved (default:
~/Downloads
).autojoin_on_invite – Whether the account should automatically join rooms upon invite. If false, then you may want to implement your own logic in an event hook when a
platypush.message.event.matrix.MatrixRoomInviteEvent
event is received, and call thejoin()
method if required.autotrust_devices – If set to True, the plugin will automatically trust the devices on encrypted rooms. Set this property to True only if you only plan to use a bot on trusted rooms. Note that if no automatic trust mechanism is set you may need to explicitly create your logic for trusting users - either with a hook when
platypush.message.event.matrix.MatrixSyncEvent
is received, or when a room is joined, or before sending a message.autotrust_devices_whitelist – Automatically trust devices with IDs IDs provided in this list.
autotrust_users_whitelist – Automatically trust devices from the user IDs provided in this list.
autotrust_rooms_whitelist – Automatically trust devices on the room IDs provided in this list.
- add_room_alias(room_id: str, alias: str)[source]#
Add an alias to a room.
- Parameters:
room_id – An existing room ID.
alias – The room alias.
- ban(room_id: str, user_id: str, reason: str | None = None)[source]#
Ban a user from a room.
- Parameters:
room_id – Room ID.
user_id – User ID.
reason – Optional reason.
- create_room(name: str | None = None, alias: str | None = None, topic: str | None = None, is_public: bool = False, is_direct: bool = False, federate: bool = True, encrypted: bool = False, invite_users: Sequence[str] = ())[source]#
Create a new room on the server.
- Parameters:
name – Room name.
alias – Custom alias for the canonical name. For example, if set to
foo
, the alias for this room will be#foo:matrix.example.org
.topic – Room topic.
is_public – Set to True if you want the room to be public and discoverable (default: False).
is_direct – Set to True if this should be considered a direct room with only one user (default: False).
federate – Whether you want to allow users from other servers to join the room (default: True).
encrypted – Whether the room should be encrypted (default: False).
invite_users – A list of user IDs to invite to the room.
- Returns:
{ "room_id": "!aBcDeFgHiJkMnO:matrix.example.org" }
- delete_devices(devices: Sequence[str], username: str | None = None, password: str | None = None)[source]#
Delete a list of devices from the user’s authorized list and invalidate their access tokens.
- Parameters:
devices – List of devices that should be deleted.
username – Username, if the server requires authentication upon device deletion.
password – User password, if the server requires authentication upon device deletion.
- download(url: str, download_path: str | None = None, filename: str | None = None, allow_remote=True)[source]#
Download a file given its Matrix URL.
Note that URLs that point to encrypted resources will be automatically decrypted only if they were received on a room joined by this account.
- Parameters:
url – Matrix URL, in the format
mxc://<server>/<media_id>
.download_path – Override the default
download_path
(output directory for the downloaded file).filename – Name of the output file (default: inferred from the remote resource).
allow_remote – Indicates to the server that it should not attempt to fetch the media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
- Returns:
{ "content_type": "image/png", "path": "/home/user/Downloads/image.png", "size": 1024, "url": "mxc://matrix.example.org/YhQycHvFOvtiDDbEeWWtEhXx" }
- forget(room_id: str)[source]#
Leave a joined room and forget its data as well as all the messages.
If all the users leave a room, that room will be marked for deletion by the homeserver.
- Parameters:
room_id – Room ID.
- get_device(device_id: str)[source]#
Get the info about a device given its ID.
- Returns:
{ "blacklisted": false, "deleted": false, "device_id": "ABCDEFG", "display_name": "Element Android", "ignored": true, "keys": { "curve25519": "BtlB0vaQmtYFsvOYkmxyzw9qP5yGjuAyRh4gXh3q", "ed25519": "atohIK2FeVlYoY8xxpZ1bhDbveD+HA2DswNFqUxP" }, "user_id": "@myuser:matrix.example.org", "verified": true }
- get_joined_rooms()[source]#
Retrieve the rooms that the user has joined.
- Returns:
[ { "avatar_url": "mxc://matrix.example.org/AbCdEfG0123456789", "display_name": "My Room", "encrypted": true, "name": "My Room", "owner_id": "@myuser:matrix.example.org", "room_id": "!aBcDeFgHiJkMnO:matrix.example.org", "topic": "My Room Topic" } ]
- get_messages(room_id: str, start: str | None = None, end: str | None = None, backwards: bool = True, limit: int = 10)[source]#
Retrieve a list of messages from a room.
- Parameters:
room_id – Room ID.
start – Start retrieving messages from this batch ID (default: latest batch returned from a call to
sync
).end – Retrieving messages until this batch ID.
backwards – Set to True if you want to retrieve messages starting from the most recent, in descending order (default). Otherwise, the first returned message will be the oldest and messages will be returned in ascending order.
limit – Maximum number of messages to be returned (default: 10).
- Returns:
{ "end": "t2-10202_143892_626_3663_5949_6_558_7501_0", "end_time": "2022-07-23T18:20:01.254223", "messages": [ { "body": "Hello world!", "content_type": "image/jpeg", "decrypted": "True if the message was encrypted and has been successfully decrypted", "event_id": "$2eOQ5ueafANj91GnPCRkRUOOjM7dI5kFDOlfMNCD2ly", "format": "markdown", "formatted_body": "**Hello world!**", "hashes": { "sha256": "yoQLQwcURq6/bJp1xQ/uhn9Z2xeA27KhMhPd/mfT8tR" }, "iv": "NqJMMdijlLvAAAAAAAAAAA", "key": { "alg": "A256CTR", "ext": true, "k": "u6jjAyNvJoBHE55P5ZfvX49m3oSt9s_L4PSQdprRSJI", "key_ops": [ "encrypt", "decrypt" ], "kty": "oct" }, "room_id": "!aBcDeFgHiJkMnO:matrix.example.org", "timestamp": "2022-07-23T17:20:01.254223", "transaction_id": "mQ8hZR6Dx8I8YDMwONYmBkf7lTgJSMV/ZPqosDNM", "url": "mxc://matrix.example.org/oarGdlpvcwppARPjzNlmlXkD", "user_id": "@myuser:matrix.example.org", "verified": "True if this is an encrypted message coming from a verified source" } ], "start": "s10226_143893_619_3648_5951_5_555_7501_0", "start_time": "2022-07-23T16:20:01.254223" }
- get_my_devices()[source]#
Get the list of devices associated to the current user.
- Returns:
[ { "device_id": "ABCDEFG", "display_name": "My Device", "last_seen_date": "2022-07-23T17:20:01.254223", "last_seen_ip": "1.2.3.4" } ]
- get_profile(user_id: str)[source]#
Retrieve the details about a user.
- Parameters:
user_id – User ID.
- Returns:
{ "avatar_url": "mxc://matrix.example.org/AbCdEfG0123456789", "display_name": "Foo Bar", "user_id": "@myuser:matrix.example.org" }
- get_room(room_id: str)[source]#
Retrieve the details about a room.
- Parameters:
room_id – room ID.
- Returns:
{ "avatar_url": "mxc://matrix.example.org/AbCdEfG0123456789", "display_name": "My Room", "encrypted": true, "name": "My Room", "owner_id": "@myuser:matrix.example.org", "room_id": "!aBcDeFgHiJkMnO:matrix.example.org", "topic": "My Room Topic" }
- get_room_members(room_id: str)[source]#
Retrieve the list of users joined into a room.
- Parameters:
room_id – The room ID.
- Returns:
[ { "avatar_url": "mxc://matrix.example.org/AbCdEfG0123456789", "display_name": "Foo Bar", "user_id": "@myuser:matrix.example.org" } ]
- invite(room_id: str, user_id: str)[source]#
Invite a user to a room.
- Parameters:
room_id – Room ID.
user_id – User ID.
- kick(room_id: str, user_id: str, reason: str | None = None)[source]#
Kick a user out of a room.
- Parameters:
room_id – Room ID.
user_id – User ID.
reason – Optional reason.
- async listen()[source]#
Main body of the async plugin. When it’s called, the event loop should already be running and available over self._loop.
- main()#
Implementation of the main loop of the plugin.
- mxc_to_http(url: str, homeserver: str | None = None) str [source]#
Convert a Matrix URL (in the format
mxc://server/media_id
) to an HTTP URL.Note that invoking this function on a URL containing encrypted content (i.e. a URL containing media sent to an encrypted room) will provide a URL that points to encrypted content. The best way to deal with encrypted media is by using
download()
to download the media locally.- Parameters:
url – The MXC URL to be converted.
homeserver – The hosting homeserver (default: the same as the URL).
- Returns:
The converted HTTP(s) URL.
- room_alias_to_id(alias: str) str [source]#
Convert a room alias (in the format
#alias:matrix.example.org
) to a room ID (in the format!aBcDeFgHiJkMnO:matrix.example.org
).- Parameters:
alias – The room alias.
- Returns:
The room ID, as a string.
- send_message(room_id: str, message_type: str = 'text', body: str | None = None, attachment: str | None = None, tx_id: str | None = None, ignore_unverified_devices: bool = False)[source]#
Send a message to a room.
- Parameters:
room_id – Room ID.
body – Message body.
attachment – Path to a local file to send as an attachment, or URL of an existing Matrix media ID in the format
mxc://<server>/<media_id>
. If the attachment is a local file, the file will be automatically uploaded,message_type
will be automatically inferred from the file and thebody
will be replaced by the filename.message_type – Message type. Supported: text, audio, video, image. Default: text.
tx_id – Unique transaction ID to associate to this message.
ignore_unverified_devices – If true, unverified devices will be ignored. Otherwise, if the room is encrypted and it contains devices that haven’t been marked as trusted, the message delivery may fail (default: False).
- Returns:
{ "event_id": "$24KT_aQz6sSKaZH8oTCibRTl62qywDgQXMpz5epXsW5" }
- set_avatar(url: str)[source]#
Set/change the avatar URL for the current user.
- Parameters:
url – New avatar URL. It must be a valid
mxc://
link.
- set_display_name(display_name: str)[source]#
Set/change the display name for the current user.
- Parameters:
display_name – New display name.
- start()#
Start the plugin.
- stop()#
Stop the plugin.
- unban(room_id: str, user_id: str)[source]#
Remove a user ban from a room.
- Parameters:
room_id – Room ID.
user_id – User ID.
- untrust_device(device_id: str)[source]#
Mark a device as untrusted.
- Parameters:
device_id – Device ID.
- update_device(device_id: str, display_name: str | None = None)[source]#
Update information about a user’s device.
- Parameters:
device_id – Device ID.
display_name – New display name.
- Returns:
{ "blacklisted": true, "deleted": true, "device_id": "ABCDEFG", "display_name": "Element Android", "ignored": false, "keys": { "curve25519": "BtlB0vaQmtYFsvOYkmxyzw9qP5yGjuAyRh4gXh3q", "ed25519": "atohIK2FeVlYoY8xxpZ1bhDbveD+HA2DswNFqUxP" }, "user_id": "@myuser:matrix.example.org", "verified": false }
- upload(file: str, name: str | None = None, content_type: str | None = None, encrypt: bool = False) str [source]#
Upload a file to the server.
- Parameters:
file – Path to the file to upload.
name – Filename to be used for the remote file (default: same as the local file).
content_type – Specify a content type for the file (default: inferred from the file’s extension and content).
encrypt – Encrypt the file (default: False).
- Returns:
The Matrix URL of the uploaded resource.
- wait_stop(timeout=None)#
Wait until a stop event is received.