Discord BOT - How to delete message by id and channel id?

Let’s say I have only channel id and message id, how to delete it? Here is example what I mean by this: getChannelById(000).getMessageById(000).deleteMessage();

How to do it? Using Discord’s Js Bot API

Here is also what I tried to do:

client.channels.cache.get(channelid).fetchMessage(messageid).then(msg => msg.delete());

It gives me this error: UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message

Bumping this topic, because not answered.

Something like this
client.guilds.get('guildID').channels.get('channelID').fetchMessage('messageID').then(message => message.delete());
Would it work for you i don’t know, because there are different versions of discord.js and i made example for 11.6.4 version. So you need to go to discord.js.org and choose your version of d.js, to make sure you using proper methods for fetching, deleting and everything else.
For example, in 11.6.4 to fetch a message you need to use fetchMessage, but if you on 12.2.0 all you need is just fetch.

1 Like
client.channels.cache.get(process.env.DISCORD_CHANNEL_ID).guild.messages.cache.fetch(data.id).then(message => message.delete());

TypeError: Cannot read property 'guild' of undefined

It doesn’t work.

I tested the code (which i provided) and it works just fine and can delete any specified message.
Just look at the code you wrote and try to understand the hierarchy. Why you trying to get channel before guild? Also why are you storing basic information in .env file? And i hope use using quotes on specified IDs.

This doesn’t work because…

client.guilds.get('guildID').channels.get('channelID').fetchMessage('messageID').then(message => message.delete());

I don’t know where to get guild id and you need use cache starting from Discord.js 12.2.0. But problem is I dont know how to implement that.

In V12, try using something like this:
client.channels.cache.get(channel => channel.id === channelid).fetch(messageid).then(message => message.delete())

might be wrong, but you cant use .get(channelid) and .fetchMessage(messageid) anymore in V12

edit: you can still use .get(channelid) according to https://discordjs.guide/additional-info/changes-in-v12.html#managers-cache

I will try that, I will let you know if it worked.

It gived me this: TypeError: Cannot read property 'fetch' of undefined

see if .get(channelid) works instead of .get(channel => channel.id === channelid)
shouldnt make a difference but i have no idea.

it deleted entire channel, instead of message. Well rip my channel.

oh. try this:
client.channels.cache.get(channelid).messages.fetch(messageid).then(message => message.delete())

if it deleted the channel, then it found it.

3 Likes

Thanks it worked! When I go back to my JavaScript account, I will mark it as solution.

client.channels.cache.get('ChannelID').messages.fetch('MessageID').then(message => message.delete());