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

时间:2019-01-11 05:17:14

标签: c# discord.net

我想创建一个记录已删除消息的不和谐机器人。

所以我做了MessageDeleted事件处理程序,但是它不能正常工作。

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

Result

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());
}

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

在宽恕我的无知之前,我还没有开发过Discord Bot,但是我认为这句话:

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

实际上应该是:

IMessage msg = await arg1.GetOrDownloadAsync();

答案 2 :(得分:0)

替换

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

使用

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

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