Descargar anexos de ficheiros desde un bot de Azure

Este artigo describe como descargar anexos de ficheiros dun bot Azure usado con mensaxería no Servizo de Atención ao Cliente de Dynamics 365.

Para descargar anexos dun bot de Azure, completa os seguintes pasos:

  1. Obtén o token para o teu bot usando o ID da aplicación Microsoft e o segredo do cliente do teu bot.

  2. Obtén o attachmentId do amsReferences array nos datos do canal da actividade.

    Por exemplo, se o amsReferences contén ["0-eus-d1-5360689c55c308cb4e3b51722e46b801"], entón o attachmentId é 0-eus-d1-5360689c55c308cb4e3b51722e46b801.

  3. Inserir o attachmentIdRequestUri nunha variable e logo usar RequestUri nunha solicitude GET , como este:

string requestUri = $"https://botapi.skype.com/amer/v3/attachments/{attachmentId}/views/original";
var httpRequest = new HttpRequestMessage(HttpMethod.Get, requestUri);

var authorization = new AuthenticationHeaderValue("bearer", <add the botToken here>);
httpRequest.Headers.Authorization = authorization;
httpRequest.Headers.Add("BotAcsId", activity.Recipient.Id);

HttpResponseMessage response = await client.SendAsync(httpRequest);

Xestionar os anexos de ficheiros

Nota

A información nesta sección é aplicable só á Nube da Comunidade do Goberno (GCC).

Esta sección describe como xestionar os anexos de ficheiros no canal de mensaxería.

Primeiro, revisa os formatos de arquivos anexos no canal de mensaxería.

Formatos de ficheiros anexos

Cando se envían anexos de ficheiros desde o Centro de Contacto de Dynamics 365 ao axente Azure no canal de mensaxería, a información necesaria para descargar os ficheiros pásase nos amsReferences campos e amsMetadata da Activity.ChannelData propiedade.

Canle de mensaxería

{
   "recipient":{
      "id":"8:acs:5ecf37b1-11 Oc-414g-ab33-804ffd6b4a33_eooe0010-7c57-1ceb-nec-113aOdOOb272",
      "name":"Omnichannel-test-bot",
      "aadObjectId":null,
      "role":null
   },
   "attachments ":null,
   "channelData":{
      "tags":"Channelld-lcw,FromCustomer",
      "deliveryMode":"bridged",
      "fromUserId":"8:acs:5ecf37b1-110c-4149-ab33-804ffd6b4a33_00000010-61 b9-ab1 d-3dfe-9c3aOd009ea4",
      "amsReferences":[
         "0-wus-d6-20e7797d208fab388cc11b09674d166"
      ],
      "amsMetadata":[
         {
            "contentType":"image/png",
            "fileName":"SurnmerTime.png"
         }
      ],
      "sourceChannelId":"omnichannel"
   }
}

Como xestionar os anexos de ficheiros no código do teu axente de Azure

A información de anexo pásase no canal de servizo do axente omnicanle e pode accederse en código do axente, como se mostra no seguinte exemplo.

// 1. Retrieve Attachment ID from ChannelData["amsReferences"]
if (activity.ChannelData != null &&
    activity.ChannelData is Dictionary<string, JsonElement> channelData &&
    channelData.TryGetValue("amsReferences", out var amsReferencesElement))
{
    var amsReferencesString = amsReferencesElement.GetString() ?? amsReferencesElement.ToString();
    string attachmentId = JsonConvert.DeserializeObject<string[]>(amsReferencesString).FirstOrDefault();

    // 2. Build HTTP request for specified attachment ID.
    string requestUri = $"https://botapi.skype.com/amer/v3/attachments/{attachmentId}/views/original";
    var httpRequest = new HttpRequestMessage(HttpMethod.Get, requestUri);

    // 3. Acquire authentication token and add it to request headers
    // Option A: Using IConnections (recommended)
    var connection = connections.GetConnection("ServiceConnection");
    var token = await connection.GetAccessTokenAsync(
        "https://api.botframework.com",
        new[] { "https://api.botframework.com/.default" },
        forceRefresh: false);

    // Option B: Using OAuth client credentials flow
    // var tokenRequest = new HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token")
    // {
    //     Content = new FormUrlEncodedContent(new Dictionary<string, string>
    //     {
    //         { "grant_type", "client_credentials" },
    //         { "client_id", botAppId },
    //         { "client_secret", botAppSecret },
    //         { "scope", "https://api.botframework.com/.default" }
    //     })
    // };
    // var tokenResponse = await client.SendAsync(tokenRequest);
    // var tokenContent = await tokenResponse.Content.ReadAsStringAsync();
    // var token = JsonConvert.DeserializeObject<dynamic>(tokenContent).access_token;

    var authorization = new AuthenticationHeaderValue("bearer", token);
    httpRequest.Headers.Add("Authorization", authorization.ToString());

    // 4. Add Azure Communication Services Bot ID to request header. This is required to achieve good download performance.
    httpRequest.Headers.Add("BotAcsId", activity.Recipient.Id);

    // 5. Use HttpClient to execute the request and download attachment
    var response = await client.SendAsync(httpRequest);

    // 6. Save HTTP response stream to the file
    var responseContentStream = await response.Content.ReadAsStreamAsync();
    using (FileStream fileCreateStream = new FileStream("file path", FileMode.Create))
    {
        await responseContentStream.CopyToAsync(fileCreateStream);
    }
}

Soporte para tarxetas por canle
Soporte para chat en directo e canles asíncronas