收到403(禁止),Microsoft Bot正在尝试进行Web客户端下载数据呼叫

本文关键字:Web 客户端 呼叫 数据 下载 禁止 Bot Microsoft 收到 | 更新日期: 2023-09-27 18:05:24

我正在尝试使用Microsoft BotFramework创建一个机器人

我面临的问题是,当机器人代码试图通过Facebook messenger/Skype/Slack等任何渠道下载数据(由用户上传到机器人的图像)时。下载代码是通过创建一个WebClient并通过传递附件URL进行DownloadData调用来实现的。

我可以浏览上传的图像URL。此外,如果我编写控制台应用程序而不是Bot应用程序,则通过web客户端下载数据的代码可以正常工作。

c#代码片段
WebClient wc = new WebClient(); 
byte[] bytes = wc.DownloadData(imageUrl); // This line gives 403 error

请建议如何解决这个问题

收到403(禁止),Microsoft Bot正在尝试进行Web客户端下载数据呼叫

这个问题的完整修复:

    private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity)
    {
        var attachments = activity?.Attachments?
        .Where(attachment => attachment.ContentUrl != null)
        .Select(c => Tuple.Create(c.ContentType, c.ContentUrl));
        if (attachments != null && attachments.Any())
        {
            var contentBytes = new List<byte[]>();
            using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                var token = await (connectorClient.Credentials as MicrosoftAppCredentials).GetTokenAsync();
                foreach (var content in attachments)
                {
                    var uri = new Uri(content.Item2);
                    using (var httpClient = new HttpClient())
                    {
                        if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
                        {
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
                        }
                        else
                        {
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(content.Item1));
                        }
                        contentBytes.Add(await httpClient.GetByteArrayAsync(uri));
                    }
                }
            }
            return contentBytes;
        }
        return null;
    }

https://github.com/Microsoft/BotBuilder/issues/662#issuecomment-232223965

你是说这个修复?这对你有用吗?

我正在使用BotFramework与Node.js并收到相同的错误。最后我找到了一个解决办法。我在ChatConnector.js中注释了下面的行,现在对我来说工作得很好。

if (isEmulator && decoded_1.payload.appid != this.settings.appId) {
       logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
       res.status(403);
        res.end();
         return;
    }

if (issimulator &&decoded_1.payload。= this.settings.appId) {记录器。ChatConnector:接收到的令牌无效。请求由意外的应用ID。');res.status (403);res.end ();返回;}