Search code examples
javascriptnode.jsdiscord.js

Delete channel commands erroring on run (TypeError: Cannot read properties of undefined (reading 'delete'))


I'm trying to add this joke command to my friend-community server which deletes a set of channels triggered by "execute order 66" it's erroring (error below and code). Help would be appreciated! :)

const fetchedChannel1 = client.guilds.cache.get('1004126581112975472');
const fetchedChannel2 = client.guilds.cache.get('1004126603963535570');
const fetchedChannel3 = client.guilds.cache.get('1004127515771666462');
const fetchedChannel4 = client.guilds.cache.get('1004127581836161186');
const fetchedChannel5 = client.guilds.cache.get('1004127590845534228');

client.on('message', async message => {
  if ((message.author.id) === bannedid) {
    if (message.content === 'execute order 66') {
      await message.react('😡');
    }

  } else if (message.content === 'execute order 66') {
    message.reply('yes my lord :innocent:'),
    fetchedChannel1.delete();
    fetchedChannel2.delete();
    fetchedChannel3.delete();
    fetchedChannel4.delete();
    fetchedChannel5.delete();
  }
  }
);
2022-08-02T20:55:49.118653+00:00 app[worker.1]: TypeError: Cannot read properties of undefined (reading 'delete')
2022-08-02T20:55:49.118673+00:00 app[worker.1]:     at Client.<anonymous> (/app/bot.js:67:21)
2022-08-02T20:55:49.118673+00:00 app[worker.1]:     at Client.emit (node:events:539:35)
2022-08-02T20:55:49.118694+00:00 app[worker.1]:     at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:34:18)
2022-08-02T20:55:49.118711+00:00 app[worker.1]:     at Object.module.exports [as MESSAGE_CREATE] 

Solution

  • Instead of fetching each channel you can create an array of IDs , where each ID is the ID of the channel you want to delete. Then filter the guild's channels and delete the ones that match.

    else if (message.content === 'execute order 66') {
      message.reply('yes my lord :innocent:');
    
      const channelsID = 
       [
         "1004126581112975472", "1004126603963535570", "1004127515771666462", 
         "1004127581836161186", "1004127590845534228"
       ]
    
      const guild = message.guild;
      // filter the channels that match the ID
      const filteredChannels = guild.channels.cache.filter(channel => channelsID.includes(channel.id))
    
      // Delete each channel that has been filtered
      filteredChannels.forEach(channel => channel.delete());
    

    }