如何在链接中找到消息

时间:2021-02-10 16:42:16

标签: javascript node.js discord.js

我最近在创建一个机器人。

现在我想知道是否有人可以帮助我完成我的 -verify (mc uuid) 命令。它会检查 URL 以查看它们的 uuid 是否在获取的对象中。所以,如果我做了 -verify (uuid) 并且找到了,它会给我一个角色。

代码:

const Discord = require('discord.js');
const fetch = require('cross-fetch');

module.exports = {
    name: `verify`,
    async execute(message, args) {
        fetch("https://api.hypixel.net/guild?key=29083d9d-58cf-4a71-95be-d24f31c018b7&name=Metanoia")
            .then(result => result.json())
            .then(({ guild }) => {
        const role = message.guild.roles.cache.get('808886143416270899');
        const uuid = args[0];
        if(uuid) {
            //
        }
        })
    }
}

1 个答案:

答案 0 :(得分:1)

您从 API URL 收到一个对象。它的 guild 属性有一个 members 数组。该数组包含带有 uuid 的对象。如果你想用提供的 uuid 找到一个,你可以使用 .find() method 返回数组中满足提供的测试函数的第一个元素的值。

在您的测试函数中,您可以测试对象的 uuid 是否与提供的成员 uuid 相同:

const foundElement = array.find((el) => el.uuid === uuid);

在您的代码中,它看起来像这样:

const fetch = require('cross-fetch');

module.exports = {
  name: `verify`,
  async execute(message, args) {
    const role = message.guild.roles.cache.get('808886143416270899');
    const uuid = args[0];

    if (!uuid) {
      return message.channel.send(`uuid is not provided`);
    }

    try {
      const result = await fetch('https://api.hypixel.net/guild?key=29083d9d-58cf-4a71-95be-d24f31c018b7&name=Metanoia');
      const { guild } = await result.json();
      const member = guild.members.find((member) => member.uuid === uuid);

      if (!member) {
        return message.channel.send(`No member found with uuid ${uuid}`);
      }

      // you can do anything with the found member
      message.channel.send('```' + JSON.stringify(member, null, 2) + '```');
    } catch (error) {
      console.log(error);
      message.channel.send('Oops, there was an error');
    }
  }
}

如果您的 execute 方法已经是一个异步函数,您可以使用 async/await 来获取结果。我在上面的代码中使用了它。

enter image description here

相关问题