Discord.js开发:如何实现所有用户断开后自动删除语音频道
临时语音频道删除逻辑修复方案
问题根源
现有代码的删除触发逻辑仅校验当前离开频道的用户是否为该临时频道的创建者:如果创建者先离开频道,后续其他用户退出时不会触发空频道校验,因此无法自动删除空频道。
核心调整点
- 将空频道校验逻辑从「仅创建者离开时触发」调整为「任何用户离开临时频道时都会触发」
- 补充集合缓存清理逻辑,避免无效数据占用内存
- 补全原代码缺失的语法闭合标记
修正后完整代码
const { Collection } = require("discord.js"); const voiceCollection = new Collection(); // 原代码缺失voiceName变量声明,可根据需求调整配置,不需要的话可删除对应判断 const voiceName = ""; module.exports = async (Discord, client, oldState, newState) => { const user = await client.users.fetch(newState.id); const member = newState.guild.member(user); // JOIN 逻辑 if (!voiceName || voiceName === "") { if (!oldState.channel && newState.channelID === "898245212541976667") { const channel = await newState.guild.channels.create(user.tag, { type: "voice", parent: newState.channel.parent, }); member.voice.setChannel(channel); voiceCollection.set(user.id, channel.id); await channel.overwritePermissions([ { id: user.id, allow: ["MANAGE_CHANNELS", "CONNECT"], }, { id: member.guild.id, deny: ["CONNECT"], }, ]); // LEAVE 逻辑 } else if (!newState.channel && oldState.channel) { // 判断当前离开的频道是否为系统创建的临时频道 if (voiceCollection.some(channelId => channelId === oldState.channelID)) { if (oldState.channel.members.size < 1) { // 清理集合缓存 const creatorId = voiceCollection.findKey(channelId => channelId === oldState.channelID); voiceCollection.delete(creatorId); return oldState.channel.delete(); } } } } };
拓展优化建议
- 可将触发频道ID、父频道ID等固定值提取为全局配置变量,方便后续维护
- 可新增异常捕获逻辑,避免频道已被手动删除时触发代码报错
内容的提问来源于stack exchange,提问作者pxpcorn
相关产品推荐
相关产品推荐

