1 | |
2 |
|
3 | type Matrix = { |
4 | baseUrl: string; |
5 | token: string; |
6 | }; |
7 | export async function main(matrix_res: Matrix, room: string, body: string) { |
8 | if (!matrix_res.token) { |
9 | throw Error("Sending a message requires an access token."); |
10 | } |
11 | const roomId = await resolveRoomAlias(matrix_res, room); |
12 | const txnId = `${Math.random()}`; |
13 | const resp = await fetch( |
14 | `${matrix_res.baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent( |
15 | roomId, |
16 | )}/send/m.room.message/${txnId}`, |
17 | { |
18 | method: "PUT", |
19 | headers: { |
20 | Accept: "application/json", |
21 | Authorization: `Bearer ${matrix_res.token}`, |
22 | "Content-Type": "application/json", |
23 | }, |
24 | body: JSON.stringify({ |
25 | body, |
26 | msgtype: "m.text", |
27 | }), |
28 | }, |
29 | ); |
30 | if (!resp.ok) { |
31 | throw Error(`Failed to send message: Error HTTP${resp.status}`); |
32 | } |
33 | const eventId = (await resp.json())["event_id"]; |
34 | if (typeof eventId !== "string") { |
35 | throw Error( |
36 | `Faulty Matrix server implementation: Server didn't provide event_id for this message.`, |
37 | ); |
38 | } |
39 | return eventId; |
40 | } |
41 |
|
42 | |
43 | * Resolves a room alias to a room id. |
44 | * This is basically like resolving a domain name to an IP address. |
45 | */ |
46 | async function resolveRoomAlias( |
47 | matrix_res: Matrix, |
48 | room: string, |
49 | ): Promise<string> { |
50 | |
51 | if (room.startsWith("!")) { |
52 | return room; |
53 | } |
54 | const resp = await fetch( |
55 | `${ |
56 | matrix_res.baseUrl |
57 | }/_matrix/client/v3/directory/room/${encodeURIComponent(room)}`, |
58 | { |
59 | headers: { |
60 | Accept: "application/json", |
61 | ...(matrix_res.token && { |
62 | Authorization: `Bearer ${matrix_res.token}`, |
63 | }), |
64 | }, |
65 | }, |
66 | ); |
67 | if (!resp.ok) { |
68 | throw Error(`Failed to resolve room alias: Error HTTP${resp.status}`); |
69 | } |
70 | const roomId = (await resp.json())["room_id"]; |
71 | if (typeof roomId !== "string") { |
72 | throw Error( |
73 | `Faulty Matrix server implementation: Server didn't provide room_id for this alias.`, |
74 | ); |
75 | } |
76 | return roomId; |
77 | } |
78 |
|