简体   繁体   English

如何解决discord.js中的“无法读取未定义的属性'反应'”

[英]How to fix “Cannot read property 'react' of undefined” in discord.js

I'm setting up a discord bot with reactions, but there is an error in the second reaction by number, but I can not find it. 我正在建立一个带有反应的discord机器人,但是第二反应在编号上有错误,但是我找不到它。 It's probably a loop error, but I've already tried to change the names of variables, nothing helps. 这可能是循环错误,但是我已经尝试过更改变量的名称,没有任何帮助。 I am also sorry for the length of the code, but I have tried to shorten it to the maximum. 对于代码的长度,我也感到抱歉,但是我尝试将其缩短到最大。

After hitting command !bot , the bot should reply with a message with 5 possible reactions. 击中命令!bot ,该bot会以一条带有5种可能反应的消息答复。
If I press reaction 1 , a second message appears with the description, the discord and the date in an embed. 如果按反应1 ,则会出现第二条消息,其中包含说明,不和谐和日期。
At the bottom of this message should appear a reaction ✅. 该消息的底部应显示一个反应✅。
Everything works without worries except that nothing happens when I press this reaction. 一切正常,无后顾之忧,只是当我按此反应时什么也没有发生。

client.on('message', async message => {
  if (message.content.toLowerCase().startsWith('!bot')) {

    async function accessSpreadsheet(embed) {
      const doc = new GoogleSpreadsheet('1qA11t460-ceILmwu6RtfiPGb_n9MUD_7z6Ld7I_Z6yc');
      await promisify(doc.useServiceAccountAuth)(creds);
      const info = await promisify(doc.getInfo)();
      var sheet = info.worksheets[0];

      var cells = await promisify(sheet.getCells)({
        'min-row': 2,
        'max-row': 7,
        'min-col': 16,
        'max-col': 16,
        'return-empty': true,
      })
      for (var cell of cells) {

      }
      for (let i = 0; i < 25 && cells[i]; i++) {
        {
          if (i == 0) embed.addField('Name', `•1⃣ ${cells[i].value}`, false);
        } {
          if (i == 1) embed.addField('Name', `•2⃣ ${cells[i].value}`, false);
        } {
          if (i == 2) embed.addField('Name', `•3⃣ ${cells[i].value}`, false);
        } {
          if (i == 3) embed.addField('Name', `•4⃣ ${cells[i].value}`, false);
        } {
          if (i == 4) embed.addField('Name', `•5⃣ ${cells[i].value}`, false);
        }
      }
    }

    var embed = new RichEmbed()
      .setColor('#0099ff')
      .setTitle("A title");

    try {
      var sentMessage = await accessSpreadsheet(embed)
        .then(() => message.author.send(embed))
        .catch(console.error);

      for (let n = 1; n <= 5; n++) await sentMessage.react(`${n}⃣`);

      const filter = (reaction, user) => ['1', '2', '3', '4', '5'].includes(reaction.emoji.name.slice(0, 1)) && user.id === message.author.id;
      const collected = await sentMessage.awaitReactions(filter, {
        maxMatches: 1,
        time: 4000
      });

      if (collected.size === 0) {
        await message.channel.send('Time ran out');
      } else {
        const reaction = collected.first();

        switch (reaction.emoji.name.slice(0, 1)) {
          case '1':
            async function accessSpreadsheet(embed1) {
              const doc = new GoogleSpreadsheet('1qA11t460-ceILmwu6RtfiPGb_n9MUD_7z6Ld7I_Z6yc');
              await promisify(doc.useServiceAccountAuth)(creds);
              const info = await promisify(doc.getInfo)();
              var sheet = info.worksheets[0];

              var cells = await promisify(sheet.getCells)({
                'min-row': 2,
                'max-row': 7,
                'min-col': 16,
                'max-col': 16,
                'return-empty': true,
              })
              for (let i = 0; i < 25 && cells[i]; i++) {
                {
                  if (i == 0) embed1.setTitle(`You select: ${cells[i].value}`);
                }
              }
              var cells1 = await promisify(sheet.getCells)({
                'min-row': 2,
                'max-row': 7,
                'min-col': 17,
                'max-col': 17,
                'return-empty': true,
              })
              for (let j = 0; j < 25 && cells1[j]; j++) {
                {
                  if (j == 0) embed1.setDescription(`Description: \n \n ${cells1[j].value}`);
                }
              }
              var cells1 = await promisify(sheet.getCells)({
                'min-row': 2,
                'max-row': 7,
                'min-col': 18,
                'max-col': 18,
                'return-empty': true,
              })
              for (let l = 0; l < 25 && cells1[l]; l++) {
                {
                  if (l == 0) embed1.addField(`Discord:`, `${cells1[l].value}`, true);
                }
              }
              var cells1 = await promisify(sheet.getCells)({
                'min-row': 2,
                'max-row': 7,
                'min-col': 20,
                'max-col': 20,
                'return-empty': true,
              })
              for (let k = 0; k < 25 && cells1[k]; k++) {
                {
                  if (k == 0) embed1.addField(`Date:`, `${cells1[k].value}`, true);
                }
              }
              for (let k = 0; k < 25 && cells1[k]; k++) {
                {
                  if (k == 0) embed1.addField(`To be validated with ✅:`, `click on reaction`);
                }
              }
            }

            var embed1 = new RichEmbed()
              .setColor('#0099ff');
            await accessSpreadsheet(embed1)
              .then(() => message.author.send(embed1))
              .then(message => {
                message.react('✅')
                //Problem starts here

                client.on('messageReactionAdd', async (reaction, user) => {
                  if (reaction.emoji.name === '✅' && user.id !== client.user.id) {
                    async function accessSpreadsheet(embed2) {
                      var doc = new GoogleSpreadsheet('1qA11t460-ceILmwu6RtfiPGb_n9MUD_7z6Ld7I_Z6yc');
                      await promisify(doc.useServiceAccountAuth)(creds);
                      var info = await promisify(doc.getInfo)();
                      var sheet = info.worksheets[0];
                      var cells = await promisify(sheet.getCells)({
                        'min-row': 2,
                        'max-row': 7,
                        'min-col': 21,
                        'max-col': 21,
                        'return-empty': true,
                      })
                      for (let m = 0; m < 25 && cells[m]; m++) {

                        {
                          if (m == 0) embed2.addField(`Days before toornament: ${cells[m].value}`, `Choose options: \n 1⃣  \n 2⃣ \n 3⃣ \n \n **(5 sec)**`);
                        }
                      }
                    }
                    var embed2 = new RichEmbed()
                      .setColor('#0099ff');
                    try {
                      var sentMessage1 = await accessSpreadsheet(embed2)
                        .then(() => message.author.send(embed2))
                        .catch(console.error);

                      for (let z = 1; z <= 3; z++) await sentMessage1.react(`${z}⃣`); // The error is here

                      const filter = (reaction, user) => ['1', '2', '3'].includes(reaction.emoji.name.slice(0, 1)) && user.id === message.author.id;
                      const collected = await sentMessage1.awaitReactions(filter, {
                        maxMatches: 1,
                        time: 4000
                      });

                      if (collected.size === 0) {
                        await message.channel.send('Time ran out');
                      } else {
                        const reaction = collected.first();

                        switch (reaction.emoji.name.slice(0, 1)) {
                          case '1':
                            message.channel.send('1')
                            break;
                          case '2':
                            await message.channel.send('You chose `two`.');
                            break;
                          case '3':
                            await message.channel.send('You chose `3`.');
                            break;
                        }
                      }
                    } catch (err) {
                      console.error(err);
                    }

                  }
                })
              })

              .catch(console.error);
            break;
          case '2':
            await message.channel.send('You chose `two`.');
            break;
          case '3':
            await message.channel.send('You chose `3`.');
            break;
          case '4':
            await message.channel.send('You chose `4`.');
            break;
          case '5':
            await message.channel.send('You chose `5`.');
            break;
        }
      }
    } catch (err) {
      console.error(err);
    }
  }
})

