Edits history of script submission #23636 for ' List Chat Messages (ms_teams)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_chat_id = string
    
    // Dropdown of the connected user's chats, labelled by topic or member names.
    export async function chat_id(auth: RT.MsTeams) {
      const response = await fetch(
        `https://graph.microsoft.com/v1.0/me/chats?$expand=members&$top=50`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { value } = (await response.json()) as { value: any[] }
      return value.map((x) => ({
        value: x.id,
        label:
          x.topic ||
          (x.members ?? [])
            .map((m: any) => m.displayName)
            .filter(Boolean)
            .join(", ") ||
          x.chatType,
      }))
    }
    
    /**
     * List Chat Messages
     * List the messages of a chat, newest first. Pass the returned @odata.nextLink as `next_link` for the next page. Requires Chat.Read (covered by the default Chat.ReadWrite).
     */
    export async function main(
      auth: RT.MsTeams,
      chat_id: DynSelect_chat_id,
      top: number = 50,
      next_link: string | undefined
    ) {
      if (
        next_link != null &&
        next_link !== "" &&
        !next_link.startsWith("https://graph.microsoft.com/")
      ) {
        throw new Error(
          "next_link must be an @odata.nextLink returned by Microsoft Graph"
        )
      }
      let url: URL
      if (next_link != null && next_link !== "") {
        url = new URL(next_link)
      } else {
        url = new URL(
          `https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(chat_id)}/messages`
        )
        url.searchParams.append("$top", String(top))
        url.searchParams.append("$orderby", "createdDateTime desc")
      }
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 2 hours ago