1
Is a Matrix user X a joined member of a Matrix room Y?
One script reply has been approved by the moderators Verified

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.

Created by jaller94 766 days ago Viewed 9310 times
0
Submitted by jaller94 Deno
Verified 766 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