diff --git a/.env.example b/.env.example index e96e75cbe..dad822c8a 100644 --- a/.env.example +++ b/.env.example @@ -210,10 +210,16 @@ LUCKY_NOTIFY_API_KEY= # LUCKY_MEMBERS_API_KEY is used by the /api/service/guild/* endpoints (Criativaria admin panel) LUCKY_MEMBERS_API_KEY= -# top.gg vote webhook (optional — for the /webhooks/topgg-votes endpoint) +# top.gg integration (optional — for vote webhooks and stats posting) +# TOPGG_AUTH_TOKEN: webhook auth token for the /webhooks/topgg-votes endpoint. # Get this from https://top.gg/bot//webhooks after listing the bot. # The value you paste in top.gg's "Authorization" field must match this. # TOPGG_AUTH_TOKEN=your_topgg_webhook_auth_token +# +# TOPGG_TOKEN: bot-stats API token for posting server count to Top.gg. +# Get this from https://top.gg/bot/ in the Bot → Webhooks/API section. +# When set, the bot posts its server count every 30 minutes (and on startup). +# TOPGG_TOKEN=your_topgg_api_token # Service announcements (hardened endpoint for internal admin panel) # API key for /api/service/announce endpoint diff --git a/packages/bot/src/bot/start/initializer.ts b/packages/bot/src/bot/start/initializer.ts index 417f3b5c8..c6cd4fffb 100644 --- a/packages/bot/src/bot/start/initializer.ts +++ b/packages/bot/src/bot/start/initializer.ts @@ -24,6 +24,7 @@ import { musicWatchdogService } from '../../utils/music/watchdog' import { birthdayScheduler } from '../../utils/general/birthdayScheduler' import { reminderScheduler } from '../../utils/general/reminderScheduler' import { giveawayScheduler } from '../../utils/general/giveawayScheduler' +import { topggStatsScheduler } from '../../utils/general/topggStatsScheduler' import { modDigestSchedulerService } from '../../utils/moderation/modDigestScheduler' import { aiDevToolkitService } from '../../services/AiDevToolkitService' import { dependencyCheckService } from '../../services/DependencyCheckService' @@ -224,6 +225,12 @@ export class BotInitializer { errorLog({ message: 'Error stopping giveaway scheduler:', error }) } + try { + topggStatsScheduler.stop() + } catch (error) { + errorLog({ message: 'Error stopping Top.gg stats scheduler:', error }) + } + try { modDigestSchedulerService.stop() } catch (error) { diff --git a/packages/bot/src/handlers/clientHandler/service.ts b/packages/bot/src/handlers/clientHandler/service.ts index 5f3ecb971..da8ccd915 100644 --- a/packages/bot/src/handlers/clientHandler/service.ts +++ b/packages/bot/src/handlers/clientHandler/service.ts @@ -10,6 +10,7 @@ import { modDigestSchedulerService } from '../../utils/moderation/modDigestSched import { birthdayScheduler } from '../../utils/general/birthdayScheduler' import { reminderScheduler } from '../../utils/general/reminderScheduler' import { giveawayScheduler } from '../../utils/general/giveawayScheduler' +import { topggStatsScheduler } from '../../utils/general/topggStatsScheduler' import { criativariaLiveNotificationService } from '../../services/CriativariaLiveNotificationService' let presenceControls: { @@ -150,6 +151,15 @@ export async function startClient({ }) } + try { + topggStatsScheduler.start(client) + } catch (error) { + errorLog({ + message: 'Failed to start Top.gg stats scheduler', + error, + }) + } + try { criativariaLiveNotificationService.start(client) } catch (error) { diff --git a/packages/bot/src/utils/general/topggStatsScheduler.spec.ts b/packages/bot/src/utils/general/topggStatsScheduler.spec.ts new file mode 100644 index 000000000..c27c66ebd --- /dev/null +++ b/packages/bot/src/utils/general/topggStatsScheduler.spec.ts @@ -0,0 +1,196 @@ +import { describe, test, expect, jest, beforeEach } from '@jest/globals' + +jest.mock('@lucky/shared/utils', () => ({ + infoLog: jest.fn(), + warnLog: jest.fn(), +})) + +jest.mock('../monitoring/sentry', () => ({ + addBreadcrumb: jest.fn(), + captureMessage: jest.fn(), +})) + +import { TopggStatsScheduler } from './topggStatsScheduler' +import { infoLog, warnLog } from '@lucky/shared/utils' +import { captureMessage } from '../monitoring/sentry' + +function makeClient(guildCount: number) { + return { + guilds: { + cache: { + size: guildCount, + }, + }, + } +} + +beforeEach(() => { + jest.clearAllMocks() + delete process.env.TOPGG_TOKEN +}) + +describe('TopggStatsScheduler', () => { + test('should skip entirely when TOPGG_TOKEN is unset', async () => { + const mockFetch = jest.fn() + const scheduler = new TopggStatsScheduler({ fetch: mockFetch }) + const client = makeClient(5) as any + + scheduler.start(client) + + expect(infoLog).toHaveBeenCalledWith({ + message: expect.stringContaining('TOPGG_TOKEN not set'), + }) + expect(mockFetch).not.toHaveBeenCalled() + + // start() arms the interval timer before the token check early-returns, + // so it must be stopped to avoid leaking a timer into later tests. + scheduler.stop() + }) + + test('should POST server count on ready and every interval when TOPGG_TOKEN is set', async () => { + process.env.TOPGG_TOKEN = 'test-token-123' + const mockFetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + statusText: 'OK', + }) + const scheduler = new TopggStatsScheduler({ + tickIntervalMs: 100, + fetch: mockFetch, + }) + const client = makeClient(42) as any + const timeoutSpy = jest.spyOn(AbortSignal, 'timeout') + + scheduler.start(client) + + // Wait for onStart's immediate tick to complete + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(mockFetch).toHaveBeenCalledWith( + 'https://top.gg/api/bots/962198089161134131/stats', + expect.objectContaining({ + method: 'POST', + headers: { + Authorization: 'test-token-123', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ server_count: 42 }), + // Bounded so a stalled POST can't wedge the scheduler forever. + signal: expect.any(AbortSignal), + }), + ) + // ...and bounded to the intended 10s, not just any signal. + expect(timeoutSpy).toHaveBeenCalledWith(10_000) + timeoutSpy.mockRestore() + expect(infoLog).toHaveBeenCalledWith({ + message: 'Top.gg stats posted successfully', + data: { serverCount: 42 }, + }) + + scheduler.stop() + }) + + test('should log warning and capture Sentry message on failed POST', async () => { + process.env.TOPGG_TOKEN = 'test-token-123' + const mockFetch = jest.fn().mockResolvedValue({ + ok: false, + status: 500, + statusText: 'Internal Server Error', + text: jest.fn().mockResolvedValue('error details'), + }) + const scheduler = new TopggStatsScheduler({ + tickIntervalMs: 100, + fetch: mockFetch, + }) + const client = makeClient(10) as any + + scheduler.start(client) + + // Wait for onStart's immediate tick to complete + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(warnLog).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining('Top.gg stats POST failed'), + data: expect.objectContaining({ + status: 500, + serverCount: 10, + }), + }), + ) + expect(captureMessage).toHaveBeenCalledWith( + expect.stringContaining('Top.gg stats POST failed'), + 'warning', + expect.objectContaining({ + category: 'topgg.stats', + serverCount: 10, + }), + ) + + scheduler.stop() + }) + + test('should log warning on fetch error', async () => { + process.env.TOPGG_TOKEN = 'test-token-123' + const testError = new Error('Network error') + const mockFetch = jest.fn().mockRejectedValue(testError) + const scheduler = new TopggStatsScheduler({ + tickIntervalMs: 100, + fetch: mockFetch, + }) + const client = makeClient(7) as any + + scheduler.start(client) + + // Wait for onStart's immediate tick to complete + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(warnLog).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + 'Top.gg stats POST request failed', + ), + data: expect.objectContaining({ + serverCount: 7, + }), + }), + ) + expect(captureMessage).toHaveBeenCalledWith( + expect.stringContaining('Top.gg stats POST request failed'), + 'warning', + expect.objectContaining({ + category: 'topgg.stats', + }), + ) + + scheduler.stop() + }) + + test('should use global fetch when no fetch override provided', async () => { + process.env.TOPGG_TOKEN = 'test-token-123' + const originalFetch = global.fetch + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + statusText: 'OK', + }) as typeof global.fetch + const scheduler = new TopggStatsScheduler() + const client = makeClient(3) as any + + try { + scheduler.start(client) + + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining('top.gg/api/bots'), + expect.objectContaining({ + method: 'POST', + }), + ) + } finally { + scheduler.stop() + global.fetch = originalFetch + } + }) +}) diff --git a/packages/bot/src/utils/general/topggStatsScheduler.ts b/packages/bot/src/utils/general/topggStatsScheduler.ts new file mode 100644 index 000000000..676e15a7e --- /dev/null +++ b/packages/bot/src/utils/general/topggStatsScheduler.ts @@ -0,0 +1,133 @@ +import { infoLog, warnLog } from '@lucky/shared/utils' +import { TOP_GG_BOT_ID } from '@lucky/shared/constants' +import { addBreadcrumb, captureMessage } from '../monitoring/sentry' + +import { IntervalScheduler } from './IntervalScheduler' + +// Tick every 30 minutes to post stats +const DEFAULT_TICK_INTERVAL_MS = 30 * 60 * 1000 + +// Bound each POST so a stalled connection can't leave the scheduler's +// single-flight guard set forever (which would skip every later tick). +const TOPGG_FETCH_TIMEOUT_MS = 10_000 + +type TopggStatsSchedulerOptions = { + tickIntervalMs?: number + fetch?: typeof fetch +} + +export class TopggStatsScheduler extends IntervalScheduler { + private readonly fetchFn: typeof fetch + private loggedMissingToken = false + + constructor(options: TopggStatsSchedulerOptions = {}) { + super(options.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS) + this.fetchFn = options.fetch ?? fetch + } + + protected onStart(): void { + const token = process.env.TOPGG_TOKEN + if (!token) { + if (!this.loggedMissingToken) { + infoLog({ + message: + 'TOPGG_TOKEN not set — Top.gg stats posting disabled', + }) + this.loggedMissingToken = true + } + return + } + + infoLog({ + message: `Top.gg stats scheduler started (interval: ${this.tickIntervalMs}ms)`, + }) + // Run once immediately on startup so stats are posted right after bot connects + void this.tick() + } + + protected async execute(): Promise { + const token = process.env.TOPGG_TOKEN + if (!token) { + // Silently return — already logged once at startup + return + } + + if (!this.client) return + + const serverCount = this.client.guilds.cache.size + + try { + const response = await this.fetchFn( + `https://top.gg/api/bots/${TOP_GG_BOT_ID}/stats`, + { + method: 'POST', + headers: { + Authorization: token, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ server_count: serverCount }), + signal: AbortSignal.timeout(TOPGG_FETCH_TIMEOUT_MS), + }, + ) + + if (!response.ok) { + const text = await response.text() + const statusText = + response.statusText || `HTTP ${response.status}` + warnLog({ + message: `Top.gg stats POST failed: ${statusText}`, + data: { + status: response.status, + statusText, + serverCount, + responseBody: text.slice(0, 500), // Log first 500 chars + }, + }) + + addBreadcrumb( + `Top.gg stats POST failed: ${statusText}`, + 'topgg.stats', + 'warning', + { status: response.status, serverCount }, + ) + + captureMessage( + `Top.gg stats POST failed: ${statusText} (status ${response.status})`, + 'warning', + { + category: 'topgg.stats', + serverCount, + status: response.status, + }, + ) + return + } + + infoLog({ + message: 'Top.gg stats posted successfully', + data: { serverCount }, + }) + } catch (error) { + warnLog({ + message: 'Top.gg stats POST request failed', + error: error as Error, + data: { serverCount }, + }) + + addBreadcrumb( + 'Top.gg stats POST request failed', + 'topgg.stats', + 'warning', + { error: String(error), serverCount }, + ) + + captureMessage( + `Top.gg stats POST request failed: ${String(error)}`, + 'warning', + { category: 'topgg.stats', serverCount }, + ) + } + } +} + +export const topggStatsScheduler = new TopggStatsScheduler()