我现在使用Microsoft Bot Builder .NET SDK通过Emulator接收附件

时间:2017-09-28 13:18:58

标签: c# bots botframework chatbot

我正在为我的项目使用Microsoft的Bot builder SDK for .NET,我希望从Emulator接收附件并继续使用该流程。

当我从模拟器附加任何文件时,我遇到问题我没有获取上传文件的内容,内容URL也是一些我无法继续的localhost URL。

代码:

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
    var message = await result;
    var reply = context.MakeMessage();
}

var消息中的附件值:

enter image description here

我的问题是如何获取我上传的文件的内容和内容网址。

1 个答案:

答案 0 :(得分:1)

您无法获取内容。 Yoy需要使用ContentUrl下载它。请查看core-ReceiveAttachment示例,了解如何操作。

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var message = await argument;

    if (message.Attachments != null && message.Attachments.Any())
    {
        var attachment = message.Attachments.First();
        using (HttpClient httpClient = new HttpClient())
        {
            // Skype & MS Teams attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
            if ((message.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase) || message.ChannelId.Equals("msteams", StringComparison.InvariantCultureIgnoreCase)) 
                && new Uri(attachment.ContentUrl).Host.EndsWith("skype.com"))
            {
                var token = await new MicrosoftAppCredentials().GetTokenAsync();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }

            var responseMessage = await httpClient.GetAsync(attachment.ContentUrl);

            var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;

            await context.PostAsync($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received.");
        }
    }
    else
    {
        await context.PostAsync("Hi there! I'm a bot created to show you how I can receive message attachments, but no attachment was sent to me. Please, try again sending a new message including an attachment.");
    }

    context.Wait(this.MessageReceivedAsync);
}