首页 > 解决方案 > 无法向刚刚创建的频道发送消息

问题描述

我正在尝试在创建频道后向频道发送消息,但它似乎不起作用。我正在使用 discord.js@v12

这是代码:

message.guild.channels.create(cpl, 'text').then(ma => {
  ma.setParent(cat);
  ma.lockPermissions();
}).catch(err => console.log(err))

let nChannel = bot.channels.cache.find(ch => ch.name === cpl)
console.log(nChannel)
let embed = new Discord.MessageEmbed()
  .setTitle("New Ticket")

nChannel.send(embed)

这是记录到控制台的内容:

Cannot read property 'send' of undefined

标签: discord.js

解决方案


这是因为您在尝试发送消息之前没有等待创建通道。.setParent()与在使用and之前等待它准备好一样.lockPermissions(),您应该在使用之前等待它.send()
这是我的做法:

message.guild.channels.create(cpl, 'text').then(async (newChannel) => {
  // You're inside .then, so all of this is happening AFTER the channel is created

  // Wait for .setParent and .lockPermissions to fulfill
  await newChannel.setParent(cat)
  await newChannel.lockPermissions()

  // You can now send your message
  let embed = new Discord.MessageEmbed()
    .setTitle("New Ticket")
  newChannel.send(embed)
})

推荐阅读