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(() => {});
}