I know this should only work with Reaction 1, but the console shows: 我知道这只应在反应1中使用,但控制台显示:

DiscordAPIError : Can not send messages to this user DiscordAPIError :无法向该用户发送消息
TypeError : Can not read property 'react' of undefined` TypeError :无法读取未定义的属性“ react”

The error is raised on the following line: 错误在以下行中引发:

for (let z = 1; z <= 3; z ++) await sentMessage1.react (`$ {z} ⃣`);

One thing I noticed is that you are using async/wait but handling it like a promise.then 我注意到的一件事是,您正在使用异步/等待,但像应许一样处理它。

var sentMessage1 = await accessSpreadsheet(embed2)
                        .then(() => message.author.send(embed2))
                        .catch(console.error);

sentMessage1 does not receive anything back from you call. sentMessage1不会从您的电话收到任何sentMessage1

You either must return a something that has .react on it or handle everything inside your then statement. 您要么必须返回带有.react内容,要么要处理then语句中的所有内容。

var sentMessage1 = await accessSpreadsheet(embed2)
                        .then(() => {
                             message.author.send(embed2);
                             message.author.react(####); //I don't know the discord API
                         })
                        .catch(console.error);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决:“TypeError:无法读取discord.js中未定义的属性&#39;标签&#39;错误 - How to fix: “TypeError: Cannot read property 'tag' of undefined” error in discord.js 如何修复“TypeError:无法读取未定义的属性 'toString'” | discord.js - How to fix “TypeError: Cannot read property 'toString' of undefined” | discord.js 如何修复“无法读取未定义的属性'长度'”和 Args 输入在我的扫雷命令中不起作用 - Discord.js - How do I fix “Cannot read property 'length' of undefined” and Args Input not working in my Minesweeper Command - Discord.js discord.js | 无法读取未定义的属性“设置” - discord.js | Cannot read property 'set' of undefined 类型错误:无法读取未定义 Discord.js javascript 的属性“添加” - TypeError: Cannot read property 'add' of undefined Discord.js javascript 无法读取未定义的 discord.js 警告命令的属性“发送” - Cannot read property 'send' of undefined discord.js warn command discord.js 无法读取未定义的属性“第一个” - discord.js Cannot read property 'first' of undefined Discord.js 的欢迎消息 - “无法读取未定义的属性 &#39;get&#39;” - Welcome message with Discord.js - “Cannot read property 'get' of undefined” 无法读取 Discord.js 上未定义的属性“hasPermission” - Cannot read property 'hasPermission' of undefined on Discord.js 类型错误:无法读取未定义的属性 &#39;has&#39; // Discord.js - TypeError: Cannot read property 'has' of undefined // Discord.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM