Welcome to synadm’s documentation!

Command Line Reference

Main Command

synadm

the Matrix-Synapse admin CLI

synadm [OPTIONS] COMMAND [ARGS]...

Options

-v, --verbose

Enable INFO (-v) or DEBUG (-vv) logging on console.

--batch, --yes, --non-interactive, --scripting

Enable batch processing mode. Use with caution! This will:

- Disable all interactive prompts.
- Disable automatic translation of unix timestamps to human readable
formats.
-o, --output <output>

Override default output format. The ‘human’ mode gives a tabular or list view depending on the fetched data, but often needs a lot of horizontal space to display correctly. ‘json’ returns formatted json. ‘minified’ is minified json, suitable for scripting purposes. ‘pprint’ shows a formatted output with the help of Python’s built-in pprint module. ‘yaml’ is a compromise between human- and machine-readable output, it doesn’t need as much terminal width as ‘human’ does and is the default on fresh installations.

Options:

yaml | json | minified | human | pprint | y | j | m | h | p |

-c, --config-file <config_file>

Configuration file path.

Default:

~/.config/synadm.yaml

Commands

config

Modify synadm’s configuration.

group

Manage groups (communities).

history

Purge historic events from Synapse database.

matrix

Execute Matrix API calls.

media

Manage local and remote media.

notice

Send messages to users.

regtok

Manage registration tokens.

room

Manipulate rooms and room membership.

user

List, add, modify, deactivate/erase users,…

version

Get the Synapse server version.

Config

synadm config

Modify synadm’s configuration.

Configuration details are generally always asked interactively. Command line options override the suggested defaults in the prompts.

synadm config [OPTIONS]

Options

-u, --user <user_>

Admin user allowed to access the Synapse admin API’s.

-t, --token <token>

The Admin user’s access token.

-b, --base-url <base_url>

The base URL Synapse is running on. Typically this is https://localhost:8008 or https://localhost:8448. If Synapse is configured to expose its admin API’s to the outside world it might as well be something like this: https://example.org:8448

-p, --admin-path <admin_path>

The path Synapse provides its admin API’s, usually the default fits most installations.

-m, --matrix-path <matrix_path>

The path Synapse provides the regular Matrix API’s, usually the default fits most installations.

-w, --timeout <timeout>

The time in seconds synadm should wait for responses from admin API’s or Matrix API’s. The default is 7 seconds.

-o, --output <output>

How synadm displays data by default. The ‘human’ mode gives a tabular or list view depending on the fetched data, but often needs a lot of horizontal space to display correctly. ‘json’ returns formatted json. ‘minified’ is minified json, suitable for scripting purposes. ‘pprint’ shows a formatted output with the help of Python’s built-in pprint module. ‘yaml’ is a compromise between human- and machine-readable output, it doesn’t need as much terminal width as ‘human’ does and is the default on fresh installations. The

default output format can always be overridden by using the global –output/-o switch (eg ‘synadm -o pprint user list’).

Options:

yaml | json | minified | human | pprint

-d, --server-discovery <server_discovery>

The method used for discovery of “the own homeserver name”. Since none of the currently existing Admin API endpoints provide this information, the federation API among other things is asked for help. If set to “well-known” the URI of the federation API is tried to be fetched via the well-known resource of the configured “Synapse base URL”. If set to “dns” the SRV record of the domain name found in the “Synapse base URL” is used to get that information. Once the federation URI is known, the homeserver name can be retrieved. In case “Synapse base URL” contains “localhost”, it’s assumed that the required federation API is listening on localhost:port already (the “keys” Matrix API endpoint). If that is failing as well, as a last resort solution, the homeserver name can just be saved to the configuration directly via the “homeserver” setting. Note that the fetching of the homeserver name is only executed when a synadm subcommand requires it (eg. like some of the media and user subcommands do), and the “homeserver” directive in the config is set to “auto-retrieval”.

Options:

well-known | dns

-n, --homeserver <homeserver>

Synapse homeserver hostname. Usually matrix.DOMAIN or DOMAIN. The default value ‘auto-retrieval’ will try to discover the name using the method set by –server-discovery.

User

synadm user

List, add, modify, deactivate/erase users, reset passwords.

synadm user [OPTIONS] COMMAND [ARGS]...
3pid

Find a user based on their Third Party ID.

Finds a user based on their Third Party ID (3PID) where medium is the kind of Third Party ID that is used such as ‘email’ or ‘msidn’.

synadm user 3pid [OPTIONS] ADDRESS

Options

-m, --medium <medium>

Required Medium specifies what kind of Third Party ID is used such as ‘email’ or ‘msidn’

Default:

email

Arguments

ADDRESS

Required argument

auth-provider

Find a user based on their ID in auth-provider.

Finds a user based on their external user ID in a particular auth provider where provider is the auth provider ID as advertised in supported authenticated methods in m.login.sso api response such as ‘oidc’ or ‘google’ or ‘github’.

synadm user auth-provider [OPTIONS] EXTERNAL_USER_ID

Options

-p, --provider <provider>

Required Provider ID as advertised in supported authenticated methods in m.login.sso api response such as ‘oidc’ or ‘google’ or ‘github’

Arguments

EXTERNAL_USER_ID

Required argument

deactivate

Deactivate or gdpr-erase a user. Provide matrix user ID (@user:server) as argument. It removes active access tokens, resets the password, and deletes third-party IDs (to prevent the user requesting a password reset).

synadm user deactivate [OPTIONS] USER_ID

Options

-e, --gdpr-erase

