Discord Bot MessageDeleted event handler not working correctly

I want make a discord bot that logs deleted message.

So I made MessageDeleted event handler but it's not working correctly.

I can't find what's wrong with my code.


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 answers

  • answered 2019-01-11 05:26 user326608


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


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

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

  • answered 2019-01-11 05:28 rshepp

    I haven't developed a Discord Bot before so forgive my ignorance, but I assume this line:

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

    Should actually be:

    IMessage msg = await arg1.GetOrDownloadAsync();

  • answered 2019-01-11 05:53 Still

    As others have pointed out, you must await your task. However, you are missing one crucial configuration - enabling the message cache. With Discord.Net and the MessageDeleted event, in order to retrieve the message, you must enable caching since you cannot retrieve a deleted message from the Discord server. To enable caching, please set the MessageCacheSize in the DiscordSocketConfig object and pass it into DiscordSocketClient.

    Setting up the cache

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

    Getting the deleted message from cache

    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;

    This event is thoroughly documented on the Discord.Net documentation, please see the MessageDeleted event.