How to add server stats channels on discord.js?

by elisha_langworth , in category: Javascript , a month ago

How to add server stats channels on discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ryan.murray , a month ago

@elisha_langworth 

Member

by aubrey , a month ago

@elisha_langworth 

To add server stats channels on Discord.js, you can create a command that fetches the necessary information and sends it to a specific text channel. Here's an example implementation using Discord.js:

  1. First, ensure you have Discord.js installed by running the following command in your terminal:
1
npm install discord.js


  1. Create a new JavaScript file (e.g., serverStats.js) and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const Discord = require('discord.js');
const client = new Discord.Client();
const { token, guildId, channelId } = require('./config.json'); // Create a JSON file with the necessary information

client.once('ready', async () => {
    const guild = await client.guilds.cache.get(guildId);
    const channel = await guild.channels.cache.get(channelId);

    const totalMembers = guild.memberCount;
    const onlineMembers = guild.members.cache.filter(member => member.presence.status !== 'offline').size;
    const offlineMembers = totalMembers - onlineMembers;

    const statsEmbed = new Discord.MessageEmbed()
        .setTitle('Server Stats')
        .addField('Total Members', totalMembers, true)
        .addField('Online Members', onlineMembers, true)
        .addField('Offline Members', offlineMembers, true);

    channel.send(statsEmbed);
});

client.login(token);


  1. Create a config.json file in the same directory as serverStats.js with the following structure:
1
2
3
4
5
{
    "token": "YOUR_DISCORD_BOT_TOKEN",
    "guildId": "YOUR_GUILD_ID",
    "channelId": "YOUR_TEXT_CHANNEL_ID"
}


  1. Replace "YOUR_DISCORD_BOT_TOKEN", "YOUR_GUILD_ID", and "YOUR_TEXT_CHANNEL_ID" with your own bot token, guild ID, and text channel ID.
  2. Run your script using Node.js:
1
node serverStats.js


Your bot should come online and fetch the server stats, sending them to the specified text channel in your Discord server. Remember to add proper error handling and permissions check for fetching guild and channel data.