NodeJS Discord.js创建线程,但不会在命令期间添加成员

zzwlnbp8  于 2023-01-30  发布在  Node.js
关注(0)|答案(1)|浏览(100)

我正在构建一个Discord机器人,它在运行命令时会创建一个私有线程,并将运行该命令的用户添加到该线程。我遇到了一个问题,即线程已成功创建,但在尝试将成员添加到线程时,出现错误。
我的代码如下:

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js')

module.exports = {
  data: new SlashCommandBuilder()
    .setName('pthread')
    .setDescription('Create private thread'),

  async execute(interaction) {

    const channel = interaction.channel
    const user = interaction.user
    const userName = user.username
    const threadName = userName + "'s-Private-Thread"

    // Create a new private thread
    channel.threads
      .create({
        name: threadName,
        autoArchiveDuration: 60,
        type: 12,
        reason: 'na',
      })
      .then(threadChannel => console.log(threadChannel))
      .catch(console.error);

    var thread = channel.threads.cache.find(x => x.name === threadName)
    await thread.members.add(user)

    await interaction.reply({ content: 'A private thread has been created for you!', ephemeral: true })

  }
}

下面是我得到的错误:

TypeError: Cannot read properties of undefined (reading 'members')
    at Object.execute (C:\Users\Liam\Desktop\Files\Code\GitHubRepos\ThreadMaker\commands\addEntry.js:27:18)

如果我尝试使用

await thread.send({ content: 'Hello' })

具体而言,

TypeError: Cannot read properties of undefined (reading 'send')
    at Object.execute (C:\Users\Liam\Desktop\Files\Code\GitHubRepos\ThreadMaker\commands\addEntry.js:27:18)

如果我运行这个命令两次,它确实成功地将用户添加到线程中/在线程中发送消息,但随后创建了一个重复的线程。这几乎就像命令需要在我能够对线程做任何事情之前完成执行一样。我唯一的理论是在命令完成执行之前线程没有保存到缓存中。如果是这种情况,我可以强制它在执行过程中保存到缓存中吗?谢谢

laik7k3q

laik7k3q1#

我不知道你为什么把then()方法和async/await混合在一起。可能这就是你认为该高速缓存已经更新的原因。然而,在你的代码中,channel.threads.cache.find()channel.threads.create()完成创建你的线程之前运行(因为承诺不会阻止事件循环)。
channel.threads.create()返回一个promise,一旦它被解析,就返回创建的ThreadChannel。这意味着你可以获取创建的频道。
您还应该使用枚举(如ChannelType.GuildPrivateThread)而不是幻数(12)。

const { ChannelType } = require('discord.js');

// ...

async execute(interaction) {
  const channel = interaction.channel;
  const user = interaction.user;
  const userName = user.username;
  const threadName = userName + "'s-Private-Thread";

  try {
    // Create a new private thread
    const threadChannel = await channel.threads.create({
      name: threadName,
      autoArchiveDuration: 60,
      type: ChannelType.GuildPrivateThread,
      reason: 'na',
    });

    await threadChannel.members.add(user);

    await interaction.reply({
      content: 'A private thread has been created for you!',
      ephemeral: true,
    });
  } catch (error) {
    console.log(error);
  }
},

相关问题