Marks the user as GDPR-erased. This means messages sent by the user will still be visible by anyone that was in the room when these messages were sent, but hidden from users joining the room afterwards.

Default:

False

Arguments

USER_ID

Required argument

details

View details of a user account.

synadm user details [OPTIONS] USER_ID

Arguments

USER_ID

Required argument

list

List users, search for users.

synadm user list [OPTIONS]

Options

-f, --from <from_>

Offset user listing by given number. This option is also used for pagination.

Default:

0

-l, --limit <limit>

Limit user listing to given number

Default:

100

-g, --guests, -G, --no-guests

Show guest users.

-d, --deactivated

Also show deactivated/erased users

Default:

False

-n, --name <name>

Search users by name - filters to only return users with user ID localparts or displaynames that contain this value (localpart is the left part before the colon of the matrix ID (@user:server)

-i, --user-id <user_id>

Search users by ID - filters to only return users with Matrix IDs (@user:server) that contain this value

login

Get an access token for a given user.

Useful for when admins wish to do actions on behalf of a user.

If no –expire* option is given, a default token expiry time of exactly 1 day (24h) is used. If it’s desired that the token never expires, use –expire-never

This API does not generate a new device for the user, and so will not appear in their /devices list, and in general the target user should not be able to tell they have been logged in as.

To expire the token before the expiry date/time is reached, call the standard /logout API with the token. Note: The token will expire if the admin user calls /logout/all from any of their devices, but the token will not expire if the target user does the same.

synadm user login [OPTIONS] USER_ID

Options

-d, --expire-days <expire_days>

Expire token after this number of days.

--expire <expire>

Expire token after this point in time. Eg. ‘2021-01-01’, see above for available date/time formats.

--expire-ts <expire_ts>

Expire token after this point in time giving a unix timestamp in ms.

--expire-never

Never expire token.

Default:

False

Arguments

USER_ID

Required argument

media

List all local media uploaded by a user.

Provide matrix user ID (@user:server) as argument.

Gets a list of all local media that a specific user_id has created. By default, the response is ordered by descending creation date and ascending media ID. The newest media is on top. You can change the order with options –order-by and –reverse.

Caution. The database only has indexes on the columns media_id, user_id and created_ts. This means that if a different sort order is used (upload_name, last_access_ts, media_length, media_type, quarantined_by or safe_from_quarantine), this can cause a large load on the database, especially for large environments

synadm user media [OPTIONS] USER_ID

Options

-f, --from <from_>

Offset media listing by given number. This option is also used for pagination.

Default:

0

-l, --limit <limit>

Limit media listing to given number

Default:

100

-s, --sort <sort>

The method by which to sort the returned list of media. If the ordered field has duplicates, the second order is always by ascending media_id, which guarantees a stable ordering.

Options:

media_id | upload_name | created_ts | last_access_ts | media_length | media_type | quarantined_by | safe_from_quarantine

-r, --reverse

Direction of media order. If set it will reverse the sort order of –order-by method.

--datetime, --dt, --timestamp, --ts

Display created and last accessed timestamps in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].

Arguments

USER_ID

Required argument

membership

List all rooms a user is member of.

Provide matrix user ID (@user:server) as argument.

synadm user membership [OPTIONS] USER_ID

Options

--aliases, --ids

Display rooms as canonical aliases or room ID’s. [default: aliases]

Arguments

USER_ID

Required argument

modify

Create or modify a local user. Provide matrix user ID (@user:server) as argument.

synadm user modify [OPTIONS] USER_ID

Options

-p, --password-prompt

Set password interactively.

-P, --password <password>

Set password on command line.

-n, --display-name <display_name>

Set display name. defaults to the value of user_id

-t, --threepid <threepid>

Add a third-party identifier. This can be an email address or a phone number. Threepids are used for several things: For use when logging in, as an alternative to the user id. In the case of email, as an alternative contact to help with account recovery, as well as to receive notifications of missed messages. Format: medium value (eg. –threepid email <user@example.org>). This option can also be stated multiple times, i.e. a user can have multiple threepids configured.

-v, --avatar-url <avatar_url>

Set avatar URL. Must be a MXC URI (https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris)

-a, --admin, -u, --no-admin

Grant user admin permission. Eg user is allowed to use the admin API.

--activate

Re-activate user.

--deactivate

Deactivate user. Use with caution! Deactivating a user removes their active access tokens, resets their password, kicks them out of all rooms and deletes third-party identifiers (to prevent the user requesting a password reset). See also “user deactivate” command.

Arguments

USER_ID

Required argument

password

Change a user’s password.

To prevent the user from being logged out of all sessions use option -n.

synadm user password [OPTIONS] USER_ID

Options

-n, --no-logout

Don’t log user out of all sessions on all devices.

-p, --password <password>

New password.

Arguments

USER_ID

Required argument

prune-devices

Delete devices and invalidate access tokens of a user.

Deletes devices of a user and invalidates any access token associated with them. Starts from deleting the oldest devices, not seen in a number of days, which may be abandoned.

Note that this will affect the encryption and decryption of messages sent by other users to this user or to rooms where the user is present.

synadm user prune-devices [OPTIONS] USER_ID

Options

-l, --list-only

Dry-run: does not perform the deletion but shows what would be done. If you want to list all devices/sessions, you can also use the whois command.

Default:

False

-d, --min-days <min_days>

How many days need to have passed from the last time a device was seen for it to be deleted.

Default:

90

-s, --min-surviving <min_surviving>

Stop processing devices when only this number of devices is left for this user. Allows to reduce disruption by preserving recently used devices/sessions.

Default:

1

-i, --device-id <device_id>

