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

创建Discord文本频道后发送消息报错:Cannot read properties of undefined

创建Discord文本频道后发送消息报错:Cannot read properties of undefined (reading 'send')

问题原因

message.guild.channels.create是异步操作,返回的是Promise对象。你当前的代码同步获取MafiaChannel.id时,频道还未完成创建,导致client.channels.cache.get(...)找不到对应频道,返回undefined,调用send方法自然报错。

解决方案

两种可靠方式处理异步逻辑,确保频道创建完成后再发送消息:

方式1:使用async/await(推荐,代码更直观)

确保包含这段代码的函数声明为async,用await等待频道创建完成:

async function setupMafiaChannel(message) {
  let everyoneRole = message.guild.roles.cache.find(r => r.name === '@everyone');

  // 等待频道创建完成,MafiaChannel直接是创建好的频道对象
  const MafiaChannel = await message.guild.channels.create('mafia', {
    type: 'text',
    permissionOverwrites: [
      {
        id: everyoneRole.id,
        deny: ['VIEW_CHANNEL']
      },
      {
        id: PlayersShuffled[0].id,
        allow: ['VIEW_CHANNEL']
      }
    ]
  });

  // 直接用频道对象发送消息
  MafiaChannel.send("Who do you want to kill?");
}

方式2:使用Promise的.then()方法

如果无法使用async函数,通过.then()处理创建完成后的逻辑:

let everyoneRole = message.guild.roles.cache.find(r => r.name === '@everyone');

message.guild.channels.create('mafia', {
  type: 'text',
  permissionOverwrites: [
    {
      id: everyoneRole.id,
      deny: ['VIEW_CHANNEL']
    },
    {
      id: PlayersShuffled[0].id,
      allow: ['VIEW_CHANNEL']
    }
  ]
})
.then(MafiaChannel => {
  // 频道创建成功后执行消息发送
  MafiaChannel.send("Who do you want to kill?");
})
.catch(err => {
  // 可选:捕获创建频道时的错误,方便排查
  console.error('创建频道出错:', err);
});

额外提示

不需要通过client.channels.cache.get查找频道,channels.create返回的Promise完成后,直接得到已创建好的频道实例,直接调用其send方法更高效可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:10:09