0

Send Channel Message

by
Published today

Post a new message to a channel as the connected user, as plain text or HTML, with an optional subject line. Requires ChannelMessage.Send (a connection default).

Script ms_teams Verified

The script

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

3
export type DynSelect_team_id = string
4

5
// Dropdown of the teams the connected user has joined.
6
export async function team_id(auth: RT.MsTeams) {
7
  const response = await fetch(
8
    `https://graph.microsoft.com/v1.0/me/joinedTeams`,
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) => ({ value: x.id, label: x.displayName }))
21
}
22

23
export type DynSelect_channel_id = string
24

25
// Dropdown of the chosen team's channels.
26
export async function channel_id(auth: RT.MsTeams, team_id: string) {
27
  if (team_id == null || team_id === "") return []
28
  const response = await fetch(
29
    `https://graph.microsoft.com/v1.0/teams/${encodeURIComponent(team_id)}/channels`,
30
    {
31
      headers: {
32
        Authorization: `Bearer ${auth.token}`,
33
        Accept: "application/json",
34
      },
35
    }
36
  )
37
  if (!response.ok) {
38
    throw new Error(`${response.status} ${await response.text()}`)
39
  }
40
  const { value } = (await response.json()) as { value: any[] }
41
  return value.map((x) => ({ value: x.id, label: x.displayName }))
42
}
43

44
/**
45
 * Send Channel Message
46
 * Post a new message to a channel as the connected user, as plain text or HTML, with an optional subject line. Requires ChannelMessage.Send (a connection default).
47
 */
48
export async function main(
49
  auth: RT.MsTeams,
50
  team_id: DynSelect_team_id,
51
  channel_id: DynSelect_channel_id,
52
  message: string,
53
  content_type: "text" | "html" = "text",
54
  subject: string | undefined
55
) {
56
  const payload: { [key: string]: any } = {
57
    body: { contentType: content_type, content: message },
58
  }
59
  if (subject != null && subject !== "") {
60
    payload.subject = subject
61
  }
62

63
  const response = await fetch(
64
    `https://graph.microsoft.com/v1.0/teams/${encodeURIComponent(team_id)}/channels/${encodeURIComponent(channel_id)}/messages`,
65
    {
66
      method: "POST",
67
      headers: {
68
        Authorization: `Bearer ${auth.token}`,
69
        "Content-Type": "application/json",
70
        Accept: "application/json",
71
      },
72
      body: JSON.stringify(payload),
73
    }
74
  )
75

76
  if (!response.ok) {
77
    throw new Error(`${response.status} ${await response.text()}`)
78
  }
79

80
  return await response.json()
81
}
82