0

I made a function that supposed to return a role member count but it returns "undefined".

Here's my code:

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', (message) => {
    argument = message.content.split(' ');
    switch (argument[0]) {
        case 'showmember':
          let membercount = (therole) => {
            let role = message.guild.roles.cache.find(r => r.name === therole);
            message.guild.members.fetch().then(fetched => {
              let total = fetched.filter(m => m.roles.cache.some(r => r === role));
              return total.length;
            });
          };
          message.channel.send(membercount(argument.join(',').slice('showmember'.length)));
        break;
    }
}

This is what it says on the console (node:133436) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message

1 Answers1

2

The reason why it returns "undefined" is because .fetch() is a promise and thus your function called membercount does not immediately return a value. In fact, membercount doesn't even return a value. You can refer to Return from a promise then() for why. Solution to this is just replacing return total.length with message.channel.send(total.length).

Additionally, I have to point out that message.content.slice('showmember'.length) would be an empty string. The problem lies with your switch statement switch (message.content) because your case statement would be looking for an exact match message.content === 'showmember'. What you want to do instead is to check if message.content starts with 'showmember'. I recommend replacing your switch-case statement with if(message.content.startsWith('showmember') or something of similar logic.

secretlyrice
  • 305
  • 1
  • 6