检查 Discord.js 上特定消息的反应?

时间:2021-01-10 00:29:00

标签: node.js discord discord.js

我试图通过存储消息 ID 来检查特定消息的反应。我正在使用 discord.js。

问题

<块引用>

问题是在使用我的代码时,我收到此错误:TypeError:无法读取未定义的属性“id”。也许是因为它是一个嵌入?我想要做的是获取发送的嵌入的 id 并将其写入文件。然后,在处理反应的代码中,我应该得到写在文件上的 id,并测试这是否是反应添加到的正确消息。

我的代码

async function tembed(message) {
  
    const mention = message.mentions.members.first();
        if (mention.roles.cache.find(r => r.name === "dittatore")) {
          message.channel.send(`Cannot eject **${mention}**.`);
          message.channel.bulkDelete(1);
        }
        if (mention.roles.cache.find(r => r.name === "dittatore")) return;
        message.channel.bulkDelete(1);
        const testembed = {
          color: '#7A2F8F',
          title: 'test',
          description: `${mention} this is a test embed`,
          footer: 'test footer',
        };
        let sent = await message.channel.send({ embed: testembed }).then(async (embedMessage) => {
          await embedMessage.react('✅');
          await embedMessage.react('❌');
        });
        let id = sent.id; //TypeError: Cannot read property 'id' of undefined
        fs.writeFile('/home/pi/botstuff/testembed.txt', id, (err) => { 
          if (err) throw err;
        });
        console.log(`wrote ${id} on file`);
        const channel = message.guild.channels.cache.get("770735002182877224");
        channel.send(`${mention}`);
  }

1 个答案:

答案 0 :(得分:1)

在您的代码中,您正在执行:

let sent = await message.channel.send({ embed: testembed }).then()

这是错误的做法。 async/await 本质上是使用 Promise 的一种更简单的方法;本质上,它是.then()替代。因此,上面的代码相当于执行 message.channel.send().then().then(),这意味着 sent 现在仍然是 Promise(带有 .then() 方法)或者只是 undefined 而不是您希望它成为的 message 对象。

对此的简单解决方案是停止尝试同时使用两种不同的方法来处理 Promise。使用 async/await.then(),但不要同时使用两者。 async/await 更易于使用,因此我们将在本示例解决方案中使用它。

async function tembed(message) {
    const mention = message.mentions.members.first();

    if (mention.roles.cache.find(r => r.name === "dittatore")) {
        message.channel.send(`Cannot eject **${mention}**.`);
        message.channel.bulkDelete(1);
        return;
    }

    message.channel.bulkDelete(1);

    const testembed = {
      color: '#7A2F8F',
      title: 'test',
      description: `${mention} this is a test embed`,
      footer: 'test footer',
    };

    let sent = await message.channel.send({ embed: testembed });        
    await sent.react('✅');
    await sent.react('❌');
    let id = sent.id; //TypeError no longer occurs
    
    fs.writeFile('/home/pi/botstuff/testembed.txt', id, (err) => { 
      if (err) throw err;
    });
    console.log(`wrote ${id} on file`);
    const channel = message.guild.channels.cache.get("770735002182877224");
    channel.send(`${mention}`);

}

我还从您提供的代码中删除了一些不必要的冗余(包括您对 dittatore 角色的重复检查以及您对 sentembedMessage 变量的定义是相同的消息)。