Reputation: 147
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());
}
Upvotes: 2
Views: 2251
Reputation: 332
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.
Upvotes: 3
Reputation:
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();
Upvotes: 1
Reputation: 2548
replace
embed.AddField("deleted message", msg.ToString());
with
embed.AddField("deleted message", msg.Content);
via https://discord.foxbot.me/docs/api/Discord.IMessage.html
Upvotes: 0