← Back to lessons
ERLC SYSTEMS

Lesson 1 — ERLC Player Count

Goal: Fetch the player count from your ER:LC private server using the API.

Lesson Overview

This lesson introduces the ERLC API. You will create a command that requests server data from the ERLC API and returns the current player count and queue size.

This lesson also shows two ways to display the response:
• Embed responses
• Discord Components V2 responses

Video Lesson

Notes — Understanding the Code

SlashCommandBuilder

Creates the slash command used in Discord.

fetch()

Sends a request to the ERLC API to retrieve server information.

Server-Key

Your ERLC API key used to authenticate requests.

EmbedBuilder

Formats the response into a styled Discord embed message.

ContainerBuilder

Used in Discord Components V2 to build advanced message layouts.

interaction.editReply()

Sends the final response back to the user after processing the API request.

Step-by-Step

Create the command file

Create: commands/playercount.js

Add your ERLC API key

{
"TOKEN": "",
"APP_ID": "",
"GUILD_ID": "",
"ERLC_API_KEY": ""
}

Embed Version (Beginner)

Show Code

	
embeds v1 player countconst { SlashCommandBuilder } = require("@discordjs/builders");
const { EmbedBuilder } = require("discord.js");
const config = require("../config.json");

module.exports = {
    dev: true, // visible only to guilds in config.json
    guilds: [''], // whitelist by guild ID
    roles: [''], // requires user to have listed role IDs
    users: [''], // whitelist by user ID
    cooldown: 0, // cooldown time in seconds
    userPerms: [''], // required user permissions
    clientPerms: [''], // required bot permissions
    alias: '', // Single Alias
	aliases: [''], // Mulitple Aliases
    defer: false, // defer without being ephemeral | true or false
	cache: true, // the next time you run this command it will jump straight to the bottom without delay. | true or false
    data: new SlashCommandBuilder()
        .setName('playercount') // Name of your slash command
        .setDescription('Fetch the current ER:LC player count in your private server'),
    async execute(interaction) {
        try {
            const response = await fetch(
                "https://api.policeroleplay.community/v1/server",
                {
                    method: "GET",
                    headers: {
                        "Server-Key": config.ERLC_API_KEY,
                    },
                }
            );

            if (!response.ok) {
                const errorData = await response.json().catch(() => null);

                const errorMessage =
                    errorData?.message ?? `HTTP ${response.status}`;
                
                    return interaction.editReply({
                        embeds: [
                            new EmbedBuilder()
                                .setTitle("API Error")
                                .setDescription(`\`\`\`${errorMessage}\`\`\``),
                        ],
                    });
            }

            const data = await response.json();

            return interaction.editReply({
                embeds: [
                    new EmbedBuilder()
                        .setTitle("ER:LC Server Response")
                        .addFields(
                            {
                                name: "Players",
                                value: `${data.CurrentPlayers} / ${data.MaxPlayers}`,
                                inline: true,
                            }
                        
                            {
                                name: "Queue",
                                value: `${data.Queue}`,
                                inline: true,
                            }
                        )
                        .setTimestamp(),
                ],
            });
        } catch (err) {
            console.error("Player Count Error: ", err);
            return interaction.editReply({
                embeds: [
                    new EmbedBuilder()
                        .setTitle("Request Failed")
                        .setDescription(
                            "An unexpected error occured when contacting the ER:LC API."
                        ),
                ],
            });
        }
    },
};

Components Version (Advanced)

Show Code


const { SlashCommandBuilder } = require("@discordjs/builders");
const {
    ContainerBuilder,
    TextDisplayBuilder,
    SeperatorBuilder,
    SeperatorSpacingSize,
    MessageFlags,
} = require("discord.js");
const config = require("../config.json")

module.exports = {
    dev: true, // visible only to guilds in config.json
    guilds: [''], // whitelist by guild ID
    roles: [''], // requires user to have listed role IDs
    users: [''], // whitelist by user ID
    cooldown: 0, // cooldown time in seconds
    userPerms: [''], // required user permissions
    clientPerms: [''], // required bot permissions
    alias: '', // Single Alias
	aliases: [''], // Mulitple Aliases
    defer: false, // defer without being ephemeral | true or false
	cache: true, // the next time you run this command it will jump straight to the bottom without delay. | true or false
    data: new SlashCommandBuilder()
        .setName('playercount') // Name of your slash command
        .setDescription('fetch player count'),
    async execute(interaction) {
        try {
            const response = await fetch(
                'https://api.policeroleplay.community/v1/server',
                {
                    method: "GET",
                    headers: {
                        "Server-Key": config.ERLC_API_KEY,
                    },
                }
            );

            if (!response.ok) {
                const errorData = await response.json().catch(() => null);
                const errorMessage =
                    errorData?.message ?? `HTTP ${response.status}`;
                const errorContainer = new ContainerBuilder()
                    .addTextDisplayComponents(
                        (t) => t.setContent("## API Error"),
                        (t) => t.setContent(`\`\`\`${errorMessage}\`\`\``)
                    );
                return interaction.editReply({
                    components: [errorContainer],
                    flags: MessageFlags.IsComponentsV2,
                });
            }
        }

        const data = await response.json();

        const container = new ContainerBuilder()
            .addTextDisplayComponents(
                (t) => t.setContent("## ERLC Server Response")
            )
            .addTextDisplayComponents(
                (t) =>
                    t.setContent(
                        `**Players:** ${data.CurrentPlayers} / ${data.MaxPlayers}`
                    ),
                (t) => t.setContent(`**Queue:** ${data.Queue}`)
            );
        return interaction.editReply({
            components: [container],
            flags: MessageFlags.IsComponentsV2,
        });
    }, catch (err) {
        console.error("Player Count Error ", err);

        const errorContainer = new ContainerBuilder()
            .addTextDisplayComponents(
                (t) => t.setContent("## Failed Request"),
                (t) =>
                    t.setContent(
                        "An unexpected error occured"
                    )
            );
        return interaction.editReply({
            components: [errorContainer],
            flags: MessageFlags.IsComponentsV2,
        });
    }
};

Restart your bot


node index.js

Challenge

Completion Checklist

← Course Home Next Lesson →