0

Send Message

by
Published today

Post a text message to a Google Chat space, optionally in a thread.

Script gchat Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
export type DynSelect_space = string
4

5
// Dropdown of the spaces, group chats and DMs the user is a member of.
6
export async function space(auth: RT.Gchat) {
7
  const response = await fetch(
8
    "https://chat.googleapis.com/v1/spaces?pageSize=1000",
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { spaces } = (await response.json()) as {
20
    spaces?: { name: string; displayName?: string; spaceType: string }[]
21
  }
22
  return (spaces ?? []).map((s) => ({
23
    value: s.name,
24
    label: s.displayName
25
      ? `${s.displayName} (${s.name})`
26
      : `${s.spaceType} ${s.name}`,
27
  }))
28
}
29

30
/**
31
 * Send Message
32
 * Post a text message to a Chat space as the connected user. Supports Chat's markup (`*bold*`, `_italic_`, `<users/123>` mentions). Set `thread_key` to group messages into the same thread: the first message with a key starts the thread, later ones reply in it.
33
 */
34
export async function main(
35
  auth: RT.Gchat,
36
  space: DynSelect_space,
37
  text: string,
38
  thread_key: string | undefined
39
) {
40
  const url = new URL(`https://chat.googleapis.com/v1/${space}/messages`)
41
  const body: { [key: string]: any } = { text }
42
  if (thread_key !== undefined && thread_key !== "") {
43
    url.searchParams.append(
44
      "messageReplyOption",
45
      "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
46
    )
47
    body.thread = { threadKey: thread_key }
48
  }
49

50
  const response = await fetch(url, {
51
    method: "POST",
52
    headers: {
53
      Authorization: `Bearer ${auth.token}`,
54
      "Content-Type": "application/json",
55
      Accept: "application/json",
56
    },
57
    body: JSON.stringify(body),
58
  })
59
  if (!response.ok) {
60
    throw new Error(`${response.status} ${await response.text()}`)
61
  }
62

63
  return await response.json()
64
}
65