1

Is a Matrix user X a joined member of a Matrix room Y?

by
Published Nov 17, 2022

This function throws an error, if you're not a room member. Otherwise, it returns a boolean "is_joined". Furthermore, it returns the user info provided by the server.

Script matrix Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 6 days ago
1
//native
2

3
/**
4
 * This function throws an error, if you're not a room member.
5
 *
6
 * Expected return values:
7
 *
8
 * {
9
 *   "is_joined": false,
10
 *   "user_info": null
11
 * }
12
 *
13
 * or
14
 *
15
 * {
16
 *   "is_member": true,
17
 *   "user_info": {
18
 *     "avatar_url": "mxc://matrix.org/abc123",
19
 *     "display_name": "Jane Doe"
20
 *   }
21
 * }
22
 */
23
type Matrix = {
24
  baseUrl: string;
25
  token: string;
26
};
27
export async function main(
28
  matrix_res: Matrix,
29
  room_id: string,
30
  user_id: string,
31
) {
32
  const url = `${
33
    matrix_res.baseUrl
34
  }/_matrix/client/v3/rooms/${encodeURIComponent(room_id)}/joined_members`;
35
  const resp = await fetch(url, {
36
    headers: {
37
      Authorization: `Bearer ${matrix_res.token}`,
38
    },
39
  });
40
  if (!resp.ok) {
41
    throw Error(`Failed to fetch joined member list: Error HTTP${resp.status}`);
42
  }
43
  const data = await resp.json();
44
  return {
45
    is_joined: user_id in data?.joined,
46
    user_info: data?.joined?.[user_id],
47
  };
48
}
49

Other submissions
  • Submitted by jaller94 Deno
    Created 398 days ago
    1
    /**
    2
     * This function throws an error, if you're not a room member.
    3
     *
    4
     * Expected return values:
    5
     *
    6
     * {
    7
     *   "is_joined": false,
    8
     *   "user_info": null
    9
     * }
    10
     *
    11
     * or
    12
     *
    13
     * {
    14
     *   "is_member": true,
    15
     *   "user_info": {
    16
     *     "avatar_url": "mxc://matrix.org/abc123",
    17
     *     "display_name": "Jane Doe"
    18
     *   }
    19
     * }
    20
     */
    21
    type Matrix = {
    22
      baseUrl: string;
    23
      token: string;
    24
    };
    25
    export async function main(
    26
      matrix_res: Matrix,
    27
      room_id: string,
    28
      user_id: string,
    29
    ) {
    30
      const url = `${
    31
        matrix_res.baseUrl
    32
      }/_matrix/client/v3/rooms/${encodeURIComponent(room_id)}/joined_members`;
    33
      const resp = await fetch(url, {
    34
        headers: {
    35
          Authorization: `Bearer ${matrix_res.token}`,
    36
        },
    37
      });
    38
      if (!resp.ok) {
    39
        throw Error(`Failed to fetch joined member list: Error HTTP${resp.status}`);
    40
      }
    41
      const data = await resp.json();
    42
      return {
    43
        is_joined: user_id in data?.joined,
    44
        user_info: data?.joined?.[user_id],
    45
      };
    46
    }
    47