3
Post an unencrypted message
One script reply has been approved by the moderators Verified

Post a plain text message to a Matrix chat room. The event type is "m.room.message" and the message type is "m.text".

Created by jaller94 834 days ago Viewed 13112 times
0
Submitted by jaller94 Deno
Verified 834 days ago
1
type Matrix = {
2
  baseUrl: string;
3
  token: string;
4
};
5
export async function main(matrix_res: Matrix, room: string, body: string) {
6
  if (!matrix_res.token) {
7
    throw Error("Sending a message requires an access token.");
8
  }
9
  const roomId = await resolveRoomAlias(matrix_res, room);
10
  const txnId = `${Math.random()}`;
11
  const resp = await fetch(
12
    `${matrix_res.baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(
13
      roomId,
14
    )}/send/m.room.message/${txnId}`,
15
    {
16
      method: "PUT",
17
      headers: {
18
        Accept: "application/json",
19
        Authorization: `Bearer ${matrix_res.token}`,
20
        "Content-Type": "application/json",
21
      },
22
      body: JSON.stringify({
23
        body,
24
        msgtype: "m.text",
25
      }),
26
    },
27
  );
28
  if (!resp.ok) {
29
    throw Error(`Failed to send message: Error HTTP${resp.status}`);
30
  }
31
  const eventId = (await resp.json())["event_id"];
32
  if (typeof eventId !== "string") {
33
    throw Error(
34
      `Faulty Matrix server implementation: Server didn't provide event_id for this message.`,
35
    );
36
  }
37
  return eventId;
38
}
39

40
/**
41
 * Resolves a room alias to a room id.
42
 * This is basically like resolving a domain name to an IP address.
43
 */
44
async function resolveRoomAlias(
45
  matrix_res: Matrix,
46
  room: string,
47
): Promise<string> {
48
  // Is it already a room ID?
49
  if (room.startsWith("!")) {
50
    return room;
51
  }
52
  const resp = await fetch(
53
    `${
54
      matrix_res.baseUrl
55
    }/_matrix/client/v3/directory/room/${encodeURIComponent(room)}`,
56
    {
57
      headers: {
58
        Accept: "application/json",
59
        ...(matrix_res.token && {
60
          Authorization: `Bearer ${matrix_res.token}`,
61
        }),
62
      },
63
    },
64
  );
65
  if (!resp.ok) {
66
    throw Error(`Failed to resolve room alias: Error HTTP${resp.status}`);
67
  }
68
  const roomId = (await resp.json())["room_id"];
69
  if (typeof roomId !== "string") {
70
    throw Error(
71
      `Faulty Matrix server implementation: Server didn't provide room_id for this alias.`,
72
    );
73
  }
74
  return roomId;
75
}
76