Only search devices with this ID. The other options still apply if they’re not 0.

--datetime, --dt, --timestamp, --ts

Display ‘last seen date/time’ in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].

Arguments

USER_ID

Required argument

shadow-ban

Shadow-ban or unban a user.

Useful for moderating malicious or egregiously abusive users.

A shadow-banned user will not receive any notification, but still will be unable to contact anyone on the server. Use this as a tool of last resort since it may lead to confusing or broken behaviour for the client.

Generally, it is more appropriate to ban or kick abusive users.

synadm user shadow-ban [OPTIONS] USER_ID

Options

-u, --unban

Unban the specified user

Arguments

USER_ID

Required argument

whois

View information about a user’s active session.

synadm user whois [OPTIONS] USER_ID

Arguments

USER_ID

Required argument

Room

synadm room

Manipulate rooms and room membership.

The syntax of room IDs in synadm is as the Matrix spec defines: https://spec.matrix.org/latest/#room-structure. Make sure to escape the ! character from your shell. In bash and zsh this can be achieved by using single quotes (‘), eg. ‘!id123abc:matrix.DOMAIN’

synadm room [OPTIONS] COMMAND [ARGS]...
block

Block or unblock a room.

synadm room block [OPTIONS] ROOM_ID

Options

-b, --block, -u, --unblock

Specifies whether to block or unblock a room.

Default:

True

Arguments

ROOM_ID

Required argument

block-status

Get if a room is blocked, and who blocked it.

synadm room block-status [OPTIONS] ROOM_ID

Arguments

ROOM_ID

Required argument

delete

Delete and possibly purge a room.

synadm room delete [OPTIONS] ROOM_ID

Options

-u, --new-room-user-id <new_room_user_id>

If set, a new room will be created with this user ID as the creator and admin, and all users in the old room will be moved into that room. If not set, no new room will be created and the users will just be removed from the old room. The user ID must be on the local server, but does not necessarily have to belong to a registered user.

-n, --room-name <room_name>

A string representing the name of the room that new users will be invited to. Defaults to “Content Violation Notification”

-m, --message <message>

A string containing the first message that will be sent as new_room_user_id in the new room. Ideally this will clearly convey why the original room was shut down. Defaults to “Sharing illegal content on this server is not permitted and rooms in violation will be blocked.”

-b, --block

If set, this room will be added to a blocking list, preventing future attempts to join the room

Default:

False

--no-purge

Prevent removing of all traces of the room from your database.

Default:

False

Arguments

ROOM_ID

Required argument

details

Get room details.

synadm room details [OPTIONS] ROOM_ID

Arguments

ROOM_ID

Required argument

join

Join a room.

synadm room join [OPTIONS] ROOM_ID_OR_ALIAS USER_ID

Arguments

ROOM_ID_OR_ALIAS

Required argument

USER_ID

Required argument

list

List and search for rooms.

synadm room list [OPTIONS]

Options

-f, --from <from_>

Offset room listing by given number. This option is used for pagination.

Default:

0

-l, --limit <limit>

Maximum amount of rooms to return.

Default:

100

-n, --name <name>

Filter rooms by parts of their room name, canonical alias and room id.

-s, --sort <sort>

The method in which to sort the returned list of rooms.

Options:

name | canonical_alias | joined_members | joined_local_members | version | creator | encryption | federatable | public | join_rules | guest_access | history_visibility | state_events

-r, --reverse

Direction of room order. If set it will reverse the sort order of –order-by method.

make-admin

Grant a user room admin permission.

If the user is not in the room, and it is not publicly joinable, then invite the user.

synadm room make-admin [OPTIONS] ROOM_ID

Options

-u, --user-id <user_id>

By default the server admin (the caller) is granted power, but another user can optionally be specified.

Arguments

ROOM_ID

Required argument

members

List current room members.

synadm room members [OPTIONS] ROOM_ID

Arguments

ROOM_ID

Required argument

power-levels

List user’s power levels set in rooms.

A combination of commands room list and room state. It enriches the room list response with a list of users and their corresponding power levels set. It only displays a subset of the available information (room name, id, aliases and power levels). Increase the number of rooms fetched using –limit/-l (default: 10) or use the pagination option –from/-f to go beyond the default. Use –name/-n to search. This command can require quite some time to complete depending on those options.

synadm room power-levels [OPTIONS]

Options

-i, --room-id <room_id>

View power levels of this room only.

-a, --all-details

Show detailed information about each room. The default is to only show room_id, name, canonical_alias and power_levels.

-f, --from <from_>

Offset room listing by given number. This option is used for pagination.

Default:

0

-l, --limit <limit>

Maximum amount of rooms to return.

Default:

10

-n, --name <name>

Filter rooms by parts of their room name, canonical alias and room id.

-s, --sort <sort>

The method in which to sort the returned list of rooms.

Options:

name | canonical_alias | joined_members | joined_local_members | version | creator | encryption | federatable | public | join_rules | guest_access | history_visibility | state_events

-r, --reverse

Direction of room order. If set it will reverse the sort order of –order-by method.

resolve

Lookup room ID from alias or vice versa.

synadm room resolve [OPTIONS] ROOM_ID_OR_ALIAS

Options

-r, --reverse

Fetch all room aliases corresponding to a given room ID, instead of the other way round.

Default:

False

Arguments

ROOM_ID_OR_ALIAS

Required argument

state

Get a list of all state events in a room.

synadm room state [OPTIONS] ROOM_ID

Arguments

ROOM_ID

Required argument

Media

synadm media

Manage local and remote media.

synadm media [OPTIONS] COMMAND [ARGS]...
delete

