Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

bot.js

Raw
import { Client, Events, GatewayIntentBits } from 'discord.js';
import { loadConfig } from './config.js';
import { PufferApi } from './api.js';
import { Lifecycle } from './lifecycle.js';
import { occupancy } from './occupancy.js';
import { ShardReadiness } from './readiness.js';
import { PollController } from './telemetry.js';
import { DiscordUi } from './discord-ui.js';

async function main() {
  const config = await loadConfig();
  const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
  const readiness = new ShardReadiness();
  const controls = new Map(config.mappings.map(mapping => {
    const api = new PufferApi({ baseUrl: config.panelUrl, clientId: mapping.oauthClientId, clientSecret: mapping.oauthClientSecret });
    const poller = new PollController({ serverId: mapping.serverId, api, game: mapping.game });
    const control = new Lifecycle({ serverId: mapping.serverId, api, onBeforeStart: () => poller.prepareStartup(), onStart: () => poller.beginStartup(), onStop: () => poller.beginStop() });
    poller.onState = state => control.observeTelemetry(state);
    return [mapping.voiceChannelId, { mapping, shardId: undefined, control, poller }];
  }));
  const ui = new DiscordUi({ client, config, entries: controls });

  function cachedGuild(entry) {
    return client.guilds.cache.get(entry.mapping.guildId);
  }

  function reconcile(entry) {
    const guild = cachedGuild(entry);
    if (guild) entry.shardId = guild.shardId;
    const state = occupancy(guild, entry.mapping.voiceChannelId);
    entry.control.reconcile({ ...state, known: state.known && readiness.has(entry.shardId) });
  }

  function reconcileShard(shardId) {
    for (const entry of controls.values()) {
      if (entry.shardId === shardId || cachedGuild(entry)?.shardId === shardId) reconcile(entry);
    }
  }

  function invalidateGuild(guildId) {
    for (const entry of controls.values()) {
      if (entry.mapping.guildId === guildId) entry.control.reconcile({ known: false, humans: 0 });
    }
  }

  client.once(Events.ClientReady, () => {
    readiness.bootstrap(client.ws.shards.keys());
    for (const entry of controls.values()) {
      void entry.poller.start().catch(() => console.warn(`PufferPanel-Telemetrie ${entry.mapping.displayName}: nicht gestartet`));
      reconcile(entry);
    }
    void ui.start().catch(() => console.warn('Discord-Bedienung: nicht gestartet'));
  });
  client.on(Events.ShardReady, shardId => {
    if (readiness.ready(shardId)) reconcileShard(shardId);
  });
  client.on(Events.ShardResume, shardId => {
    if (readiness.resume(shardId)) reconcileShard(shardId);
  });
  client.on(Events.ShardReconnecting, shardId => {
    readiness.unavailable(shardId);
    reconcileShard(shardId);
  });
  client.on(Events.ShardDisconnect, (_event, shardId) => {
    readiness.unavailable(shardId);
    reconcileShard(shardId);
  });
  client.on(Events.GuildUnavailable, guild => invalidateGuild(guild.id));
  client.on(Events.GuildDelete, guild => invalidateGuild(guild.id));
  for (const event of [Events.GuildAvailable, Events.GuildCreate]) {
    client.on(event, guild => {
      for (const entry of controls.values()) {
        if (entry.mapping.guildId === guild.id && readiness.has(guild.shardId)) reconcile(entry);
      }
    });
  }
  client.on(Events.ChannelDelete, channel => {
    const entry = controls.get(channel.id);
    if (entry) entry.control.reconcile({ known: false, humans: 0 });
  });
  client.on(Events.VoiceStateUpdate, (oldState, newState) => {
    for (const entry of controls.values()) {
      if (oldState.channelId === entry.mapping.voiceChannelId || newState.channelId === entry.mapping.voiceChannelId) reconcile(entry);
    }
  });

  let stopping = false;
  async function shutdown() {
    if (stopping) return;
    stopping = true;
    ui.close();
    for (const entry of controls.values()) {
      entry.control.close();
      entry.poller.close();
    }
    client.destroy();
  }
  process.once('SIGINT', () => void shutdown());
  process.once('SIGTERM', () => void shutdown());
  client.on(Events.Error, () => console.warn('Discord-Verbindung: Fehler'));
  try { await client.login(config.discordToken); }
  catch { await shutdown(); throw new Error('login-failed'); }
}

try { await main(); } catch { console.error('Unfugwart konnte nicht gestartet werden. Konfiguration und Discord-Verbindung prüfen.'); process.exitCode = 1; }