Discord Bot MessageDeleted 事件处理程序无法正常工作

Discord Bot MessageDeleted event handler not working correctly

我想制作一个记录已删除消息的 discord 机器人。

所以我制作了 MessageDeleted 事件处理程序,但它无法正常工作。

我找不到我的代码有什么问题。

private async Task Client_MessageDeleted(Cacheable<IMessage, ulong> arg1, ISocketMessageChannel channel)
{
    Task<IMessage> msg = arg1.GetOrDownloadAsync();
    EmbedBuilder embed = new EmbedBuilder();

    embed.WithColor(40, 200, 150);
    embed.AddField("deleted message", msg.ToString());

    await channel.SendMessageAsync("", false, embed.Build());
}

替换

embed.AddField("deleted message", msg.ToString());

embed.AddField("deleted message", msg.Content);

通过https://discord.foxbot.me/docs/api/Discord.IMessage.html

我之前没有开发过 Discord Bot,所以请原谅我的无知,但我假设是这样的:

Task<IMessage> msg = arg1.GetOrDownloadAsync();

实际上应该是:

IMessage msg = await arg1.GetOrDownloadAsync();

正如其他人所指出的,您必须等待您的任务。但是,您缺少一项关键配置 - 启用消息缓存。对于 Discord.Net 和 MessageDeleted 事件,为了检索消息,您必须启用缓存,因为您无法从 Discord 服务器检索已删除的消息。要启用缓存,请在 DiscordSocketConfig 对象中设置 MessageCacheSize 并将其传递给 DiscordSocketClient

设置缓存

var config = new DiscordSocketConfig {MessageCacheSize = 100};
var client = new DiscordSocketClient(config);

正在从缓存中获取已删除的消息

private Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, ISocketMessageChannel channel)
{
    Console.WriteLine(msg.HasValue ? 
        msg.Value.Content : 
        "A message was deleted, but its content could not be retrieved from cache.");
    return Task.CompletedTask;
}

此事件在 Discord.Net 文档中有详细记录,请参阅 MessageDeleted event