Edits history of script submission #23645 for ' Send Chat Message (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,
      }))
    }
    
    /**
     * Send Chat Message
     * 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).
     */
    export async function main(
      auth: RT.MsTeams,
      chat_id: DynSelect_chat_id,
      message: string,
      content_type: "text" | "html" = "text"
    ) {
      const payload: { [key: string]: any } = {
        body: { contentType: content_type, content: message },
      }
    
      const response = await fetch(
        `https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(chat_id)}/messages`,
        {
          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