Skip to content
Advertisement

How can I delete a 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.

Advertisement

Answer

kanal.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 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');

    try {
      const sentMessage = await kanal.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 kanal.send(embed);
      sentMessage.delete({ timeout: 5000 });
    } catch (error) {
      console.log(error);
    }
    // ...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement