Node.js Discord bot频道重名校验功能实现问题咨询
代码问题定位
- 逻辑顺序错误:先执行频道创建,再做存在性校验,完全颠倒了校验的作用
- 匹配规则错误:
result是存储已存在频道名的数组,直接用字符串和数组做===全等判断永远返回false - 校验位置错误:判断逻辑写在
for循环外部,只能拿到循环结束后的最后一个key值,无法对所有待创建频道做校验 - 异步逻辑未处理:
mess.guild.channels.create是异步方法,未加await会导致执行顺序混乱,同时.then中直接写console.log会立即执行,不会等待创建完成后触发 - 方法调用错误:发送消息的方法是
mess.channel.send,你代码中误写为mess.channels.send - 安全风险:非必要场景使用
eval执行外部导入的代码,存在注入攻击风险,建议优先替换为函数封装实现count_users逻辑
修复后代码实现
// 函数前加async以支持await处理异步操作 async function info_channels(robot, mess, args) { const existedChannelNames = []; // 这里的re沿用你原有代码定义的正则即可 robot.channels.cache.forEach(el => { let processedName = el.name.replace(re, ''); existedChannelNames.push(processedName); }); for(key in Channels.channels){ // 先对当前待创建的频道名做和现有频道相同的规则处理 const currentChannelRawName = Channels.channels[key].Name; const processedCurrentName = currentChannelRawName.replace(re, ''); // 校验是否已存在 if(existedChannelNames.includes(processedCurrentName)){ // 存在就发送错误提示,跳过创建 await mess.channel.send(`该频道「${currentChannelRawName}」已存在`); continue; } // 不存在则执行创建逻辑 try { // 建议先替换eval逻辑,此处暂时保留你的原有实现 const userCount = eval(Channels.channels[key].count_users); await mess.guild.channels.create(`${currentChannelRawName} ${userCount}`,{ type: "voice", permissionOverwrites: [ { id: mess.guild.roles.everyone, allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'], deny: ['CONNECT','MANAGE_CHANNELS','SPEAK'] }, { id: mess.guild.roles.cache.get(config.userRole), allow: ['VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'], deny: ['CONNECT','MANAGE_CHANNELS','SPEAK'] }, { id: mess.guild.roles.cache.get(config.role_Rinka), allow: ['VIEW_CHANNEL','MANAGE_CHANNELS','READ_MESSAGE_HISTORY'], } ], parent: '914852886599569458', }); console.log(`Канал${processedCurrentName} создан!`); await mess.channel.send(`频道「${currentChannelRawName}」创建成功`); } catch (err) { console.error('频道创建失败:', err); await mess.channel.send(`频道「${currentChannelRawName}」创建失败,请检查权限配置`); } } }
替代实现方案
你也可以不用提前遍历所有频道存到数组,直接用discord.js内置的缓存查找方法,代码更简洁:
// 在循环内直接查找是否存在同名频道 const isExisted = mess.guild.channels.cache.some(el => el.name.replace(re, '') === Channels.channels[key].Name.replace(re, '')); if(isExisted) { await mess.channel.send(`该频道「${Channels.channels[key].Name}」已存在`); continue; }
内容的提问来源于stack exchange,提问作者Uximy
相关产品推荐
相关产品推荐

