mirror of
https://github.com/legop3/MultiRoombaRover.git
synced 2026-09-18 18:40:47 -04:00
fix discord bot config restart and startup connection retry
Container image / image (push) Failing after 1m1s
Container image / image (push) Failing after 1m1s
This commit is contained in:
@@ -6,12 +6,14 @@ const { MessageFlags } = require('discord.js');
|
|||||||
function createChannelIO({ client, logger, sanitizeMentions }) {
|
function createChannelIO({ client, logger, sanitizeMentions }) {
|
||||||
const channelCache = new Map();
|
const channelCache = new Map();
|
||||||
const typingMessageCache = new Map();
|
const typingMessageCache = new Map();
|
||||||
|
let stopped = false;
|
||||||
|
|
||||||
async function fetchChannel(id) {
|
async function fetchChannel(id) {
|
||||||
if (!id) return null;
|
if (stopped || !client.isReady() || !id) return null;
|
||||||
if (channelCache.has(id)) return channelCache.get(id);
|
if (channelCache.has(id)) return channelCache.get(id);
|
||||||
try {
|
try {
|
||||||
const channel = await client.channels.fetch(id);
|
const channel = await client.channels.fetch(id);
|
||||||
|
if (stopped) return null;
|
||||||
if (channel) {
|
if (channel) {
|
||||||
channelCache.set(id, channel);
|
channelCache.set(id, channel);
|
||||||
return channel;
|
return channel;
|
||||||
@@ -68,6 +70,7 @@ function createChannelIO({ client, logger, sanitizeMentions }) {
|
|||||||
const content = `-# *${username} is typing...*`;
|
const content = `-# *${username} is typing...*`;
|
||||||
try {
|
try {
|
||||||
const message = await channel.send({ content, allowedMentions: { parse: [] }, flags: [MessageFlags.SuppressNotifications]});
|
const message = await channel.send({ content, allowedMentions: { parse: [] }, flags: [MessageFlags.SuppressNotifications]});
|
||||||
|
if (stopped) return;
|
||||||
const timeoutId = setTimeout(() => {
|
const timeoutId = setTimeout(() => {
|
||||||
clearTypingMessage(entry.guildId, typingId);
|
clearTypingMessage(entry.guildId, typingId);
|
||||||
}, 20000);
|
}, 20000);
|
||||||
@@ -78,6 +81,12 @@ function createChannelIO({ client, logger, sanitizeMentions }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
stop() {
|
||||||
|
stopped = true;
|
||||||
|
for (const record of typingMessageCache.values()) clearTimeout(record.timeoutId);
|
||||||
|
typingMessageCache.clear();
|
||||||
|
channelCache.clear();
|
||||||
|
},
|
||||||
fetchChannel,
|
fetchChannel,
|
||||||
sendToChannel,
|
sendToChannel,
|
||||||
clearTypingMessage,
|
clearTypingMessage,
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// Owns connection replacement and recovery from failed initial logins.
|
||||||
|
function createConnectionManager({ createRuntime, logger }) {
|
||||||
|
let desired = { enabled: false, token: '' };
|
||||||
|
let revision = 0;
|
||||||
|
let runtime = null;
|
||||||
|
let queue = Promise.resolve();
|
||||||
|
let retryTimer = null;
|
||||||
|
let retryDelay = 5000;
|
||||||
|
|
||||||
|
function enqueue(operation) {
|
||||||
|
const pending = queue.then(operation);
|
||||||
|
// Report failures without poisoning subsequent configuration changes.
|
||||||
|
queue = pending.catch((err) => logger.error('Discord connection update failed', err.message));
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stop() {
|
||||||
|
const previous = runtime;
|
||||||
|
runtime = null;
|
||||||
|
if (!previous) return;
|
||||||
|
previous.stop();
|
||||||
|
// discord.js cannot cancel login while gateway discovery is pending.
|
||||||
|
// Let that attempt settle before destroying it, otherwise it can open a
|
||||||
|
// socket after destroy() has already run and leave an orphan connection.
|
||||||
|
await previous.login;
|
||||||
|
await previous.client.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleRetry(version) {
|
||||||
|
if (version !== revision || !desired.enabled) return;
|
||||||
|
const delay = retryDelay;
|
||||||
|
retryDelay = Math.min(retryDelay * 2, 60000);
|
||||||
|
logger.warn('Retrying Discord login', { delayMs: delay });
|
||||||
|
retryTimer = setTimeout(() => {
|
||||||
|
retryTimer = null;
|
||||||
|
enqueue(() => start(version));
|
||||||
|
}, delay);
|
||||||
|
retryTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start(version) {
|
||||||
|
if (version !== revision || !desired.enabled) return;
|
||||||
|
await stop();
|
||||||
|
if (version !== revision || !desired.enabled) return;
|
||||||
|
const current = createRuntime();
|
||||||
|
runtime = current;
|
||||||
|
const { client } = current;
|
||||||
|
client.on('error', (err) => logger.error('Discord client error', err.message));
|
||||||
|
client.on('shardError', (err, shardId) => {
|
||||||
|
logger.warn('Discord connection error', { shardId, error: err.message });
|
||||||
|
});
|
||||||
|
client.on('shardDisconnect', (event, shardId) => {
|
||||||
|
logger.warn('Discord disconnected', { shardId, code: event.code });
|
||||||
|
});
|
||||||
|
client.on('clientReady', () => { retryDelay = 5000; });
|
||||||
|
|
||||||
|
// Login must not block configuration saves while the network is down.
|
||||||
|
// Each attempt has its own client, so stale login completion/cleanup cannot
|
||||||
|
// clear the credentials or stop the connection of its replacement.
|
||||||
|
current.login = client.login(desired.token).catch((err) => {
|
||||||
|
if (version !== revision || runtime !== current) return;
|
||||||
|
logger.error('Discord login failed', err.message);
|
||||||
|
enqueue(async () => {
|
||||||
|
if (version !== revision || runtime !== current) return;
|
||||||
|
await stop();
|
||||||
|
// Credentials require an operator edit; retry network/service failures.
|
||||||
|
if (err.code === 'TokenInvalid' || err.status === 401) return;
|
||||||
|
scheduleRetry(version);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function configure({ enabled, token }) {
|
||||||
|
const next = { enabled: Boolean(enabled), token };
|
||||||
|
if (next.enabled === desired.enabled && next.token === desired.token) return queue;
|
||||||
|
desired = next;
|
||||||
|
const version = ++revision;
|
||||||
|
clearTimeout(retryTimer);
|
||||||
|
retryTimer = null;
|
||||||
|
retryDelay = 5000;
|
||||||
|
return enqueue(async () => {
|
||||||
|
if (version !== revision) return;
|
||||||
|
if (desired.enabled) await start(version);
|
||||||
|
else await stop();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
configure,
|
||||||
|
refresh() { runtime?.refresh(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createConnectionManager };
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { EventEmitter } = require('node:events');
|
||||||
|
const { createConnectionManager } = require('./connection');
|
||||||
|
|
||||||
|
const flush = () => new Promise((resolve) => setImmediate(resolve));
|
||||||
|
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
let reject;
|
||||||
|
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
|
|
||||||
|
function setup(t, attempts = []) {
|
||||||
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||||
|
const runtimes = [];
|
||||||
|
const logs = [];
|
||||||
|
const manager = createConnectionManager({
|
||||||
|
logger: {
|
||||||
|
warn: (...args) => logs.push(args),
|
||||||
|
error: (...args) => logs.push(args),
|
||||||
|
},
|
||||||
|
createRuntime() {
|
||||||
|
const attempt = attempts[runtimes.length] || {};
|
||||||
|
const client = new EventEmitter();
|
||||||
|
const runtime = {
|
||||||
|
client,
|
||||||
|
stopped: false,
|
||||||
|
destroyed: false,
|
||||||
|
refresh() {},
|
||||||
|
stop() { runtime.stopped = true; },
|
||||||
|
};
|
||||||
|
client.login = async (token) => {
|
||||||
|
runtime.token = token;
|
||||||
|
await attempt.login?.();
|
||||||
|
};
|
||||||
|
client.destroy = async () => {
|
||||||
|
await attempt.destroy?.();
|
||||||
|
runtime.destroyed = true;
|
||||||
|
};
|
||||||
|
runtimes.push(runtime);
|
||||||
|
return runtime;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { manager, runtimes, logs };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('retries a network failure at startup with a fresh client', async (t) => {
|
||||||
|
const { manager, runtimes } = setup(t, [{ login: () => { throw new Error('getaddrinfo EAI_AGAIN'); } }]);
|
||||||
|
await manager.configure({ enabled: true, token: 'token' });
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes[0].stopped, true);
|
||||||
|
assert.equal(runtimes[0].destroyed, true);
|
||||||
|
t.mock.timers.tick(4999);
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes.length, 1);
|
||||||
|
t.mock.timers.tick(1);
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes.length, 2);
|
||||||
|
assert.equal(runtimes[1].token, 'token');
|
||||||
|
assert.notEqual(runtimes[0].client, runtimes[1].client);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('backs off repeated failures and cancels retries when disabled', async (t) => {
|
||||||
|
const failed = { login: () => { throw new Error('Network unavailable'); } };
|
||||||
|
const { manager, runtimes, logs } = setup(t, Array(8).fill(failed));
|
||||||
|
await manager.configure({ enabled: true, token: 'token' });
|
||||||
|
await flush();
|
||||||
|
for (const delay of [5000, 10000, 20000, 40000, 60000]) {
|
||||||
|
t.mock.timers.tick(delay);
|
||||||
|
await flush();
|
||||||
|
}
|
||||||
|
assert.deepEqual(logs.filter(([message]) => message === 'Retrying Discord login').map(([, data]) => data.delayMs),
|
||||||
|
[5000, 10000, 20000, 40000, 60000, 60000]);
|
||||||
|
await manager.configure({ enabled: false, token: 'token' });
|
||||||
|
t.mock.timers.tick(120000);
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes.length, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('waits for logout before logging in with a changed token', async (t) => {
|
||||||
|
const logout = deferred();
|
||||||
|
const { manager, runtimes } = setup(t, [{ destroy: () => logout.promise }]);
|
||||||
|
await manager.configure({ enabled: true, token: 'old' });
|
||||||
|
const change = manager.configure({ enabled: true, token: 'new' });
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes[0].stopped, true);
|
||||||
|
assert.equal(runtimes.length, 1);
|
||||||
|
logout.resolve();
|
||||||
|
await change;
|
||||||
|
assert.equal(runtimes[0].destroyed, true);
|
||||||
|
assert.equal(runtimes[1].token, 'new');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('retires a pending login before replacement and ignores its stale failure', async (t) => {
|
||||||
|
const login = deferred();
|
||||||
|
const { manager, runtimes } = setup(t, [{ login: () => login.promise }]);
|
||||||
|
await manager.configure({ enabled: true, token: 'old' });
|
||||||
|
const change = manager.configure({ enabled: true, token: 'new' });
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes[0].stopped, true);
|
||||||
|
assert.equal(runtimes[0].destroyed, false);
|
||||||
|
login.reject(new Error('Old connection failed'));
|
||||||
|
await change;
|
||||||
|
assert.equal(runtimes[0].destroyed, true);
|
||||||
|
assert.equal(runtimes[1].token, 'new');
|
||||||
|
t.mock.timers.tick(120000);
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes.length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('re-enabling creates a fresh client; unrelated config edits do not reconnect', async (t) => {
|
||||||
|
const { manager, runtimes } = setup(t);
|
||||||
|
await manager.configure({ enabled: true, token: 'token' });
|
||||||
|
await manager.configure({ enabled: true, token: 'token', channels: { general: 'new-channel' } });
|
||||||
|
assert.equal(runtimes.length, 1);
|
||||||
|
await manager.configure({ enabled: false, token: 'token' });
|
||||||
|
assert.equal(runtimes[0].destroyed, true);
|
||||||
|
await manager.configure({ enabled: true, token: 'token' });
|
||||||
|
assert.equal(runtimes.length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid credentials wait for a token edit instead of retrying', async (t) => {
|
||||||
|
const { manager, runtimes } = setup(t, [{ login: () => {
|
||||||
|
throw Object.assign(new Error('Invalid token'), { code: 'TokenInvalid' });
|
||||||
|
} }]);
|
||||||
|
await manager.configure({ enabled: true, token: 'bad' });
|
||||||
|
await flush();
|
||||||
|
t.mock.timers.tick(120000);
|
||||||
|
await flush();
|
||||||
|
assert.equal(runtimes.length, 1);
|
||||||
|
await manager.configure({ enabled: true, token: 'fixed' });
|
||||||
|
assert.equal(runtimes[1].token, 'fixed');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('client and gateway errors are logged without throwing', async (t) => {
|
||||||
|
const { manager, runtimes, logs } = setup(t);
|
||||||
|
await manager.configure({ enabled: true, token: 'token' });
|
||||||
|
runtimes[0].client.emit('error', new Error('Client failure'));
|
||||||
|
runtimes[0].client.emit('shardError', new Error('Gateway failure'), 0);
|
||||||
|
runtimes[0].client.emit('shardDisconnect', { code: 1006 }, 0);
|
||||||
|
assert.deepEqual(logs.map(([message]) => message), [
|
||||||
|
'Discord client error', 'Discord connection error', 'Discord disconnected',
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -67,6 +67,7 @@ const {
|
|||||||
} = require('../privateRoverAccessRequestService');
|
} = require('../privateRoverAccessRequestService');
|
||||||
const { subscribe } = require('../eventBus');
|
const { subscribe } = require('../eventBus');
|
||||||
const { createPresenceManager } = require('./presence');
|
const { createPresenceManager } = require('./presence');
|
||||||
|
const { createConnectionManager } = require('./connection');
|
||||||
const { createChannelIO } = require('./channelIO');
|
const { createChannelIO } = require('./channelIO');
|
||||||
const { createCommandHandlers } = require('../operatorCommandService');
|
const { createCommandHandlers } = require('../operatorCommandService');
|
||||||
const greenModeService = require('../greenModeService');
|
const greenModeService = require('../greenModeService');
|
||||||
@@ -86,9 +87,7 @@ const {
|
|||||||
buildStatusMessage,
|
buildStatusMessage,
|
||||||
} = require('../replayDeliveryService/workflow');
|
} = require('../replayDeliveryService/workflow');
|
||||||
|
|
||||||
// Discord helper modules retain references to these objects. Mutating those
|
// Keep configuration object identities stable for the active runtime's helpers.
|
||||||
// references on configuration application updates command and integration
|
|
||||||
// behavior without registering a second tree of Discord/event listeners.
|
|
||||||
const config = structuredClone(loadConfig());
|
const config = structuredClone(loadConfig());
|
||||||
const discordConfig = config.discord || {};
|
const discordConfig = config.discord || {};
|
||||||
let enabled = Boolean(discordConfig.enabled);
|
let enabled = Boolean(discordConfig.enabled);
|
||||||
@@ -106,11 +105,6 @@ const intents = [
|
|||||||
GatewayIntentBits.MessageContent,
|
GatewayIntentBits.MessageContent,
|
||||||
];
|
];
|
||||||
|
|
||||||
const client = new Client({
|
|
||||||
intents,
|
|
||||||
partials: [Partials.Channel, Partials.Message, Partials.Reaction, Partials.User],
|
|
||||||
});
|
|
||||||
|
|
||||||
function sanitizeMentions(text) {
|
function sanitizeMentions(text) {
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
return String(text)
|
return String(text)
|
||||||
@@ -156,6 +150,13 @@ function countReady() {
|
|||||||
return { ready, total };
|
return { ready, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Each connection owns its listeners, timers, and cached Discord objects.
|
||||||
|
// Rebuilding them prevents a reconnect from retaining a destroyed client.
|
||||||
|
function createDiscordRuntime() {
|
||||||
|
const client = new Client({
|
||||||
|
intents,
|
||||||
|
partials: [Partials.Channel, Partials.Message, Partials.Reaction, Partials.User],
|
||||||
|
});
|
||||||
const channelIO = createChannelIO({
|
const channelIO = createChannelIO({
|
||||||
client,
|
client,
|
||||||
logger,
|
logger,
|
||||||
@@ -181,7 +182,7 @@ const replayCaption = createReplayCaptionBuilder({
|
|||||||
// Discord is the preferred replay host only while this optional feature is
|
// Discord is the preferred replay host only while this optional feature is
|
||||||
// active. The core replay delivery service owns generation and automatically
|
// active. The core replay delivery service owns generation and automatically
|
||||||
// falls back to its local media store when any operation below fails.
|
// falls back to its local media store when any operation below fails.
|
||||||
registerPreferredDeliveryProvider({
|
const unregisterReplayProvider = registerPreferredDeliveryProvider({
|
||||||
async begin(job) {
|
async begin(job) {
|
||||||
const channelId = discordConfig.channels?.replay;
|
const channelId = discordConfig.channels?.replay;
|
||||||
if (!enabled || !channelId) throw new Error('Discord replay delivery is disabled');
|
if (!enabled || !channelId) throw new Error('Discord replay delivery is disabled');
|
||||||
@@ -405,7 +406,7 @@ function restartFleetDailyReports() {
|
|||||||
fleetDailyReports.start();
|
fleetDailyReports.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
client.on('ready', () => {
|
client.on('clientReady', () => {
|
||||||
logger.info('Discord bot logged in', { tag: client.user?.tag });
|
logger.info('Discord bot logged in', { tag: client.user?.tag });
|
||||||
presence.schedulePresenceRotation();
|
presence.schedulePresenceRotation();
|
||||||
// Discord is only a delivery consumer. Starting its scheduler after the bot
|
// Discord is only a delivery consumer. Starting its scheduler after the bot
|
||||||
@@ -414,42 +415,45 @@ client.on('ready', () => {
|
|||||||
restartFleetDailyReports();
|
restartFleetDailyReports();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
client,
|
||||||
|
refresh() {
|
||||||
|
if (client.isReady()) restartFleetDailyReports();
|
||||||
|
},
|
||||||
|
stop() {
|
||||||
|
for (const event of ['clientReady', 'messageCreate', 'typingStart', 'messageReactionAdd']) {
|
||||||
|
client.removeAllListeners(event);
|
||||||
|
}
|
||||||
|
integrationHandlers.stop();
|
||||||
|
unregisterReplayProvider();
|
||||||
|
presence.stop();
|
||||||
|
channelIO.stop();
|
||||||
|
fleetDailyReports?.stop();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const connection = createConnectionManager({ createRuntime: createDiscordRuntime, logger });
|
||||||
|
|
||||||
function replaceObject(target, source = {}) {
|
function replaceObject(target, source = {}) {
|
||||||
Object.keys(target).forEach((key) => delete target[key]);
|
Object.keys(target).forEach((key) => delete target[key]);
|
||||||
Object.assign(target, structuredClone(source));
|
Object.assign(target, structuredClone(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyDiscordConfig(nextDiscordConfig = {}) {
|
async function applyDiscordConfig(nextDiscordConfig = {}) {
|
||||||
const wasEnabled = enabled;
|
|
||||||
const previousToken = discordConfig.token;
|
|
||||||
replaceObject(discordConfig, nextDiscordConfig);
|
replaceObject(discordConfig, nextDiscordConfig);
|
||||||
config.discord = discordConfig;
|
config.discord = discordConfig;
|
||||||
enabled = Boolean(discordConfig.enabled);
|
enabled = Boolean(discordConfig.enabled);
|
||||||
|
await connection.configure(discordConfig);
|
||||||
if (!enabled) {
|
connection.refresh();
|
||||||
fleetDailyReports?.stop();
|
|
||||||
fleetDailyReports = null;
|
|
||||||
if (wasEnabled) client.destroy();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!wasEnabled || previousToken !== discordConfig.token) {
|
|
||||||
if (wasEnabled) client.destroy();
|
|
||||||
// Login health is reported by Discord itself; do not hold the committed
|
|
||||||
// configuration request open while an external network service connects.
|
|
||||||
client.login(discordConfig.token).catch((err) => {
|
|
||||||
logger.error('Discord login failed after configuration change', err.message);
|
|
||||||
});
|
|
||||||
} else if (client.isReady()) {
|
|
||||||
restartFleetDailyReports();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function applySharedConfigSection(section, value) {
|
function applySharedConfigSection(section, value) {
|
||||||
config[section] = structuredClone(value);
|
config[section] = structuredClone(value);
|
||||||
// Fleet delivery owns a timer derived from both Discord and fleet settings.
|
// Fleet delivery owns a timer derived from both Discord and fleet settings.
|
||||||
// Reconnecting is unnecessary; rebuild only that scheduler when ready.
|
// Reconnecting is unnecessary; rebuild only that scheduler when ready.
|
||||||
if (section === 'fleetReports' && client.isReady()) {
|
if (section === 'fleetReports') {
|
||||||
restartFleetDailyReports();
|
connection.refresh();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -458,10 +462,8 @@ registerConfigurationHandler('discord', applyDiscordConfig);
|
|||||||
registerConfigurationHandler(section, (value) => applySharedConfigSection(section, value));
|
registerConfigurationHandler(section, (value) => applySharedConfigSection(section, value));
|
||||||
});
|
});
|
||||||
|
|
||||||
if (enabled) {
|
connection.configure(discordConfig).catch((err) => {
|
||||||
client.login(discordConfig.token).catch((err) => {
|
logger.error('Discord startup failed', err.message);
|
||||||
logger.error('Discord login failed', err.message);
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {};
|
module.exports = {};
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ function createIntegrations(deps) {
|
|||||||
const userAnnouncements = createUserAnnouncements({ ...deps, sendToChannel, schedulePresenceRotation });
|
const userAnnouncements = createUserAnnouncements({ ...deps, sendToChannel, schedulePresenceRotation });
|
||||||
|
|
||||||
function register() {
|
function register() {
|
||||||
|
let stopped = false;
|
||||||
client.on('typingStart', (typing) => {
|
client.on('typingStart', (typing) => {
|
||||||
chat.handleDiscordTypingStart(typing).catch((err) => logger.warn('Error handling Discord typing', err.message));
|
chat.handleDiscordTypingStart(typing).catch((err) => logger.warn('Error handling Discord typing', err.message));
|
||||||
});
|
});
|
||||||
@@ -33,14 +34,31 @@ function createIntegrations(deps) {
|
|||||||
dm.handlePrivateAccessReaction(reaction, user).catch((err) => logger.warn('Error handling private access reaction', err.message));
|
dm.handlePrivateAccessReaction(reaction, user).catch((err) => logger.warn('Error handling private access reaction', err.message));
|
||||||
});
|
});
|
||||||
|
|
||||||
subscribe('*', handleBusEvent);
|
// Only the active, ready connection consumes server events. Retain each
|
||||||
subscribe('*', userAnnouncements.handleBusEvent);
|
// unsubscribe function so replacement clients never duplicate deliveries.
|
||||||
subscribe('verification.requested', dm.sendVerificationRequestDms);
|
const unsubscribe = [];
|
||||||
subscribe('privateRoverAccess.requested', dm.sendPrivateRoverAccessRequestDms);
|
function subscribeWhileReady(type, handler) {
|
||||||
subscribe('chat:message', chat.handleChatBridgeOutbound);
|
unsubscribe.push(subscribe(type, (event) => {
|
||||||
subscribe('chat:typing', chat.handleChatTypingOutbound);
|
Promise.resolve().then(() => {
|
||||||
|
if (!stopped && client.isReady()) return handler(event);
|
||||||
|
}).catch((err) => {
|
||||||
|
logger.warn('Error handling Discord integration event', { type, error: err.message });
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribeWhileReady('*', handleBusEvent);
|
||||||
|
subscribeWhileReady('*', userAnnouncements.handleBusEvent);
|
||||||
|
subscribeWhileReady('verification.requested', dm.sendVerificationRequestDms);
|
||||||
|
subscribeWhileReady('privateRoverAccess.requested', dm.sendPrivateRoverAccessRequestDms);
|
||||||
|
subscribeWhileReady('chat:message', chat.handleChatBridgeOutbound);
|
||||||
|
subscribeWhileReady('chat:typing', chat.handleChatTypingOutbound);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
stop() {
|
||||||
|
stopped = true;
|
||||||
|
unsubscribe.forEach((remove) => remove());
|
||||||
|
},
|
||||||
handleBridgeInbound: chat.handleBridgeInbound,
|
handleBridgeInbound: chat.handleBridgeInbound,
|
||||||
handleBusEvent,
|
handleBusEvent,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
|
|||||||
const PRESENCE_ROTATE_MS = 20000;
|
const PRESENCE_ROTATE_MS = 20000;
|
||||||
let presenceInterval = null;
|
let presenceInterval = null;
|
||||||
let presenceShowObjective = false;
|
let presenceShowObjective = false;
|
||||||
|
let stopped = false;
|
||||||
|
|
||||||
function truncatePresenceText(text, maxLength) {
|
function truncatePresenceText(text, maxLength) {
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
@@ -40,6 +41,7 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
|
|||||||
}
|
}
|
||||||
|
|
||||||
function schedulePresenceRotation() {
|
function schedulePresenceRotation() {
|
||||||
|
if (stopped) return;
|
||||||
if (presenceInterval) {
|
if (presenceInterval) {
|
||||||
clearInterval(presenceInterval);
|
clearInterval(presenceInterval);
|
||||||
presenceInterval = null;
|
presenceInterval = null;
|
||||||
@@ -59,6 +61,11 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
stop() {
|
||||||
|
stopped = true;
|
||||||
|
clearInterval(presenceInterval);
|
||||||
|
presenceInterval = null;
|
||||||
|
},
|
||||||
schedulePresenceRotation,
|
schedulePresenceRotation,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user