0

Send Message

by
Published today

Send a message on a conversation thread to a recipient.

Script hubspot Verified

The script

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

3
/**
4
 * Send Message
5
 * Send a message on a conversation thread to a recipient. `sender_actor_id` is an agent actor ID (A-<user ID>), `channel_id` and `channel_account_id` come from the thread or List Channel Accounts, and `recipient_type` is the kind of address in `recipient_value` (e.g. HS_EMAIL_ADDRESS). Requires conversations.write.
6
 */
7
export async function main(
8
  auth: RT.Hubspot,
9
  thread_id: string,
10
  text: string,
11
  sender_actor_id: string,
12
  channel_id: string,
13
  channel_account_id: string,
14
  recipient_type:
15
    | "HS_EMAIL_ADDRESS"
16
    | "HS_PHONE_NUMBER"
17
    | "CHANNEL_SPECIFIC_OPAQUE_ID",
18
  recipient_value: string,
19
  subject: string | undefined,
20
  rich_text: string | undefined,
21
  file_ids: string[] | undefined
22
) {
23
  const body: { [key: string]: any } = {
24
    type: "MESSAGE",
25
    text,
26
    senderActorId: sender_actor_id,
27
    channelId: channel_id,
28
    channelAccountId: channel_account_id,
29
    recipients: [
30
      {
31
        recipientField: "TO",
32
        deliveryIdentifiers: [{ type: recipient_type, value: recipient_value }],
33
      },
34
    ],
35
  }
36
  if (subject != null && subject !== "") body.subject = subject
37
  if (rich_text != null && rich_text !== "") body.richText = rich_text
38
  if (file_ids?.length) {
39
    body.attachments = file_ids.map((fileId) => ({ fileId, type: "FILE" }))
40
  }
41

42
  const response = await fetch(
43
    `https://api.hubapi.com/conversations/v3/conversations/threads/${thread_id}/messages`,
44
    {
45
      method: "POST",
46
      headers: {
47
        Authorization: `Bearer ${auth.token}`,
48
        "Content-Type": "application/json",
49
        Accept: "application/json",
50
      },
51
      body: JSON.stringify(body),
52
    }
53
  )
54

55
  if (!response.ok) {
56
    throw new Error(`${response.status} ${await response.text()}`)
57
  }
58

59
  return await response.json()
60
}
61