0

Send Chat Message

by
Published today

Send a message to a one-on-one, group or meeting chat as the connected user, as plain text or HTML. Requires ChatMessage.Send (covered by the default Chat.ReadWrite).

Script ms_teams Verified

The script

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

3
export type DynSelect_chat_id = string
4

5
// Dropdown of the connected user's chats, labelled by topic or member names.
6
export async function chat_id(auth: RT.MsTeams) {
7
  const response = await fetch(
8
    `https://graph.microsoft.com/v1.0/me/chats?$expand=members&$top=50`,
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 { value } = (await response.json()) as { value: any[] }
20
  return value.map((x) => ({
21
    value: x.id,
22
    label:
23
      x.topic ||
24
      (x.members ?? [])
25
        .map((m: any) => m.displayName)
26
        .filter(Boolean)
27
        .join(", ") ||
28
      x.chatType,
29
  }))
30
}
31

32
/**
33
 * Send Chat Message
34
 * Send a message to a one-on-one, group or meeting chat as the connected user, as plain text or HTML. Requires ChatMessage.Send (covered by the default Chat.ReadWrite).
35
 */
36
export async function main(
37
  auth: RT.MsTeams,
38
  chat_id: DynSelect_chat_id,
39
  message: string,
40
  content_type: "text" | "html" = "text"
41
) {
42
  const payload: { [key: string]: any } = {
43
    body: { contentType: content_type, content: message },
44
  }
45

46
  const response = await fetch(
47
    `https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(chat_id)}/messages`,
48
    {
49
      method: "POST",
50
      headers: {
51
        Authorization: `Bearer ${auth.token}`,
52
        "Content-Type": "application/json",
53
        Accept: "application/json",
54
      },
55
      body: JSON.stringify(payload),
56
    }
57
  )
58

59
  if (!response.ok) {
60
    throw new Error(`${response.status} ${await response.text()}`)
61
  }
62

63
  return await response.json()
64
}
65