//native
/**
* Send Message via Webhook
* Post a message to a Chat space through its incoming webhook, as the webhook (no OAuth connection or Chat app needed). Send `text` (Chat markup: `*bold*`, `_italic_`, `<users/123>` mentions), `cards_v2` (a list of `{ cardId, card }` objects), or both. Set `thread_key` to group messages into a thread; `message_reply_option` picks whether a missing thread is created (REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD, the default when a key is set) or the message fails (REPLY_MESSAGE_OR_FAIL). Google allows 1 request per second per space, shared by all its webhooks.
*/
export async function main(
auth: RT.GchatWebhook,
text: string | undefined,
cards_v2: { [key: string]: any }[] | undefined,
thread_key: string | undefined,
message_reply_option:
| "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
| "REPLY_MESSAGE_OR_FAIL"
| undefined
) {
if (!text && !cards_v2?.length) {
throw new Error("Set text, cards_v2 or both")
}
if (message_reply_option && !thread_key) {
throw new Error("message_reply_option needs a thread_key")
}
const url = new URL(auth.url)
const body: { [key: string]: any } = {
text: text || undefined,
cardsV2: cards_v2?.length ? cards_v2 : undefined,
}
if (thread_key) {
body.thread = { threadKey: thread_key }
url.searchParams.set(
"messageReplyOption",
message_reply_option || "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
)
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
Accept: "application/json",
},
body: JSON.stringify(body),
})
if (response.status === 429) {
const retry = response.headers.get("Retry-After")
throw new Error(
`429 rate limited: Google Chat allows 1 request per second per space, shared by all its webhooks${
retry ? `; retry after ${retry}s` : ""
}. ${await response.text()}`
)
}
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
Submitted by hugo989 1 day ago