3

Post an unencrypted message

by
Published Aug 10, 2022

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

Script matrix Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 6 days ago
1
//native
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
  // Is it already a room ID?
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

Other submissions
  • Submitted by jaller94 Deno
    Created 398 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