如何使用Discord.js删除具有var名称的频道

时间:2020-09-21 16:04:43

标签: discord.js

我正在创建一个不和谐的bot,我想创建一个命令来删除其名称(0、1、2、3、4、5、6、7、8、9等)的通道。 我要删除的通道将具有单个名称,因此我使用了for循环。这是我的代码;我不知道为什么这行不通,请先谢谢你。

const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
 name: 'delchannels',
 execute(message) {
  for (let i = 0; i < 10; i++) {
   let fetchedChannel = message.guild.channels.cache.find(i);
   fetchedChannel.delete();
  }
 },
};

哦,是的,我有这个错误:

    TypeError: fn is not a function
        at Map.find (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\@discordjs\collection\dist\index.js:161:17)
        at Object.execute (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\commandes\delchannels.js:7:63)
        at Client.<anonymous> (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\index.js:26:38)
        at Client.emit (events.js:314:20)
        at MessageCreateAction.handle (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
        at Object.module.exports [as MESSAGE_CREATE] (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
        at WebSocketManager.handlePacket (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
        at WebSocketShard.onPacket (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
        at WebSocketShard.onMessage (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
        at WebSocket.onMessage (C:\Users\BillyLeBossWoula\Documents\GitHub\MrSmith\node_modules\ws\lib\event-target.js:125:16)

1 个答案:

答案 0 :(得分:0)

Collection.find()需要一个功能参数。它将在数组的每个元素上运行给定的函数,并返回满足该函数的第一个元素。另外,i是一个数字,因此您也必须将频道名称转换为数字。

for (let i = 0; i < 10; i++) {
 let fetchedChannel = message.guild.channels.cache.find(
  (channel) => +channel.name === i
 );
 fetchedChannel.delete();
}

const channels = [
 {
  name: '0',
  id: 123,
 },
 {
  name: '1',
  id: 234,
 },
 {
  name: '2',
  id: 345,
 },
 {
  name: '3',
  id: 456,
 },
];
for (var i = 0; i < channels.length; i++) {
 console.log(channels.find((channel) => +channel.name === i).id);
}


仅作为提示,我相信您可以像这样缩短功能:

for (let i = 0; i < 10; i++) {
 let fetchedChannel = message.guild.channels.cache.find((c) => +c.name === i);
 fetchedChannel.delete();
}

// change to:
message.guild.channels.cache
 .filter((c) => /^[0-9]$/.test(c.name))
 .forEach((c) => c.delete());