Delete media by ID, size or age

synadm media delete [OPTIONS]

Options

-i, --media-id <media_id>

The media with this specific media ID will be deleted.

-d, --before-days <before_days>

Delete all media that was last accessed before this number of days ago.

-b, --before <before>

Delete all media that was last accessed before this date/time. Eg. ‘2021-01-01’, see above for available date/time formats.

-t, --before-ts <before_ts>

Delete all media that was last accessed before this unix timestamp in ms.

--size, --kib <size>

Delete all media that is larger than this size in KiB (1 KiB = 1024 bytes).

--delete-profiles, --all

Also delete files that are still used in image data (e.g user profile, room avatar). If set, these files will be deleted too. Not valid when a specific media is being deleted (–media-id)

list

List local media by room or user.

synadm media list [OPTIONS]

Options

-r, --room-id <room_id>

List all media in room with this room ID (‘!abcdefg’).

-u, --user-id <user_id>

List all media uploaded by user with this matrix ID (@user:server).

-f, --from <from_>

Offset media listing by given number. This option is also used for pagination but only supported together with –user-id.

Default:

0

-l, --limit <limit>

Limit media listing to given number. This option is only supported together with –user-id.

Default:

100

-s, --sort <sort>

The method by which to sort the returned list of media. If the ordered field has duplicates, the second order is always by ascending media_id, which guarantees a stable ordering. This option is only supported together with –user-id.

Options:

media_id | upload_name | created_ts | last_access_ts | media_length | media_type | quarantined_by | safe_from_quarantine

-R, --reverse

Direction of media order. If set it will reverse the sort order of –order-by method. This option is only supported together with –user-id.

--datetime, --dt, --timestamp, --ts

Display created and last accessed timestamps in a human readable format, or as a unix timestamp in milliseconds. This option only applies to user media and is ignored with room media. [default: datetime].

protect

Protect specific media from being quarantined.

synadm media protect [OPTIONS] MEDIA_ID

Arguments

MEDIA_ID

Required argument

purge

Purge old cached remote media

synadm media purge [OPTIONS]

Options

-d, --before-days <before_days>

Purge all media that was last accessed before this number of days ago.

-b, --before <before>

Purge all media that was last accessed before this date/time. Eg. ‘2021-01-01’, see above for available date/time formats.

-t, --before-ts <before_ts>

Purge all media that was last accessed before this unix timestamp in ms.

quarantine

Quarantine media in rooms, by users or by media ID.

synadm media quarantine [OPTIONS]

Options

-i, --media-id <media_id>

The media with this specific media ID will be quarantined.

-r, --room-id <room_id>

All media in room with this room ID (!abcdefg) will be quarantined.

-u, --user-id <user_id>

All media uploaded by user with this matrix ID (@user:server) will be quarantined.

-s, --server-name <server_name>

The server name of the media, mandatory when –media-id is used and _remote_ media should be processed. For locally stored media this option can be omitted.

unquarantine

Remove media from quarantine.

synadm media unquarantine [OPTIONS]

Options

-i, --media-id <media_id>

The media with this specific media ID will be removed from quarantine.

-s, --server-name <server_name>

The server name of the media, mandatory when –media-id is used and _remote_ media should be processed. For locally stored media this option can be omitted.

History

synadm history

Purge historic events from Synapse database.

synadm history [OPTIONS] COMMAND [ARGS]...
purge

Purge room events before a point in time or before an event ID.

The purge history API allows server admins to purge historic events from their database, reclaiming disk space.

Depending on the amount of history being purged a call to the API may take several minutes or longer. During this period users will not be able to paginate further back in the room from the point being purged from.

Note that Synapse requires at least one message in each room, so it will never delete the last message in a room.

By default, events sent by local users are not deleted, as they may represent the only copies of this content in existence. (Events sent by remote users are deleted.)

Room state data (such as joins, leaves, topic) is always preserved.

The API starts the purge running, and returns immediately with a JSON body with a purge id. Use ‘synadm history purge-status <purge id>’ to poll for updates on the running purge.

synadm history purge [OPTIONS] ROOM_ID

Options

-i, --before-event-id <before_event_id>

Purge all history before this event ID. Event ID’s contain $, which is interpreted by the shell. Make sure it is surrounded by single quotes (‘id’).

-d, --before-days <before_days>

Purge all history before this number of days ago.

--before <before>

Purge all history before this point in time. Eg. ‘2021-01-01’, see above for available date/time formats.

--before-ts <before_ts>

Purge all history before this point in time giving a unix timestamp in ms.

--delete-local

This option overrides the default behavior and forces removal of events sent by local users.

Arguments

ROOM_ID

Required argument

purge-status

View status of a recent history purge..

Provide purge ID as argument. The status will be one of active, complete, or failed.

synadm history purge-status [OPTIONS] PURGE_ID

Arguments

PURGE_ID

Required argument

Group

synadm group

Manage groups (communities).

synadm group [OPTIONS] COMMAND [ARGS]...
delete

Delete a local group (community).

synadm group delete [OPTIONS] GROUP_ID

Arguments

GROUP_ID

Required argument

Matrix

synadm matrix

Execute Matrix API calls.

synadm matrix [OPTIONS] COMMAND [ARGS]...
login

Login to Matrix via username/password and receive an access token.

The response also contains a newly generated device ID and further information about user and homeserver.

Each successful login will show up in the user’s devices list marked with a display name of ‘synadm matrix login command’.

synadm matrix login [OPTIONS] USER_ID

Options

-p, --password <password>

The Matrix user’s password. If missing, an interactive password prompt is shown.

