1 | |
2 |
|
3 | |
4 | * Create Chat |
5 | * Create a chat between the connected user and the given users (ids or user principal names): one-on-one for a single user, a group chat with an optional topic for several. A one-on-one chat that already exists is returned instead of duplicated. Requires Chat.Create (covered by the default Chat.ReadWrite) and User.Read. |
6 | */ |
7 | export async function main( |
8 | auth: RT.MsTeams, |
9 | members: string[], |
10 | topic: string | undefined |
11 | ) { |
12 | const meResponse = await fetch( |
13 | `https://graph.microsoft.com/v1.0/me?$select=id`, |
14 | { |
15 | headers: { |
16 | Authorization: `Bearer ${auth.token}`, |
17 | Accept: "application/json", |
18 | }, |
19 | } |
20 | ) |
21 | if (!meResponse.ok) { |
22 | throw new Error(`${meResponse.status} ${await meResponse.text()}`) |
23 | } |
24 | const { id: me } = (await meResponse.json()) as { id: string } |
25 |
|
26 | |
27 | const ids = [me, ...members.filter((m) => m !== "" && m !== me)] |
28 | if (ids.length < 2) { |
29 | throw new Error("members must name at least one other user") |
30 | } |
31 | const group = ids.length > 2 |
32 | const payload: { [key: string]: any } = { |
33 | chatType: group ? "group" : "oneOnOne", |
34 | members: ids.map((id) => ({ |
35 | "@odata.type": "#microsoft.graph.aadUserConversationMember", |
36 | roles: ["owner"], |
37 | "[email protected]": `https://graph.microsoft.com/v1.0/users('${encodeURIComponent(id).replaceAll("'", "''")}')`, |
38 | })), |
39 | } |
40 | if (group && topic != null && topic !== "") { |
41 | payload.topic = topic |
42 | } |
43 |
|
44 | const response = await fetch(`https://graph.microsoft.com/v1.0/chats`, { |
45 | method: "POST", |
46 | headers: { |
47 | Authorization: `Bearer ${auth.token}`, |
48 | "Content-Type": "application/json", |
49 | Accept: "application/json", |
50 | }, |
51 | body: JSON.stringify(payload), |
52 | }) |
53 |
|
54 | if (!response.ok) { |
55 | throw new Error(`${response.status} ${await response.text()}`) |
56 | } |
57 |
|
58 | return await response.json() |
59 | } |
60 |
|