Edits history of script submission #23628 for ' Create Chat (ms_teams)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Chat
     * 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.
     */
    export async function main(
      auth: RT.MsTeams,
      members: string[],
      topic: string | undefined
    ) {
      const meResponse = await fetch(
        `https://graph.microsoft.com/v1.0/me?$select=id`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!meResponse.ok) {
        throw new Error(`${meResponse.status} ${await meResponse.text()}`)
      }
      const { id: me } = (await meResponse.json()) as { id: string }
    
      // Graph requires the caller in the member list
      const ids = [me, ...members.filter((m) => m !== "" && m !== me)]
      if (ids.length < 2) {
        throw new Error("members must name at least one other user")
      }
      const group = ids.length > 2
      const payload: { [key: string]: any } = {
        chatType: group ? "group" : "oneOnOne",
        members: ids.map((id) => ({
          "@odata.type": "#microsoft.graph.aadUserConversationMember",
          roles: ["owner"],
          "[email protected]": `https://graph.microsoft.com/v1.0/users('${encodeURIComponent(id).replaceAll("'", "''")}')`,
        })),
      }
      if (group && topic != null && topic !== "") {
        payload.topic = topic
      }
    
      const response = await fetch(`https://graph.microsoft.com/v1.0/chats`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(payload),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 2 hours ago