Arguments

USER_ID

Required argument

raw

Execute a raw request to the Matrix API.

The endpoint argument is the part of the URL _after_ the configured base URL and Matrix path (see synadm config). A simple get request would e.g look like this: synadm matrix raw client/versions

Use either –token or –prompt to provide a user’s token and execute Matrix commands on their behalf. Respect the privacy of others! Be responsible!

The precedence rules for token reading are: 1. Interactive input using –prompt; 2. Set on CLI via –token string; 3. Read from environment variable $MTOKEN; 4. Preconfigured admin token set in synadm’s config file.

synadm matrix raw [OPTIONS] ENDPOINT

Options

-m, --method <method>

The HTTP method used for the request.

Default:

get

Options:

get | post | put | delete

-d, --data <data>

The JSON string sent in the body of post, put and delete requests - provided as a string. Make sure to escape it from shell interpretation by using single quotes. E.g ‘{“key1”: “value1”, “key2”: 123}’

Default:

{}

-f, --data-file <data_file>

Read JSON data from file. To read from stdin use “-” as the filename argument.

-t, --token <token>

Token used for Matrix authentication instead of the configured admin user’s token. If –token (and –prompt) option is missing, the token is read from environment variable $MTOKEN instead. To make sure a user’s token does not show up in system logs, don’t provide it on the shell directly but set $MTOKEN with shell command read MTOKEN.

-p, --prompt

Prompt for the token used for Matrix authentication. This option always overrides $MTOKEN.

Default:

False

Arguments

ENDPOINT

Required argument

Environment variables

MTOKEN

Provide a default for --token

Regtok

synadm regtok

Manage registration tokens.

synadm regtok [OPTIONS] COMMAND [ARGS]...
delete

Delete a registration token.

synadm regtok delete [OPTIONS] TOKEN

Arguments

TOKEN

Required argument

details

View details of the given token.

synadm regtok details [OPTIONS] TOKEN

Options

--datetime, --dt, --timestamp, --ts

Display expiry time in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].

Arguments

TOKEN

Required argument

list

List registration tokens

synadm regtok list [OPTIONS]

Options

-v, --valid, -V, --invalid

List only valid/invalid tokens.

--datetime, --dt, --timestamp, --ts

Display expiry time in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].

new

Create a new registration token.

synadm regtok new [OPTIONS]

Options

-n, --token <token>

Set the registration token. The default is a random value generated by the server.

-l, --length <length>

The length of the randomly generated token if the token is not specified.

Default:

16

-u, --uses-allowed <uses_allowed>

The number of times the token can be used to complete a registration before it becomes invalid. [default: unlimited uses]

-t, --expiry-ts <expiry_ts>

The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC.

[default: no expiry]

-e, --expire-at <expire_at>

The latest time the registration token is valid. See above for available date/time formats. [default: no expiry]

update

Update a registration token

synadm regtok update [OPTIONS] TOKEN

Options

-u, --uses-allowed <uses_allowed>

The number of times the token can be used to complete a registration before it becomes invalid. Use -1 for an unlimited number of uses. [default: unchanged]

-t, --expiry-ts <expiry_ts>

The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. Use -1 for no expiration. [default: unchanged]

-e, --expire-at <expire_at>

The latest time the registration token is valid. See above for available date/time formats. [default: unchanged]

Arguments

TOKEN

Required argument

Notice

synadm notice

Send messages to users.

synadm notice [OPTIONS] COMMAND [ARGS]...
send

Send server notices to users on the local homeserver.

TO
Localpart or full matrix ID of the notice receiver. If –regex is set
this will be interpreted as a regular expression.
PLAIN
Plain text content of the notice.
FORMATTED
Formatted content of the notice. If omitted, PLAIN will be used.
synadm notice send [OPTIONS] TO PLAIN [FORMATTED]

Options

-f, --from-file

Interpret arguments as file paths instead of notice content and read content from those files.

Default:

False

-p, --paginate <PAGINATE>

The send command retrieves “pages” of users from the homeserver, filters them and sends out the notices, before retrieving the next page. PAGINATE sets how many users are in each of these “pages”. It is a performance setting and may be useful for servers with a large amount of users.

Default:

100

-r, --regex

Interpret TO as regular expression.

Default:

False

-l, --preview-length <LENGTH>

Length of the displayed list of matched recipients shown in the confirmation prompt. Does not impact sending behavior. Is ignored when global –non-interactive flag is given.

Default:

10

-s, --silent

Usually synadm commands print to console what the API returned. With the “Server Notices Admin API”, an event ID or an error messages would be printed for each message sent. Large amounts of recipients could possibly lead to performance impacts, thus this option can be used to disable printing of what the API responded.

Default:

False

Arguments

TO

Required argument

PLAIN

Required argument

FORMATTED

Optional argument

Scripting Examples

This chapter should give some ideas on how synadm commands can be combinend to achieve functionality that is not directly covered by a single synadm command.

A handy command line tool to filter and postprocess json data is jq. Some of the examples in this chapter use it. Most Linux distros have it readily available in their main repos. Read `jq`s exhaustive man page to learn what’s possible.

Piping through jq prints out formatted and valid JSON data:

$ synadm -o json media list -u testuser1 | jq
{
  "media": [
    {
      "media_id": "zdkkcUmbHPoPKkvCyFMTDNOB",
      "media_type": "application/pdf",
      "media_length": 3235323,
      "upload_name": "some_document.pdf",
      "created_ts": "2021-04-16 07:59:10",
      "last_access_ts": null,
      "quarantined_by": "@admin:example.org",
      "safe_from_quarantine": false
    },
    {
      "media_id": "ZTxHWcvUUBSuSTNixMGEzeyj",
      "media_type": "application/pdf",
      "media_length": 8875938,
      "upload_name": "another_document.pdf",
      "created_ts": "2021-04-16 07:58:54",
      "last_access_ts": null,
      "quarantined_by": null,
      "safe_from_quarantine": false
    }
  ],
  "total": 2
}

