eeb12

Create a plugin which is capable of linking to ER:LC

Kodari AI
KodariAug 29 at 11:04 am 1
ERLCBridge
A Discord bot plugin that links to Emergency Response: Liberty County (ER:LC) game servers. It connects to the ER:LC API to fetch real-time server data including player counts, active calls, and server status. The plugin provides Discord slash commands for viewing server statistics, tracking player activity, and receiving automated notifications when significant events occur in-game. It includes configurable webhook integration for real-time updates, role-based permission controls, and a dashboard-style embed system for displaying server metrics. Built with modular architecture for easy extension and customization of ER:LC data feeds.

Plan:

  1. Create a Discord.js slash-command bot with ER:LC API configuration.

  2. Add ER:LC client methods for server status, players, queue, and admin commands.

  3. Add command registration, runtime error handling, and environment templates.

Created an ER:LC Discord integration bot with:

  • /erlc status — displays server name, player count, owner IDs, and join link.

  • /erlc players — lists current ER:LC players.

  • /erlc queue — displays the server queue.

  • /erlc link — provides the ER:LC join URL.

  • /erlc command — sends server commands, restricted to members with Manage Server permission.

  • ER:LC API client with request timeout and error handling.

  • Slash-command registration script.

  • .env.example and .gitignore.

Setup:

Shell
npm install
cp .env.example .env

Fill in the Discord and ER:LC credentials, then run:

Shell
npm run register
npm start
eeb12

Wait what do I need to do?

Kodari AI
KodariAug 29 at 11:06 am 1

You need to do these steps:

  1. Install Node.js 18.17 or newer.

  2. Create a Discord bot:

    • Create an application.

    • Open Bot → Reset Token and copy the token.

    • Copy the Application ID from General Information.

    • Use the OAuth2 URL generator to invite the bot with:

      • bot

      • applications.commands

    • Give it permission to send messages and embeds.

  3. Get your ER:LC server key.

    • Obtain the server key from the ER:LC/Police Roleplay Community API system.

    • The key must belong to the ER:LC server you want to connect.

  4. Create your environment file:

    Shell
    cp .env.example .env
    

    Then edit .env:

    Env
    DISCORD_TOKEN=your_discord_bot_token
    CLIENT_ID=your_discord_application_id
    GUILD_ID=your_discord_server_id
    
    ERLC_SERVER_KEY=your_erlc_server_key
    ERLC_API_BASE_URL=https://api.policeroleplay.community/v1
    ERLC_PRIVATE_SERVER_CODE=
    

    GUILD_ID is your Discord server ID. Enable Developer Mode in Discord, then right-click your server and select Copy Server ID.

  5. Install dependencies:

    Shell
    npm install
    
  6. Register the slash commands:

    Shell
    npm run register
    
  7. Start the bot:

    Shell
    npm start
    

Once it is running, use these commands in Discord:

  • /erlc status

  • /erlc players

  • /erlc queue

  • /erlc link

  • /erlc command

Keep the terminal running while you use the bot. Also, never share your .env file or Discord/API tokens publicly.

Kodari can make mistakes. Review important code before using.
Files
src
.gitignore
package.json
Code
7 387
src/index.js
const {
  Client,
  EmbedBuilder,
  GatewayIntentBits,
  PermissionFlagsBits
} = require('discord.js');
const { getDiscordConfig, getERLCConfig } = require('./config');
const { ERLCClient, ERLCError } = require('./erlcClient');

const discordConfig = getDiscordConfig();
const erlcConfig = getERLCConfig();
const erlc = new ERLCClient(erlcConfig);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

function firstValue(object, ...keys) {
  for (const key of keys) {
    if (object && object[key] !== undefined && object[key] !== null) {
      return object[key];
    }
  }
  return null;
}

function asArray(value, keys = []) {
  if (Array.isArray(value)) return value;
  for (const key of keys) {
    if (Array.isArray(value?.[key])) return value[key];
  }
  return [];
}

function playerLine(player) {
  const name = firstValue(player, 'Player', 'Name', 'Username') || 'Unknown player';
  const team = firstValue(player, 'Team', 'team');
  const permission = firstValue(player, 'Permission', 'permission');
  const callsign = firstValue(player, 'Callsign', 'CallSign');
  const details = [callsign, team, permission].filter(Boolean).join(' • ');
  return details ? `**${name}** — ${details}` : `**${name}**`;
}

function splitLines(lines, maxLength = 950) {
  const chunks = [];
  let current = '';

  for (const line of lines) {
    if (current && current.length + line.length + 1 > maxLength) {
      chunks.push(current);
      current = '';
    }
    current += `${current ? '\n' : ''}${line}`;
  }
  if (current) chunks.push(current);
  return chunks;
}

function joinUrl(code) {
  return `https://policeroleplay.community/join?code=${encodeURIComponent(code)}`;
}

