Search code examples
javascriptnode.jsdiscorddiscord.js

Logging users' usernames from an array using Userid discord.js 13v


I'm trying to make a "ReqUsers" field in the "commandInformation" object, and basically trying to make it check if the message.author either has the required permissions and/or roles (if any) or if the message.author.id is listed on the "ReqUsers". Else, return a message saying that he can't run that command, which works, but one problem, I'm trying to make it say "...only (list of users that can) can run this command.", but after 13v came, I never found a way to get users using their id. I've tried client.users.cache.find(user => user.id == "userid"), client.users.cache.get("userid"), and message.guild.members.fetch("userid"), but I never got anything other than "undefined" or "Promise { < pending > }" which of none gave a user.

Here's the code.

/* DisShop Copyrights */

// Main Requirements \\

const { MessageEmbed } = require("discord.js")
const { Secrets, Channels, Guilds, Roles, Permission } = require(`../../config`)


// Important Values \\

const commandInformation = 
{
    CommandName: "check",
    Alias: [],
    ReqPermissions: [],
    ReqRoles: [],
    ReqUsers: ["userid2", "userid2"]
}


// Optional Requirements \\

const db = require("quick.db")

const anyRequiredRoles = commandInformation.ReqRoles.length > 0
const anyRequiredPermissions = commandInformation.ReqPermissions.length > 0
const anyRequiredUsers = commandInformation.ReqUsers.length > 0

const anyRequirements = anyRequiredRoles == false && anyRequiredPermissions == false && anyRequiredUsers == false

// Code \\

module.exports = client => {
    client.on('messageCreate', message => {
        if (message.author.bot) return
        if (!message.content.toLowerCase().startsWith(Secrets.PREFIX.toLowerCase())) return

        const command = message.content.toLowerCase()
        const args = command.replace(Secrets.PREFIX.toLowerCase(), '').split(' ')

        if (args[0].toString().toLowerCase() == commandInformation.CommandName || commandInformation.Alias.includes(args[0])) {

            // Permit Check \\

            var Permited_2 = 0

            if (anyRequiredPermissions || anyRequiredRoles) {
                if (anyRequiredPermissions&& !Permited_1 >= 1) {
                    if (commandInformation.ReqPermissions.some(permission => message.member.permissions.has(permission))) Permited_2++;
                }
                if (anyRequiredRoles && Permited_2 <= 0 && !Permited_1 >= 1) {
                    if (commandInformation.ReqRoles.some(role => message.member.roles.cache.has(role))) Permited_2++;
                }
            }
            
            var Permited_1 = 0

            if (anyRequiredUsers) {
                if (commandInformation.ReqUsers.some(userid => message.author.id == userid)) Permited_1++;
                console.log(commandInformation.ReqUsers)
                console.log(commandInformation.ReqUsers.some(userid => message.author.id == userid))
                console.log(Permited_1)
            }

            let allowedUsersList = []
            const allowedUsers = commandInformation.ReqUsers.forEach(userid => allowedUsersList.push(message.guild.members.cache.find(user => user.id == userid)))
            console.log(allowedUsersList, message.guild.members.fetch("735962632619819041"))

            if (!Permited_1 >= 1 && !Permited_2 >= 1) return message.reply(`You're not allowed to use this command, only ${allowedUsersList.join(`, `)} can.`)
            if (!Permited_2 >= 1 && !Permited_1 >= 1 && anyRequiredPermissions || anyRequiredRoles) return message.reply(`Sorry, you don't have the required permissions and/or roles.`)

            // Main Code \\

            message.reply(`Checks out.`)
        }
    })
}

Part that isn't working:

let allowedUsersList = []
const allowedUsers = commandInformation.ReqUsers.forEach(userid => allowedUsersList.push(message.guild.members.cache.find(user => user.id == userid)))
console.log(allowedUsersList, message.guild.members.fetch(""))

More Info:

"discord.js": "^13.10.2"
"npm": "8.5.0"

Any kind of help would be appreciated.


Solution

  • You'll need to fetch the members first. The fetch() method returns a promise so you'll need to resolve it first. You can use await for this.

    Instead of forEach you could also use map which creates a new array. And instead of members.cache.find you could use members.cache.get with the user ID.

    You'll also need to make sure that the GUILD_MEMBERS intent is enabled otherwise you won't be able to fetch the members. You can add Intents.FLAGS.GUILD_MEMBERS to your intents array.

    Check out the working example below:

    const commandInformation = {
      CommandName: 'check',
      Alias: [],
      ReqPermissions: [],
      ReqRoles: [],
      ReqUsers: ['userid1', 'userid2'],
    };
    
    try {
      await message.guild.members.fetch();
    } catch (error) {
      console.error(error);
    }
    
    const allowedUsersList = commandInformation.ReqUsers.map((user) =>
      message.guild.members.cache.get(user),
    );
    
    console.log(allowedUsersList);
    

    Another option is to use Promise.all to wait for every member from that list to be fetched and only log them once all of these promises are resolved:

    const commandInformation = {
      CommandName: 'check',
      Alias: [],
      ReqPermissions: [],
      ReqRoles: [],
      ReqUsers: ['userid1', 'userid2'],
    };
    
    const promises = commandInformation.ReqUsers.map(
      async (user) => await message.guild.members.fetch(user),
    );
    const allowedUsersList = await Promise.all(promises);
    
    console.log(allowedUsersList);
    

    If you want to get the tags only, you can iterate over the members:

    const allowedUsersList = await Promise.all(promises);
    const tags = allowedUsersList.map((m) => m.user.tag);
    
    console.log(tags);