Code for a slash command '/users-with-role' that sends a message to the channel with the number of users for every *used* role. Your Discord bot requires the 'Privileged Intents' permission to function.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const guild_id = context.params.event.guild_id
// Get all roles so we can send human readable role names to Discord
const roles = await lib.discord.guilds['@0.1.0'].roles.list({ guild_id });
const roleMap = roles.reduce((map, r) => ({ ...map, [r.id]: r }), {});
// Get a map of all roles and their counts
// Note: Only works for up to 1000 members
const members = await lib.discord.guilds['@0.1.0'].members.list({ guild_id, limit: 1000 });
const roleCounts = members.map(m => m.roles).flat().reduce((counts, id) => ({ ...counts, [id]: (counts[id] || 0) + 1 }), {});
await lib.discord.channels['@0.1.1'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: ``,
embed: {
title: 'Role counts',
fields: Object.entries(roleCounts).map(([id, count]) => ({ name: `@${roleMap[id].name}`, value: count })),
}
});