1

I'm currently working on a discord.js bot to start getting some practice with node.js I have currently run into a problem when trying to get all the members of a guild with a certain role. Here is the relevant code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const fetch = require('node-fetch');

module.exports = {
    data: new SlashCommandBuilder()
        .setName("server")
        .setDescription("Get server information"),
    async execute(interaction) {
        const serverInfo = await getServerInfo(interaction);
        await interaction.reply({ embeds: [serverInfo] });
    }
}

async function getServerInfo(interaction) {
    console.log("function called")
    let fetchedMemebers = await interaction.guild.members.fetch()
    let roles = await interaction.guild.roles.fetch()

    const totalMembers = fetchedMemebers.memberCount;
    const adminRole = roles.find(role => role.name === "Admin") //the role to check
    const totalAdmin = adminRole.members.length;
    const serverInfo = { // create the embed
        color: 0x0099ff,
        title: `${interaction.guild.name}\'s Server Information`,
        description: `Members: ${totalMembers}\nAdmins (Members with the "admin" role): ${totalAdmin}\nDate created: ${interaction.guild.createdAt.toDateString()}`,
        author: {
            name: `${interaction.user.username}`,
            icon_url: `${interaction.user.avatarURL()}`,
        },
        timestamp: new Date()
    }
    return serverInfo;
};
 
 


    

I have the following error:

DiscordAPIError: Invalid Form Body
data.embeds[0].description: This field is required
    at RequestHandler.execute (/workspace/node.js-verve-bot/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/workspace/node.js-verve-bot/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async CommandInteraction.reply (/workspace/node.js-verve-bot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:98:5)
    at async Object.execute (/workspace/node.js-verve-bot/commands/server.js:11:9)
    at async Client.<anonymous> (/workspace/node.js-verve-bot/index.js:46:3) {
  method: 'post',
  path: '/interactions/918268169842483211/aW50ZXJhY3Rpb246OTE4MjY4MTY5ODQyNDgzMjExOmVLZnZiSnJVVEdSMEdkVnJyTTR6ZFZOU3h1WkF0VnVFUllPQmZPb05RZmdZbmw3WjJpWjhRN3F4enI2SGhjek4xNDdJdjVrbGxRMXVwSzd3c0VjaldLS2phVVZpd25mUlJ0emJ1S3pRbTdDVjlTQzIxR21USUhvczVOelFLV0kx/callback',
  code: 50035,
  httpStatus: 400,
  requestData: { json: { type: 4, data: [Object] }, files: [] }
}

Yes, I know this isn't my question, and I don't believe this is my problem either. I know my embed is proper. I know something is wrong with how I'm getting the current guild's members, I have verified this by trying to console.log(totalMembers), but you get nothing. Not even an output. I'm not sure what I'm doing wrong here. Any ideas? Edit: changed my code based on the most recent answer, though the same error occurs. Also if you console.log(adminRole.members.length) there is no output again.

Verve
  • 58
  • 1
  • 10

1 Answers1

4

Get the members with Role#members. Keep in mind this relies on cache, so use Guild.members.fetch() to cache them

await interaction.guild.members.fetch() //cache all members in the server
const role = interaction.guild.roles.cache.find(role => role.name === "Admin") //the role to check
const totalAdmin = role.members.map(m => m.id) // array of user IDs who have the role
const totalMembers = totalAdmin.length // how many users have the role
MrMythical
  • 8,908
  • 2
  • 17
  • 45
  • I changed my code to include what you have said changing my code to use `await guild.members.fetch()` and `await interaction.guild.roles.fetch();`, I changed my totalAdmin and role aswell to be `const adminRole = interaction.guild.roles.cache.find(role => role.name === "Admin") //the role to check const totalAdmin = adminRole.members.length;` though I am still getting the same error. Did i possibly miss something? and how do I know when to use the `await` syntax? I'm not very familiar with async I've used it with discord.py but that's about it. – Verve Dec 09 '21 at 14:10
  • Try logging `serverinfo.description` – MrMythical Dec 09 '21 at 15:03
  • While I was doing that, I realized that my code seems to be stopping at `let fetchedMembers = await interaction.guild.members.fetch()`, I verified this by putting a `console.log` statement before and after. Only the one before the statement ran. Maybe the code isn't fetching the information, or is unable to? – Verve Dec 09 '21 at 17:53
  • Do you have Guild Members intent? – MrMythical Dec 09 '21 at 19:54
  • I have the following intents: `const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }); // create the client ` Guild members is included. It might also be worth noting that I changed my code slightly, holding the members in a variable, the fetched roles, and changed my embed some. Also, If i store the fetched members in the variable and log it, i get the output `undefined`. the embed description sends like this: Members: undefined Admins: (Members with the "Admin" role): undefined Date created: Fri Nov 12 2021 – Verve Dec 10 '21 at 02:02