The top-level JSON object contains a JSON array media which can be looped throuh with the jq syntax .media[]. To access specific properties of each array item we could use a shell loop like this:

$ for ID in `synadm -o json media list -u testuser1 | jq '.media[].media_id'`; do echo $ID; done
"zdkkcUmbHPoPKkvCyFMTDNOB"
"ZTxHWcvUUBSuSTNixMGEzeyj"

The ID’s we get could be passed to another synadm command, for example to remove those from quarantine.

$ for ID in `synadm -o json media list -u testuser1 | jq '.media[].media_id'`; do synadm media unquarantine -i $ID; done

Python Package Documentation

Synadm CLI Package

The synadm.cli package contains all the command line frontend code (using the Python Click module), see the sections for each subcommand for help on usage and have a look into the files inside the synadm/cli directory to see how the CLI frontend is constructed. The main command is defined in __init__.py and each subcommand lives in its own module (e.g user.py, room.py, …)

Click command definition code is not very well suited for autogenerated Python package documentations (in this case using Sphinx autodoc) but one thing in this package that is worth mentioning and generating documentation for, is the synadm.cli.APIHelper class which is the connection between the CLI code and the backend code in synadm.api:

CLI base functions and settings

class synadm.cli.APIHelper(config_path, verbose, batch, output_format_cli)

Bases: object

API client enriched with CLI-level functions, used as a proxy to the client object.

FORMATTERS = {'human': <function humanize>, 'json': <function APIHelper.<lambda>>, 'minified': <function APIHelper.<lambda>>, 'pprint': <function pformat>, 'yaml': <function dump>}
CONFIG = {'admin_path': '/_synapse/admin', 'base_url': 'http://localhost:8008', 'homeserver': 'auto-retrieval', 'matrix_path': '/_matrix', 'server_discovery': 'well-known', 'timeout': 30, 'token': '', 'user': ''}
init_logger(verbose)

Log both to console (defaults to WARNING) and file (DEBUG).

_set_formatter(_output_format)
load()

Load the configuration and initialize the client.

write_config(config)

Write a new version of the configuration to file.

output(data)

Output data object using the configured formatter.

retrieve_homeserver_name(uri=None)

Try to retrieve the homeserver name.

When homeserver is set in the config already, it’s just returned and nothing is tried to be fetched automatically. If not, either the location of the Federation API is looked up via a .well-known resource or a DNS SRV lookup. This depends on the server_discovery setting in the config. Finally the Federation API is used to retrieve the homeserver name.

Parameters:

uri (string) – proto://name:port or proto://fqdn:port

Returns:

hostname, FQDN or DOMAIN; or None on errors.

Return type:

string

generate_mxid(user_id)

Checks whether the given user ID is an MXID already or else generates it from the passed string and the homeserver name fetched via the retrieve_homeserver_name method.

Parameters:

user_id (string) – User ID given by user as command argument.

Returns:

the fully qualified Matrix User ID (MXID) or None if the

user_id parameter is None or no regex matched.

Return type:

string

Synadm Package

The synadm package contains the synadm.api module which is responsible for accessing the Synapse admin API endpoints and the regular Matrix API endpoints. Also some helper methods, e.g to calculate time-related things are to be found in this module:

Synapse admin API and regular Matrix API clients

Most API calls defined in this module respect the API’s defaults and only pass what’s necessary in the request body.

A fully qualified Matrix user ID looks like this: @user:server, where server often is a domain name only, e.g @user@example.org

See https://github.com/matrix-org/synapse/tree/master/docs/admin_api for documentation of the Synapse admin APIs and the Matrix spec at https://matrix.org/docs/spec/#matrix-apis.

class synadm.api.ApiRequest(log, user, token, base_url, path, timeout, debug)

Bases: object

Basic API request handling and helper utilities

This is subclassed by SynapseAdmin and Matrix

query(method, urlpart, params=None, data=None, token=None, base_url_override=None, verify=True)

Generic wrapper around requests methods.

Handles requests methods, logging and exceptions.

