You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v14私人语音频道代码无效,求协助排查

Discord.js v14 私人语音频道功能故障排查与修复

你的代码存在多个关键错误,导致功能完全无响应且无报错输出,以下是具体问题和修复方案:

核心错误点

  • 频道类型错误:你要创建的是语音频道,但代码里指定了ChannelType.GuildText(文本频道),无法将用户转移到文本频道,导致后续逻辑完全失效。
  • 变量未定义+语法错误:options中的name字段使用了未定义的user变量,且用双引号包裹模板字符串(模板字符串必须用反引号),同时channels.create的第一个参数已经是频道名称,这里重复设置属于冗余且错误的写法。
  • VoiceState 方法过时:Discord.js v14 中newState.setChannel()已被移除,需要使用newState.member.voice.setChannel()来转移用户。
  • 权限值格式错误:v14 中权限不能直接用字符串(如"MANAGE_CHANNELS"),必须使用PermissionFlagsBits枚举值。
  • 未捕获 Promise 错误:所有异步操作(channels.create、createInvite)都没有添加catch处理,导致错误被静默,无法在日志中看到问题。
  • 空频道判断逻辑问题:!oldState.channel?.members.size在 v14 中,members是一个 Collection,应该用oldState.channel.members.size === 0来判断是否为空。

修复后的完整代码

// 记得先导入PermissionFlagsBits和ChannelType
const { ChannelType, PermissionFlagsBits } = require('discord.js');

client.on("voiceStateUpdate", (oldState, newState) => {
    const categoryId = "1081228230321087824";
    const triggerChannelId = "103284326182943242";

    // 用户进入触发频道时创建私人语音频道
    if (newState.channel?.id === triggerChannelId) {
        newState.guild.channels.create({
            name: `${newState.member.user.username}'s 私人频道`,
            type: ChannelType.GuildVoice,
            parent: categoryId,
            permissionOverwrites: [
                {
                    id: newState.member.id,
                    allow: [PermissionFlagsBits.ManageChannels]
                },
                {
                    id: newState.guild.id,
                    deny: [PermissionFlagsBits.ManageChannels]
                }
            ]
        })
        .then(channel => {
            // 转移用户到新创建的语音频道
            return newState.member.voice.setChannel(channel);
        })
        .then(() => {
            // 创建永久邀请链接(可选)
            channel.createInvite({ maxAge: 0, maxUses: 0 });
        })
        .catch(err => {
            console.error("创建私人频道时出错:", err);
        });
    }

    // 用户离开私人频道且频道为空时删除频道
    if (oldState.channel?.id !== triggerChannelId 
        && oldState.channel?.parentId === categoryId 
        && oldState.channel.members.size === 0) {
        oldState.channel.delete()
        .catch(err => {
            console.error("删除空频道时出错:", err);
        });
    }
});

额外注意事项

  • 确保机器人拥有ManageChannels、MoveMembers等必要权限,否则无法创建频道和转移用户。
  • 验证categoryId和triggerChannelId是否正确,避免因ID错误导致逻辑不触发。

内容的提问来源于stack exchange,提问作者snaxxs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:33:13