import { Client, Events, GatewayIntentBits, Partials, REST, Routes, SlashCommandBuilder, MessageFlags, } from 'discord.js'; import { findMatchingRules, bumpCounter, getUserByDiscord } from './db.js'; import { isActiveGuild } from './active-guilds.js'; import { extractItems } from './extract.js'; import { messageMatches } from './match.js'; import { dispatch } from './destinations/index.js'; const GUILD_GRACE_MS = Number(process.env.GUILD_GRACE_HOURS ?? 168) * 60 * 60 * 1000; const REAP_INTERVAL_MS = 60 * 60 * 1000; export const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.DirectMessages, ], partials: [Partials.Channel, Partials.Message], }); client.once(Events.ClientReady, async c => { console.log(`disjecta bot ready as ${c.user.tag} in ${c.guilds.cache.size} guild(s)`); try { await registerCommands(c.user.id); } catch (err) { console.error('slash command registration failed', err.message); } reapInactiveGuilds(); setInterval(reapInactiveGuilds, REAP_INTERVAL_MS).unref(); }); client.on(Events.GuildCreate, guild => { console.log(`disjecta: joined ${guild.name} (${guild.id}); grace ${Math.round(GUILD_GRACE_MS / 3600000)}h`); }); client.on(Events.GuildDelete, guild => { console.log(`disjecta: left ${guild.name ?? '?'} (${guild.id})`); }); // ───── gateway diagnostics ────────────────────────────────────────────────── // discord.js silently drops messages when the websocket is unhealthy. These // listeners surface every interesting transition so a "bot stopped processing" // incident is diagnosable from Railway logs alone. client.on(Events.Error, (err) => { console.error(`disjecta bot[error] ${err?.message ?? err}`, err?.stack ?? ''); }); client.on(Events.Warn, (info) => { console.warn(`disjecta bot[warn] ${info}`); }); client.on(Events.ShardError, (err, shardId) => { console.error(`disjecta bot[shardError shard=${shardId}] ${err?.message ?? err}`, err?.stack ?? ''); }); client.on(Events.ShardDisconnect, (event, shardId) => { console.warn( `disjecta bot[shardDisconnect shard=${shardId}] code=${event?.code} reason="${event?.reason ?? ''}" wasClean=${event?.wasClean ?? '?'}` ); }); client.on(Events.ShardReconnecting, (shardId) => { console.log(`disjecta bot[shardReconnecting shard=${shardId}]`); }); client.on(Events.ShardReady, (shardId, unavailableGuilds) => { const u = unavailableGuilds ? `unavailable=${unavailableGuilds.size}` : ''; console.log(`disjecta bot[shardReady shard=${shardId}] ${u}`); }); client.on(Events.ShardResume, (shardId, replayedEvents) => { console.log(`disjecta bot[shardResume shard=${shardId}] replayed=${replayedEvents}`); }); client.on(Events.Invalidated, () => { // Session is dead and discord.js can't recover — process exit lets Railway // restart us into a fresh connection. console.error('disjecta bot[invalidated] session unrecoverable; exiting so Railway restarts the container'); process.exit(1); }); client.on(Events.GuildUnavailable, (guild) => { console.warn(`disjecta bot[guildUnavailable] ${guild?.id} (${guild?.name ?? '?'})`); }); function reapInactiveGuilds() { const now = Date.now(); for (const [id, guild] of client.guilds.cache) { if (isActiveGuild(id)) continue; const joined = guild.joinedTimestamp; if (!joined) continue; const age = now - joined; if (age <= GUILD_GRACE_MS) continue; console.log(`disjecta: leaving inactive guild ${guild.name} (${id}) — no active rules after ${Math.round(age / 3600000)}h`); guild.leave().catch(err => console.error('leave failed', { id, err: err.message })); } } async function registerCommands(applicationId) { const token = process.env.DISCORD_TOKEN; if (!token) return; const commands = [ new SlashCommandBuilder() .setName('disjecta') .setDescription('disjecta — URL routing') .addSubcommand(s => s.setName('connect').setDescription('Get a link to set up your disjecta account')) .addSubcommand(s => s.setName('status').setDescription('Show your link/subscription status')) .toJSON(), ]; const rest = new REST({ version: '10' }).setToken(token); await rest.put(Routes.applicationCommands(applicationId), { body: commands }); } client.on(Events.InteractionCreate, async (interaction) => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName !== 'disjecta') return; const sub = interaction.options.getSubcommand(); const publicUrl = process.env.PUBLIC_URL; if (sub === 'connect') { const url = publicUrl ?? '(PUBLIC_URL not configured)'; return interaction.reply({ content: `Set up your disjecta account here: ${url}\n\nYou'll connect this Discord account, sign in with an Atmosphere account, and configure rules.`, flags: MessageFlags.Ephemeral, }); } if (sub === 'status') { const user = getUserByDiscord.get(interaction.user.id); if (!user) { return interaction.reply({ content: `No disjecta account connected to this Discord user yet. Run \`/disjecta connect\` to set one up.`, flags: MessageFlags.Ephemeral, }); } const lines = [ `Discord ID: \`${user.discord_id}\``, `Atmosphere DID: \`${user.did ?? '(not linked)'}\``, `Subscription: \`${user.active ? 'active' : 'inactive'}\``, ]; return interaction.reply({ content: lines.join('\n'), flags: MessageFlags.Ephemeral }); } }); client.on(Events.MessageCreate, async msg => { if (msg.author.bot) return; if (!msg.guildId) return; // Cheap pre-filter: skip the SQL hit (and never touch msg.content) for // guilds where no active customer has any enabled rule. if (!isActiveGuild(msg.guildId)) return; const rules = findMatchingRules.all({ guild_id: msg.guildId, channel_id: msg.channelId, author_id: msg.author.id, }); if (rules.length === 0) return; const ctx = { guildId: msg.guildId, channelId: msg.channelId, messageId: msg.id, authorId: msg.author.id, createdAt: new Date(msg.createdTimestamp).toISOString(), }; // Each rule decides what to extract, since two rules on the same message // may want different shapes (urls vs content). for (const rule of rules) { if (!messageMatches(msg.content, rule.match_kind, rule.match_value)) continue; const items = extractItems(msg.content, rule.mode); if (items.length === 0) continue; try { await dispatch(rule, items, ctx); bumpCounter(rule.job_id, items.length); } catch (err) { console.error('dispatch failed', { rule_id: rule.rule_id, err: err.message }); } } }); export function startBot() { return client.login(process.env.DISCORD_TOKEN); }