Search code examples
discorddiscord.js

i have a problem with my bot (spamming messages)


I wrote a piece of code that lets the bot send a message and then after 5 seconds it will delete it and then redo this step, but when I tested it, it keep spamming with test. Here is my code :

client.on('messageCreate', (message) => {
    let chan = client.channels.cache.get('988807641792905248')
    if (message.channel.id === "988807641792905248" ) return chan.send(`test`).then(mess => {
        setTimeout(() => {
            mess.delete()
        }, 5000)
    })
})

Solution

  • You can use function to loop your command and adding setTimeout to delete and resend the message.

    async function repeat() { //first read of function declined
        let chan = client.channels.cache.get('988807641792905248')
        if (message.channel.id === "988807641792905248" )
           chan.send("Testing").then((msg) => { //send the message
               setTimeout(() => { //Time out for 5 seconds
                    msg.delete()
                    setTimeout(() => { //After 5 seconds, delete the message
                        repeat(); // then going back to function repeat()
                    }, 1000) 
               }, 5000)
           })
        }
        repeat(); //First read of function not declined