I wanted a quick and easy way to see how many registered users there are on my Matrix homeserver without having to log in to the admin interface, so I wrote a short bash script.
1. git clone https://github.com/drakfrid/matrix-list-number-of-users.git
2. sh ./matrix-count-users.shCode language: PHP (php)
#!/bin/bash
# Lists the number of registered users on a Matrix homeserver according to
# https://matrix-org.github.io/synapse/develop/admin_api/user_admin_api.html#list-accounts
# Version 1.1, 2022-02-20
echo "Please enter your homeserver URL (e.g. matrix.example.com)"
read HOMESERVER
if [[ -z "$HOMESERVER" ]]
then
while [[ -z "$HOMESERVER" ]]
do
echo "No admin access token entered"
echo "Please enter your admin access token"
read HOMESERVER
done
fi
echo "Please enter your admin access token"
read -s TOKEN
if [[ -z "$TOKEN" ]]
then
while [[ -z "$TOKEN" ]]
do
echo "No admin access token entered"
echo "Please enter your admin access token"
read -s TOKEN
done
fi
users=$(curl --silent -H "Authorization: Bearer $TOKEN" \
"https://$HOMESERVER/_synapse/admin/v2/users?from=0&limit=100000&guests=false")
if [[ "$users" =~ "M_UNKNOWN_TOKEN" ]]
then
echo "ERROR: Invalid access token"
exit 1
elif [[ "$users" =~ "error" ]]
then
echo "ERROR: An error occured"
echo $users
exit 2
fi
numberOfUsers=$(echo "$users" | tail -c 8 | grep -Eo "[0-99999]+")
echo "There are" $numberOfUsers "users on $HOMESERVER (non-deactivated) \
as of" $(date)
echo "There are" $numberOfUsers "users on $HOMESERVER (non-deactivated) \
as of" $(date) >> users.txtCode language: PHP (php)
Here’s what it does:
read [-s] TOKEN asks the user for an input, where you enter your homeserver URL and admin access token. The input is sent with the curl request to the matrix server (according to the Synapse API, and excluding guests).
As the JSON response includes the number of users last in the response I simply cut the last 8 bytes and search for the number of users with grep -Eo (-E for extended regexp and -o for non-empty parts). The output is stored in the variable numberOfUsers, which is written to the console as well as a users.txt file.
The final output looks something like,
There are X users on yourserver.com (non-deactivated) as of fre 14 jan 2022 16:15:14 CETCode language: CSS (css)
It works, but the code is perhaps not the best 😉
The JSON response will be quite long if you try to fetch thousands of users at once, so not sure if the code works then. I’m also not entirely sure this code is 100% safe if a user has an odd nickname, so use on your own risk.
Updated 2022-05-24