I have a function to delete a message after I send it:
export function del(interaction) {
setTimeout(() => interaction.deleteReply(), 1000);
}
I want to convert it so this will be working to interaction.channel.send
, earlier I used interaction.reply()
, but I don't want my bot to continue using reply to every command. I read Discord docs and didn't find anything helpful.
Any help on how to do this will be appreciated!
CodePudding user response:
To delete a message that was sent using interaction.channel.send()
, you can use the Message#delete()
method provided by the Discord.js library.
Here's how you can modify your del()
function to delete the message sent by interaction.channel.send()
:
export async function del(interaction) {
try {
// Send the message
const sentMessage = await interaction.channel.send("This is a message to be deleted");
// Delete the message after 1 second
setTimeout(() => sentMessage.delete(), 1000);
} catch (error) {
console.error(error);
}
}
Note that the Message#delete()
method is an asynchronous function and returns a promise, so you need to use await when calling it. Also, the Message#delete()
method can throw an error if it fails, so it's a good idea to wrap it in a try-catch block to handle any errors.
CodePudding user response:
When you use interaction.channel.send
you need to track the new message that you created (as it separate from the interaction).
Here is a quick sample where I have /ping command that creates and deletes a reply and a message:
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies with Pong!"),
async execute(interaction) {
await interaction.reply("Pong!");
const msg = await interaction.channel.send("Pong! 2!");
//Delete reply
setTimeout(async () => {
await interaction.deleteReply();
}, 1000);
//delete message
setTimeout(async () => {
await msg.delete();
}, 1500);
},
};