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

Discord自动语音频道机器人报错:newState.guild.member is not a function

解决Discord机器人创建语音频道报错:"newState.guild.member is not a function"

错误原因分析

这个报错核心是Discord.js v14+版本移除了Guild.member()方法,同时代码里还有几处API调用错误,导致创建频道的逻辑无法正常执行。

具体修正步骤

  • 替换过时的成员获取方式:原代码中newState.guild.member(user)是v13及更早版本的用法,v14+直接通过newState.member就能获取当前语音状态对应的成员对象,无需额外调用方法;同时client.user.fetch(newState.id)是错误的(client.user指向机器人自身),应直接使用newState.member.user获取用户信息。
  • 修正频道创建API:原代码newState.guild.channel.create少了复数后缀s,正确API为newState.guild.channels.create。
  • 初始化语音频道映射集合:代码中voiceCollection未定义,需先声明为Map类型,用来存储用户ID与临时语音频道ID的对应关系。
  • 优化逻辑判断:利用newState对象的现有属性简化代码,避免不必要的异步请求。

修正后的完整代码

const Discord = require("discord.js");
const TOKEN = "YOUR_BOT_TOKEN";

const { Client, GatewayIntentBits } = require('discord.js');

// 初始化存储临时语音频道的Map
const voiceCollection = new Map();

const client = new Discord.Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.DirectMessageTyping,
    GatewayIntentBits.GuildVoiceStates,
  ]
});

client.on("ready", () => {
  console.log(`${client.user.tag} 已上线`);
});

client.on('error', (err) => {
  console.log(err.message);
});

client.on("voiceStateUpdate", async (oldState, newState) => {
  // 获取当前操作的成员,直接从newState中提取
  const member = newState.member;
  if (!member) return; // 防止成员不存在的异常情况

  const targetChannelId = "YOUR_TRIGGER_CHANNEL_ID"; // 替换为你的触发频道ID

  // 用户进入指定触发频道时,创建专属临时语音频道
  if (!oldState.channel && newState.channel?.id === targetChannelId) {
    try {
      const channel = await newState.guild.channels.create({
        name: member.user.tag,
        type: Discord.ChannelType.GuildVoice,
        parent: newState.channel.parent,
      });
      await member.voice.setChannel(channel);
      voiceCollection.set(member.user.id, channel.id);
    } catch (err) {
      console.error("创建频道失败:", err);
    }
  } 
  // 用户离开临时频道时,自动删除该频道
  else if (!newState.channel) {
    const tempChannelId = voiceCollection.get(member.user.id);
    if (oldState.channelId === tempChannelId) {
      try {
        await oldState.channel.delete();
        voiceCollection.delete(member.user.id);
      } catch (err) {
        console.error("删除频道失败:", err);
      }
    }
  }
});

client.login(TOKEN);

额外注意事项

  • 确保机器人拥有创建/删除语音频道的权限,且服务器内角色权限优先级高于临时频道的权限设置。
  • 确认GuildVoiceStates和GuildMembers意图已开启,同时在Discord开发者面板中启用了对应特权网关意图。

内容的提问来源于stack exchange,提问作者İlhan Sarı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:25:51