function apiErrorMessage(error) {
  if (error instanceof ERLCError) {
    return error.status ? `${error.message} (HTTP ${error.status})` : error.message;
  }
  return 'An unexpected error occurred while contacting the ER:LC API.';
}

async function showStatus(interaction) {
  const server = await erlc.getServer();
  const name = firstValue(server, 'Name', 'name') || 'ER:LC server';
  const currentPlayers = firstValue(server, 'CurrentPlayers', 'currentPlayers');
  const maxPlayers = firstValue(server, 'MaxPlayers', 'maxPlayers');
  const ownerId = firstValue(server, 'OwnerId', 'ownerId');
  const coOwnerId = firstValue(server, 'CoOwnerId', 'coOwnerId');
  const joinCode = firstValue(server, 'JoinCode', 'joinCode');
  const embed = new EmbedBuilder()
    .setColor(0x2f80ed)
    .setTitle(`ER:LC • ${name}`)
    .addFields({
      name: 'Players',
      value: currentPlayers !== null && maxPlayers !== null ? `${currentPlayers}/${maxPlayers}` : 'Unavailable',
      inline: true
    });

  if (ownerId !== null) embed.addFields({ name: 'Owner ID', value: String(ownerId), inline: true });
  if (coOwnerId !== null) embed.addFields({ name: 'Co-owner ID', value: String(coOwnerId), inline: true });
  if (joinCode) embed.setURL(joinUrl(joinCode));
  embed.setTimestamp();
  await interaction.editReply({ embeds: [embed] });
}

async function showPlayers(interaction) {
  const players = asArray(await erlc.getPlayers(), ['Players', 'players']);
  if (!players.length) {
    await interaction.editReply('There are currently no players in the ER:LC server.');
    return;
  }

  const chunks = splitLines(players.map(playerLine));
  const embed = new EmbedBuilder()
    .setColor(0x27ae60)
    .setTitle(`ER:LC Players (${players.length})`)
    .setDescription(chunks[0]);

  for (let index = 1; index < Math.min(chunks.length, 25); index += 1) {
    embed.addFields({ name: `Players continued (${index + 1})`, value: chunks[index] });
  }
  await interaction.editReply({ embeds: [embed] });
}

async function showQueue(interaction) {
  const queue = asArray(await erlc.getQueue(), ['Queue', 'queue']);
  if (!queue.length) {
    await interaction.editReply('The ER:LC server queue is empty.');
    return;
  }

  const lines = queue.map((entry, index) => {
    const name = typeof entry === 'string'
      ? entry
      : firstValue(entry, 'Player', 'Name', 'Username') || 'Unknown player';
    return `${index + 1}. **${name}**`;
  });
  const embed = new EmbedBuilder()
    .setColor(0xf2c94c)
    .setTitle(`ER:LC Queue (${queue.length})`)
    .setDescription(splitLines(lines)[0]);
  await interaction.editReply({ embeds: [embed] });
}

async function showLink(interaction) {
  const server = await erlc.getServer();
  const code = erlcConfig.privateServerCode || firstValue(server, 'JoinCode', 'joinCode');
  if (!code) {
    await interaction.editReply('No ER:LC join code is configured or available from the API.');
    return;
  }

  await interaction.editReply({
    content: `Join the linked ER:LC server: ${joinUrl(code)}`
  });
}

async function sendCommand(interaction) {
  if (!interaction.memberPermissions?.has(PermissionFlagsBits.ManageGuild)) {
    await interaction.editReply('You need the **Manage Server** permission to run ER:LC commands.');
    return;
  }

  const command = interaction.options.getString('command', true).trim();
  if (command.length > 200) {
    await interaction.editReply('ER:LC commands must be 200 characters or fewer.');
    return;
  }

  await erlc.executeCommand(command);
  await interaction.editReply(`Sent ER:LC command: \`${command}\``);
}

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}`);
});

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== 'erlc') return;

  const subcommand = interaction.options.getSubcommand();
  if (subcommand === 'command' && !interaction.memberPermissions?.has(PermissionFlagsBits.ManageGuild)) {
    await interaction.reply({
      content: 'You need the **Manage Server** permission to run ER:LC commands.',
      ephemeral: true
    });
    return;
  }

  await interaction.deferReply();
  try {
    switch (subcommand) {
      case 'status':
        await showStatus(interaction);
        break;
      case 'players':
        await showPlayers(interaction);
        break;
      case 'queue':
        await showQueue(interaction);
        break;
      case 'link':
        await showLink(interaction);
        break;
      case 'command':
        await sendCommand(interaction);
        break;
      default:
        await interaction.editReply('Unknown ER:LC subcommand.');
    }
  } catch (error) {
    console.error('ER:LC request failed:', error);
    const message = `ER:LC request failed: ${apiErrorMessage(error)}`;
    await interaction.editReply({ content: message, embeds: [] }).catch(() => {});
  }