使用discord.js v14创建临时语音频道时提示name未指定错误求助
问题:Discord.js v14 创建临时语音频道时提示未指定
name值 我正在编写一个脚本,期望实现当用户加入指定语音频道时,机器人创建临时语音频道并将用户转移至该频道,待频道为空时自动删除它。但运行时出现错误,提示创建频道未指定name值,我使用的是discord.js v14。
我的代码如下:
robot.on('voiceStateUpdate', async (oldState, newState) => { const voiceChannelID = '1153371417182752940'; if (newState.channelId === voiceChannelID) { // Create a new voice channel const channel = await newState.guild.channels.create(`Channel ${newState.member.user.username}`, { type: 'GUILD_VOICE', parent: newState.channel.parent, name: `Channel ${newState.member.user.username}`, }); // Move the user to the new voice channel newState.setChannel(channel); // Delete the voice channel when it becomes empty channel.on('voiceStateUpdate', (oldState) => { if (oldState.channel.members.size === 0) oldState.channel.delete(); }); } });
我曾尝试在discord.js文档中寻找问题解决方案,但未找到合适内容。
解决方案
问题出在Discord.js v14的API调用方式变更上,以下是具体修正点:
1. 修正频道创建参数格式
v14中channels.create()不再支持第一个参数传名称,必须把所有配置项放在对象里;同时频道类型要使用ChannelType枚举,不能用字符串'GUILD_VOICE':
// 错误写法 const channel = await newState.guild.channels.create(`Channel ${newState.member.user.username}`, { ... }); // 正确写法 const { ChannelType } = require('discord.js'); const channel = await newState.guild.channels.create({ name: `Channel ${newState.member.user.username}`, type: ChannelType.GuildVoice, parent: newState.channel.parent, });
2. 替换过时的用户转移方法
v14中setChannel()已被废弃,改用setVoiceChannel()方法:
// 错误写法 newState.setChannel(channel); // 正确写法 await newState.member.voice.setChannel(channel);
3. 修复频道空事件监听逻辑
原代码绑定在单个频道上的voiceStateUpdate监听逻辑有误,应该通过全局事件监听并检查频道成员数量,同时记得在频道删除后移除监听避免内存泄漏。
完整修正后的代码
const { ChannelType } = require('discord.js'); robot.on('voiceStateUpdate', async (oldState, newState) => { const voiceChannelID = '1153371417182752940'; // 仅处理用户从无频道加入指定频道的情况,避免重复触发 if (!oldState.channelId && newState.channelId === voiceChannelID) { // 创建临时语音频道 const channel = await newState.guild.channels.create({ name: `Channel ${newState.member.user.username}`, type: ChannelType.GuildVoice, parent: newState.channel.parent, }); // 转移用户到新频道 await newState.member.voice.setChannel(channel); // 监听频道是否为空 const checkChannelEmpty = async () => { if (channel.members.size === 0) { await channel.delete(); // 移除监听,避免内存泄漏 robot.off('voiceStateUpdate', checkChannelEmpty); } }; robot.on('voiceStateUpdate', checkChannelEmpty); } });
内容的提问来源于stack exchange,提问作者XaipaniKaif
相关产品推荐
相关产品推荐

