【发布时间】: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 没有崩溃,也没有抛出任何东西例外。如果您也遇到此问题,请检查文件重量
【问题讨论】:
-
一般来说异步操作应该被等待,并且可能需要配置等待,以便可以捕获或不捕获上下文。 docs.microsoft.com/en-us/dotnet/api/…
标签: c# .net-core bots .net-5 discord.net