Home > database >  How to delete in bulk for a Discord bot
How to delete in bulk for a Discord bot

Time:10-02

import DiscordJS, { Channel, Intents, Message } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const prefix = '~';

const client = new DiscordJS.Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MESSAGE_REACTIONS
  ]
})

client.on('ready', () => {
  console.log('The bot is ready')
})

client.on('messageCreate', (message) => {
  if(message.content.toLowerCase().startsWith(prefix   'clearall')) {
    async function clear() {
      message.delete();
      const fetched = await message.channel.fetchMessages({limit: 99});
      message.channel.bulkDelete(fetched);
      message.channel.send('Deleted 99 messages')
    }
    clear();
  }


})


client.login(process.env.TOKEN)

I'm trying to delete messages in a channel in bulk for a Discord bot, but I the clear() function, fetchMessages and bulkDelete comes out with errors.

enter image description here

CodePudding user response:

Function declarations are not allowed inside blocks when targeting ES3 or ES5;

You can edit your tsconfig.json and set the compilerOptions.target option to something recent, like ES2017 or even esnext. This is an interesing change since further errors can come because of targeting a legacy JS version.

If you still don't have a tsconfig in your project, create a file named tsconfig.json in the root of your project with something like:

{
  "compilerOptions": {
    "target": "ES2017",
    "strict": true,
    "esModuleInterop": true
  }
}

Since your code is going to run on a very recent JS version (inside node.js), there's no need to target an old JS version.

Extra: removing the unnecessary function

You also don't need to create that clear() function there. You can just run its inner code directly.

Removing the function will then trigger a warning about async await, which you can solve by changing this line:

client.on('messageCreate', async (message) => { // add "async" there

x does not exist

The channel object does not have the fetchMessages() function. You can review the docs or CTRL click to navigate the type definitions and try to find the desired function.

From a quick look it looks like fetchMessages() resides inside an inner messages object, so message.channel.messages.fetchMessages(...) might be what you are looking for.

  • Related