0

Here is my code, everything up to clearChat functon works. It throws no error but it doesn't delete the messages.

    const bot = new Discord.Client();
    bot.on('message', msg => {
      
       const args = msg.content.substring(config.prefix.length).split(' ');

       switch (args[0]) {
           case 'clear':

               if(isNaN(args[1])) return msg.reply('Define the amount of messages you want to clear!');
               else if(args[1] > 101 ) return msg.reply('Cannot clear more than 100 messages!');
               else if(args[1] < 1)) return msg.reply('Must clear at least 1 message!');
               else {

                    clearChat = async(msg, args) => {

                         let deleteAmount = +args[1] + 1;

                         messages = await msg.channel.messages.fetch({ limit: deleteAmount }).then(async(messages) => {
                             await msg.channel.bulkDelete(messages);
                         });
                    };
               };
               break;
       };
    });
    

1 Answer 1

1

This doesn't work because you never actually execute the delete part of your code.

You need to define it as a function to run it the way you want to here.

async function clearChat (msg, args) {
            
    let deleteAmount = +args[1] + 1;

    messages = await msg.channel.messages.fetch({ limit: deleteAmount }).then(async (messages) => {
        await msg.channel.bulkDelete(messages);
    });
}

Once defined correctly you need to call that function

else {
    clearChat(msg, args)
}

In addition to that, you have an extra ) in your else if (args[1] < 1).

The complete code should look a little something like this:

if (isNaN(args[1])) return msg.reply('Define the amount of messages you want to clear!');
else if (args[1] > 101) return msg.reply('Cannot clear more than 100 messages!');
else if (args[1] < 1) return msg.reply('Must clear at least 1 message!');
else {
    clearChat(msg, args)
}
        
async function clearChat (msg, args) {
            
    let deleteAmount = +args[1] + 1;

    messages = await msg.channel.messages.fetch({ limit: deleteAmount }).then(async (messages) => {
        await msg.channel.bulkDelete(messages);
    });
}
2
  • another the problem is that msg.channel.messages.fetch is not recognized as a function but msg.channel.fetchMessages works.
    – Potochnik
    Commented Oct 12, 2020 at 13:35
  • when I tried your solution the only things I had to change were the ones described above. What version of discord.js are you using? Commented Oct 12, 2020 at 13:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.