matrix

class platypush.plugins.matrix.Credentials(server_url: str, user_id: str, access_token: str, device_id: str | None)[source]

Bases: object

__init__(server_url: str, user_id: str, access_token: str, device_id: str | None) None
class platypush.plugins.matrix.MatrixPlugin(server_url: str = 'https://matrix-client.matrix.org', user_id: Optional[str] = None, password: Optional[str] = None, access_token: Optional[str] = None, device_name: str | None = 'platypush', device_id: Optional[str] = None, download_path: Optional[str] = None, autojoin_on_invite: bool = True, autotrust_devices: bool = False, autotrust_devices_whitelist: Optional[Collection[str]] = None, autotrust_users_whitelist: Optional[Collection[str]] = None, autotrust_rooms_whitelist: Optional[Collection[str]] = None, **kwargs)[source]

Bases: AsyncRunnablePlugin

Matrix chat integration.

Requires:

  • matrix-nio (pip install 'matrix-nio[e2e]')

  • libolm (on Debian `apt-get install libolm-devel, on Arch

    pacman -S libolm)

  • async_lru (pip install async_lru)

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.

Triggers:

__init__(server_url: str = 'https://matrix-client.matrix.org', user_id: Optional[str] = None, password: Optional[str] = None, access_token: Optional[str] = None, device_name: str | None = 'platypush', device_id: Optional[str] = None, download_path: Optional[str] = None, autojoin_on_invite: bool = True, autotrust_devices: bool = False, autotrust_devices_whitelist: Optional[Collection[str]] = None, autotrust_users_whitelist: Optional[Collection[str]] = None, autotrust_rooms_whitelist: Optional[Collection[str]] = None, **kwargs)[source]

Authentication requires user_id/password on the first login. Afterwards, 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.

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 the server_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 the join() 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.

delete_room_alias(alias: str)[source]

Delete a room alias.

Parameters:

alias – The room alias.

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": 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": 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.

join(room_id: str)[source]

Join a room.

Parameters:

room_id – Room 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.

leave(room_id: str)[source]

Leave a joined room.

Parameters:

room_id – Room ID.

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 the body 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.

trust_device(device_id: str)[source]

Mark a device as trusted.

Parameters:

device_id – Device ID.

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:

display_name – New display name.

Returns:

{
  "blacklisted": false,
  "deleted": false,
  "device_id": "ABCDEFG",
  "display_name": "Element Android",
  "ignored": false,
  "keys": {
    "curve25519": "BtlB0vaQmtYFsvOYkmxyzw9qP5yGjuAyRh4gXh3q",
    "ed25519": "atohIK2FeVlYoY8xxpZ1bhDbveD+HA2DswNFqUxP"
  },
  "user_id": "@myuser:matrix.example.org",
  "verified": true
}

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.

upload_keys()[source]

Synchronize the E2EE keys with the homeserver.