Skybow
Skybow

Reputation: 25

How can I delete a Discord message after sending it?

I have a code that sends a message when a member joins the guild and I want to shortly delete it afterwards.

My code:

client.on('guildMemberAdd', (member) => {
  var server = member.guild.id;
  if (server === '760511134079254610') {
    let kanal = client.channels.cache.get('786172941703970860');
    const embed = new Discord.MessageEmbed()
      .setTitle('Hoşgeldin!')
      .setDescription(`**<@${member.user.id}>** kullanıcısı sunucumuza geldi!`)
      .setColor('BLUE')

    kanal.send(embed)
}})

I tried embed.delete or just the classic msg.delete but it doesn't work as I can/don't know how to define "msg" as the last msg the bot has sent.

Upvotes: 1

Views: 380

Answers (2)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23189

.send(embed) returns a promise. You can use async/await here to grab that message so you can delete it later. Check the following code; it should delete the message after 5s:

client.on('guildMemberAdd', async (member) => {
  const server = member.guild.id;
  if (server === '760511134079254610') {
    let channel = client.channels.cache.get('786172941703970860');
    const embed = new Discord.MessageEmbed()
      .setTitle('Hoşgeldin!')
      .setDescription(`**<@${member.user.id}>** kullanıcısı sunucumuza geldi!`)
      .setColor('BLUE');

    try {
      const sentMessage = await channel.send(embed);

      setTimeout(() => {
        sentMessage.delete();
      }, 5000);
    } catch (error) {
      console.log(error);
    }
  }
});

Update: Legendary Emoji mentioned that instead of setTimeout you could also use an options object with a timeout property in sentMessage.delete like this:

    try {
      const sentMessage = await channel.send(embed);
      sentMessage.delete({ timeout: 5000 });
    } catch (error) {
      console.log(error);
    }
    // ...

However, it doesn't work in the latest version of discord.js

Upvotes: 5

draymone
draymone

Reputation: 134

Thats very easy, you just need to do

    kanal.send(embed).then(sentMessage => {
sentMessage.delete()
})

This will send the message, then instantly delete it. But the player will recieve mentions and/or desktop notifications

Upvotes: 1

Related Questions