Parameters:
  • urlpart (string) – The path to the API endpoint, excluding self.base_url and self.path (the part after proto://fqdn:port/path).

  • params (dict, optional) – URL parameters (?param1&paarm2). Defaults to None.

  • data (dict, optional) – Request body used in POST, PUT, DELETE requests. Defaults to None.

  • base_url_override (bool) – The default setting of self.base_url set on initialization can be overwritten using this argument.

  • verify (bool) – Mandatory SSL verification is turned on by default and can be turned off using this method.

Returns:

Usually a JSON string containing

the response of the API; responses that are not 200(OK) (usally error messages returned by the API) will also be returned as JSON strings. On exceptions the error type and description are logged and None is returned.

Return type:

string or None

_timestamp_from_days_ago(days)

Get a unix timestamp in ms from days ago

Parameters:

days (int) – number of days

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_timestamp_from_days_ahead(days)

Get a unix timestamp in ms for the given number of days ahead

Parameters:

days (int) – number of days

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_timestamp_from_datetime(_datetime)

Get a unix timestamp in ms from a datetime object

Parameters:

_datetime (datetime object) – an object built by datetime.datetime

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_datetime_from_timestamp(timestamp, as_str=False)

Get a datetime object from a unix timestamp in ms

Parameters:

timestamp (int) – a unix timestamp in milliseconds (ms)

Returns:

an object built by datetime.datetime.

If as_str is set, return a string formatted by self._format_datetime() instead.

Return type:

datetime object

_format_datetime(datetime_obj)

Get a formatted date as a string.

Parameters:

datetime_obj (int) – A datetime object.

Returns:

A date in the format we use it throughout synadm. No sanity

checking.

Return type:

string

class synadm.api.MiscRequest(log, timeout, debug)

Bases: ApiRequest

Miscellaneous HTTP requests

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

federation_uri_well_known(base_url)

Retrieve the URI to the Server-Server (Federation) API port via the .well-known resource of a Matrix server/domain.

Parameters:

base_url – proto://name or proto://fqdn

Returns:

https://fqdn:port of the delegated server for Server-Server

communication between Matrix homeservers or None on errors.

Return type:

string

class synadm.api.Matrix(log, user, token, base_url, matrix_path, timeout, debug)

Bases: ApiRequest

Matrix API client

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

user_login(user_id, password)

Login as a Matrix user and retrieve an access token

Parameters:
  • user_id (string) – a fully qualified Matrix user ID

  • password (string) – the Matrix user’s password

Returns:

JSON string containing a token suitable to access the

Matrix API on the user’s behalf, a device_id and some more details on Matrix server and user.

Return type:

string

room_get_id(room_alias)

Get the room ID for a given room alias

Parameters:

room_alias (string) – A Matrix room alias (#name:example.org)

Returns:

A dict containing the room ID for the alias.

If room_id is missing in the response we return the whole response as it might contain Synapse’s error message.

Return type:

string, dict or None

room_get_aliases(room_id)

Get a list of room aliases for a given room ID

Parameters:

room_id (string) – A Matrix room ID (!abc123:example.org)

Returns:

A dict containing a list of room aliases, Synapse’s

error message or None on exceptions.

Return type:

dict or None

raw_request(endpoint, method, data, token=None)
server_name_keys_api(server_server_uri)

Retrieve the Matrix server’s own homeserver name via the Server-Server (Federation) API.

Parameters:

server_server_uri (string) – proto://name:port or proto://fqdn:port

Returns:

The Matrix server’s homeserver name or FQDN, usually something like matrix.DOMAIN or DOMAIN

Return type:

string

class synadm.api.SynapseAdmin(log, user, token, base_url, admin_path, timeout, debug)

Bases: ApiRequest

Synapse admin API client

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

user_list(_from, _limit, _guests, _deactivated, _name, _user_id)

List and search users

Parameters:
  • _from (int) – offsets user list by this number, used for pagination

  • _limit (int) – maximum number of users returned, used for pagination

  • _guests (bool) – enable/disable fetching of guest users

  • _deactivated (bool) – enable/disable fetching of deactivated users

  • _name (string) – user name localpart to search for, see Synapse admin API docs for details

  • _user_id (string) – fully qualified Matrix user ID to search for

Returns:

JSON string containing the found users

Return type:

string

user_membership(user_id, return_aliases, matrix_api)

Get a list of rooms the given user is member of

Parameters:
  • user_id (string) – Fully qualified Matrix user ID

  • room_aliases (bool) – Return human readable room aliases instead of room ID’s if applicable.

  • matrix_api (object) – An initialized Matrix object needs to be passes as we need some Matrix API functionality here.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

user_deactivate(user_id, gdpr_erase)

Delete a given user

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • gdpr_erase (bool) – enable/disable gdpr-erasing the user, see Synapse admin API docs for details.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

user_password(user_id, password, no_logout)

Set the user password, and log the user out if requested

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • password (string) – new password that should be set

  • no_logout (bool) – the API defaults to logging out the user after password reset via the admin API, this option can be used to disable this behaviour.

Returns:

JSON string containing the admin API’s response or None if an exception occured. See Synapse admin API docs for details.

Return type:

string

user_details(user_id)

Get information about a given user

Note that the admin API docs describe this function as “Query User Account”.

Parameters:

user_id (string) – fully qualified Matrix user ID

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

user_login(user_id, expire_days, expire, _expire_ts)

Get an access token that can be used to authenticate as that user.

If one of the args expire_days, expire or _expire_ts is set, the valid_until_ms field will be sent to the API endpoint. If this is not the case the default of the API would be used. At the time of writing, this would be that tokens never expire.

Note: If this method is called by the CLI frontend code (synadm.cli.user.user_login_cmd), a default expiry date of 1 day (24h) is passed.

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • expire_days (int) – token should expire after this number of days

  • expire (datetime) – token should expire after this date/time - a datetime object (e.g. as generated by Click.DateTime())

  • _expire_ts (int) – token should expire after this date/time - a unix timestamp in ms.

Returns:

JSON string containing the admin API’s response or None if an exception occured. See Synapse admin API docs for details.

Return type:

string

user_modify(user_id, password, display_name, threepid, avatar_url, admin, deactivation)

Create or update information about a given user

Threepid should be passed as a tuple in a tuple

user_whois(user_id)

Return information about the active sessions for a specific user

user_devices(user_id)

Return information about all devices for a specific user.

Parameters:

user_id (string) – Fully qualified Matrix user ID.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

user_devices_get_todelete(devices_data, min_days, min_surviving, device_id, readable_seen)

Gather a list of devices that possibly could be deleted.

This method is used by the ‘user prune-devices’ command.

Parameters:
  • devices_data (list) – Containing dicts of all the user’s devices, as returned by the user_devices method (the user/devices API endpoint).

  • min_days (int) – At least this number of days need to have passed from the last time a device was seen for it to be deleted. A reasonable default should be sent by the CLI level method.

  • min_surviving – At least this amount of devices will be kept alive. A reasonable default should be sent by the CLI level method.

  • device_id – Only search devices with this ID.

  • datetime – When True, ‘last seen timestamp’ is replaced with a human readable format.

Returns:

Containing dicts of devices that possibly could be deleted.

If non apply, an empty list is returned.

Return type:

list

user_devices_delete(user_id, devices)

Delete the specified devices for a specific user. Returns an empty JSON dict.

devices is a list of device IDs

Finds a user based on their ID (external id) in auth provider represented by auth provider id (provider).

Finds a user based on their Third Party ID by specifying what kind of 3PID it is as medium.

room_join(room_id_or_alias, user_id)

Allow an administrator to join an user account with a given user_id to a room with a given room_id_or_alias

room_list(_from, limit, name, order_by, reverse)

List and search rooms

room_details(room_id)

Get details about a room

room_members(room_id)

Get a list of room members

room_state(room_id)

Get a list of all state events in a room.

Parameters:

room_id (string) –

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

room_power_levels(from_, limit, name, order_by, reverse, room_id=None, all_details=True, output_format='json')

Get a list of configured power_levels in all rooms.

or a single room.

Parameters:

room_id (string) – If left out, all rooms are fetched.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

room_delete(room_id, new_room_user_id, room_name, message, block, no_purge)

Delete a room and purge it if requested

block_room(room_id, block)

Block or unblock a room.

Parameters:
  • room_id (string) – Required.

  • block (boolean) – Whether to block or unblock a room.

Returns:

JSON string containing the admin API’s response or None if

an exception occurred. See Synapse admin API docs for details.

Return type:

string

room_block_status(room_id)

Returns if the room is blocked or not, and who blocked it.

Parameters:

room_id (string) – Fully qualified Matrix room ID.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

room_make_admin(room_id, user_id)

Grant a user room admin permission. If the user is not in the room, and it is not publicly joinable, then invite the user.

room_media_list(room_id)

Get a list of known media in an (unencrypted) room.

media_quarantine(server_name, media_id)

Quarantine a single piece of local or remote media

media_unquarantine(server_name, media_id)

Removes a single piece of local or remote media from quarantine.

room_media_quarantine(room_id)

Quarantine all local and remote media in a room

user_media_quarantine(user_id)

Quarantine all local and remote media of a user

user_media(user_id, _from, limit, order_by, reverse, readable)

Get a user’s uploaded media

media_delete(server_name, media_id)

Delete a specific (local) media_id

media_delete_by_date_or_size(server_name, before_days, before, _before_ts, _size_gt, delete_profiles)

Delete local media by date and/or size FIXME and/or?

media_protect(media_id)

Protect a single piece of local or remote media

from being quarantined

purge_media_cache(before_days, before, _before_ts)

Purge old cached remote media

version()

Get the server version

group_delete(group_id)

Delete a local group (community)

purge_history(room_id, before_event_id, before_days, before, _before_ts, delete_local)

Purge room history

purge_history_status(purge_id)

Get status of a recent history purge

The status will be one of active, complete, or failed.

regtok_list(valid, readable_expiry)

List registration tokens

Parameters:
  • valid (bool) – List only valid (if True) or invalid (if False) tokens. Default is to list all tokens regardless of validity.

  • readable_expiry (bool) – If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

regtok_details(token, readable_expiry)

Get details about the given registration token

Parameters:
  • token (string) – The registration token in question

  • readable_expiry (bool) – If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

regtok_new(token, length, uses_allowed, expiry_ts, expire_at)

Create a new registration token

Parameters:
  • token (string) – Registration token to create. Default is randomly generated by the server.

  • length (int) – The length of the token to generate if the token is not provided.

  • uses_allowed (int) – The number of times the token can be used to complete a registration before it becomes invalid.

  • expiry_ts (int) – The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC.

  • expire_at (click.DateTime) – The latest time the registration token is valid.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

regtok_update(token, uses_allowed, expiry_ts, expire_at)

Update a registration token

Parameters:
  • token (string) – Registration token to update.

  • uses_allowed (int) – The number of times the token can be used to complete a registration before it becomes invalid.

  • expiry_ts (int) – The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. -1 indicates no expiry.

  • expire_at (click.DateTime) – The latest time the registration token is valid.

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

regtok_delete(token)

Delete a registration token

Parameters:

token (string) – The registration token to delete

Returns:

JSON string containing the admin API’s response or None if

an exception occured. See Synapse admin API docs for details.

Return type:

string

user_shadow_ban(user_id, unban)

Shadow-ban or unban a user.

Parameters:
  • user_id (string) – The user to be banned/unbanned.

  • unban (boolean) – Unban the specified user.

notice_send(receivers, content_plain, content_html, paginate, regex)

Send server notices.

Parameters:
  • receivers (string) – Target(s) of the notice. Either localpart or regular expression matching localparts.

  • content_plain (string) – Unformatted text of the notice.

  • content_html (string) – HTML-formatted text of the notice.

  • paginate (int) – Limits to how many users the notice is sent at once. Users are fetched with the user_list method and using its pagination capabilities.

  • to_regex (bool) – Selects whether receivers should be interpreted as a regular expression or a single recipient.

Returns:

A list of dictionaries, each containing the response of

what a single notice admin API call returned. Usually that is an event ID or an error. See Synapse admin API docs for details.

Return type:

list

Indices and tables