Publish a message to a channel
One script reply has been approved by the moderators Verified

Publish a message to the specified channel

Created by hugo697 138 days ago
Submitted by hugo697 Bun
Verified 138 days ago
1
//native
2
type Ably = {
3
  apiKey: string;
4
};
5
/**
6
 * Publish a message to a channel
7
 * Publish a message to the specified channel
8
 */
9
export async function main(
10
  auth: Ably,
11
  channel_id: string,
12
  format: "json" | "jsonp" | "msgpack" | "html" | undefined,
13
  X_Ably_Version: string,
14
  body: {
15
    name?: string;
16
    data?: string;
17
    id?: string;
18
    timestamp?: number;
19
    encoding?: string;
20
    clientId?: string;
21
    connectionId?: string;
22
    extras?: {
23
      push?: {
24
        data?: string;
25
        notification?: {
26
          title?: string;
27
          body?: string;
28
          icon?: string;
29
          sound?: string;
30
          collapseKey?: string;
31
        };
32
        apns?: {
33
          notification?: {
34
            title?: string;
35
            body?: string;
36
            icon?: string;
37
            sound?: string;
38
            collapseKey?: string;
39
          };
40
        };
41
        fcm?: {
42
          notification?: {
43
            title?: string;
44
            body?: string;
45
            icon?: string;
46
            sound?: string;
47
            collapseKey?: string;
48
          };
49
        };
50
        web?: {
51
          notification?: {
52
            title?: string;
53
            body?: string;
54
            icon?: string;
55
            sound?: string;
56
            collapseKey?: string;
57
          };
58
        };
59
      };
60
    };
61
  },
62
) {
63
  const url = new URL(`https://rest.ably.io/channels/${channel_id}/messages`);
64
  for (const [k, v] of [["format", format]]) {
65
    if (v !== undefined && v !== "" && k !== undefined) {
66
      url.searchParams.append(k, v);
67
    }
68
  }
69
  const response = await fetch(url, {
70
    method: "POST",
71
    headers: {
72
      "X-Ably-Version": X_Ably_Version,
73
      "Content-Type": "application/json",
74
      Authorization: "Bearer " + auth.apiKey,
75
    },
76
    body: JSON.stringify(body),
77
  });
78
  if (!response.ok) {
79
    const text = await response.text();
80
    throw new Error(`${response.status} ${text}`);
81
  }
82
  return await response.json();
83
}
84