【问题标题】:Discord.net bot not sending files with SocketTextChannel.SendFileAsync()Discord.net bot 不使用 SocketTextChannel.SendFileAsync() 发送文件
【发布时间】:2022-01-22 07:08:22
【问题描述】:

我正在为我的 discord 服务器开发一个机器人。机器人的功能之一 - 通过将此消息复制到特殊频道来批准玩家的提议(消息格式“文本 + 附件”)。我找不到使用SendMessageAsync 函数发送文件的方法,所以我使用SendFileAsync,就像这样:

        [Command("approve")]
        public async Task Approve([Remainder] ulong id)
        {
            var sourceMsg = await Context.Channel.GetMessageAsync(id);
            if (sourceMsg == null)
                return;
            await Context.Channel.SendMessageAsync($"Approving offer at {id}");
            var targetChannel = Context.Guild.TextChannels.Single(x => x.Name == _config["approved"]);

            if (sourceMsg.Attachments.Count > 0)
            {
                var httpClient = new HttpClient();
                var file = await httpClient.GetByteArrayAsync(sourceMsg.Attachments.ElementAt(0).Url);
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream(file))
                {
                    var fileAtt = new FileAttachment(stream, sourceMsg.Attachments.ElementAt(0).Filename);
                    await targetChannel.SendFileAsync(fileAtt, sourceMsg.Content);
                }

                return;
            }
            await Context.Channel.SendMessageAsync("Can not approve offer without attached songfile");
        }

问题是,当调用SendFileAsync 时,机器人由于某种未知原因挂起,没有抛出任何异常。

我在网上找了一个解决方案,但没有找到任何可以理解的东西

我还认为问题可能是在发送机器人之前使用HttpClient 下载文件,但是如果我指定了一个本地文件而不是下载的文件,直接放在包含机器人可执行文件的文件夹中,同样的事情发生了

我正在使用 Discord.Net v3.1.0、.NET Core 5.0

UPD:机器人仍在对命令做出反应,但每个新的“!批准”命令仍然冻结在 SendFileAsync

UPD2:好的,我解决了。问题是文件重量,太大了。默认情况下,Discord 用户可以发送重量不超过 8MB 的文件,但意外的是我所有的测试文件重量都超过了 8MB,所以 discord 阻止了文件发送,而且,我不知道为什么,bot 没有崩溃,也没有抛出任何东西例外。如果您也遇到此问题,请检查文件重量

【问题讨论】:

标签: c# .net-core bots .net-5 discord.net


【解决方案1】:

改变这一行 ` await Context.Channel.SendMessageAsync($"Approving offer at {id}");

` await Context.Channel.SendMessageAsync($"Approving offer at {id}").ConfigureAwait(true);

其他异步调用也做同样的事情

【讨论】:

  • 我已经尝试过了,但没有任何改变,当SendFileAsync 调用时,bot 仍然冻结,最重要的是 bot 不会崩溃并且仍然对其他命令做出反应
  • 不知道为什么它被否决了。
猜你喜欢
  • 2020-10-11
  • 2017-09-20
  • 1970-01-01
  • 2018-07-29
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 2022-01-04
相关资源
最近更新 更多