I'm working on a Discord game badge spoofer bot, but I'm running into an issue with the badges. The Game Variety badge works perfectly, but the Game Time badge usually only goes up to the 300-hour level and won't progress any further.
Nothing shows up in my logs, and yes, I'm aware of the 24–48 hour synchronization period.
// Badge Runner — converts BadgeMaxxer.py logic to JS.
// Uses Discord's telemetry API (/api/v9/science) to send
// game events (launch_game + running_game_heartbeat) that count
// toward the Game Variety and Game Time badges.
const https = require('https');
const crypto = require('crypto');
const { MessageFlags, ContainerBuilder, SeparatorSpacingSize } = require('discord.js');
// ── Constants ──────────────────────────────────────────────────────────────────
const TELEMETRY_URL = '/api/v9/science';
const IDENTITY_URL = '/api/v9/users/@me?with_analytics_token=true';
const CATALOG_URL = 'https://cdn.discordapp.com/detectables/games.json';
const BATCH_LIMIT = 50;
const NETWORK_COOLDOWN_MS = 1000; // 1s between batches (same as original spoofer.py)
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) discord/1.0.9253 Chrome/148.0.7778.280 Electron/42.7.1 Safari/537.36';
const CLIENT_LOCALE = 'en-US';
const CLIENT_TIMEZONE = 'UTC';
const LOADING = '<a:308215loading:1542993472749969489>';
const TICK = '<:tick:1533064242280796200>';
const CROSS = '<:x:1533064240661794866>';
// Game Variety tiers (number of different games)
const VARIETY_TIERS = [
{ level: 1, name: 'Experimenter', games: 2 },
{ level: 2, name: 'Excursionist', games: 5 },
{ level: 3, name: 'Enthusiast', games: 10 },
{ level: 4, name: 'Ranger', games: 15 },
{ level: 5, name: 'Explorer', games: 20 },
{ level: 6, name: 'Adventurer', games: 30 },
{ level: 7, name: 'Navigator', games: 40 },
{ level: 8, name: 'Globetrotter', games: 60 },
{ level: 9, name: 'Polymath', games: 80 },
{ level: 10, name: 'Universalist', games: 100 },
];
// Game Time tiers (hours played)
const TIME_TIERS = [
{ level: 1, name: 'Casual', hours: 1 },
{ level: 2, name: 'Recreational', hours: 5 },
{ level: 3, name: 'Dedicated', hours: 20 },
{ level: 4, name: 'Committed', hours: 75 },
{ level: 5, name: 'Serious', hours: 150 },
{ level: 6, name: 'Devoted', hours: 300 },
{ level: 7, name: 'Veteran', hours: 500 },
{ level: 8, name: 'Staunch', hours: 1000 },
{ level: 9, name: 'Unshakeable', hours: 2000 },
{ level: 10, name: 'Eternal', hours: 5000 },
];
// ── Utilities ──────────────────────────────────────────────────────────────────
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function httpsRequest(hostname, path, method, headers, body = null) {
return new Promise((resolve) => {
const bodyStr = body ? (typeof body === 'string' ? body : JSON.stringify(body)) : null;
const options = {
hostname,
path,
method,
headers: {
...headers,
...(bodyStr ? { 'content-length': Buffer.byteLength(bodyStr) } : {}),
},
};
const req = https.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString();
let data = null;
try { data = JSON.parse(raw); } catch { data = raw; }
resolve({ status: res.statusCode, data });
});
});
req.on('error', (err) => resolve({ status: 0, data: { message: err?.message || 'Request failed' } }));
if (bodyStr) req.write(bodyStr);
req.end();
});
}
function httpsGet(url) {
return new Promise((resolve, reject) => {
https.get(url, { headers: { 'user-agent': 'Mozilla/5.0' } }, (res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch (e) {
reject(e);
}
});
}).on('error', reject);
});
}
// ── Super Properties ────────────────────────────────────────────────────────────
const DESKTOP_CLIENT_VERSION = '1.0.9253';
const DESKTOP_BUILD_NUMBER = 594031;
const NATIVE_BUILD_NUMBER = 88414;
const PLATFORM_OS_VERSION = '10.0.26200';
const BROWSER_VERSION = '42.7.1';
function localFallbackProps() {
return {
os: 'Windows',
browser: 'Discord Client',
release_channel: 'stable',
client_version: DESKTOP_CLIENT_VERSION,
os_version: PLATFORM_OS_VERSION,
os_arch: 'x64',
app_arch: 'x64',
system_locale: 'en-US',
has_client_mods: false,
browser_user_agent: USER_AGENT,
browser_version: BROWSER_VERSION,
os_sdk_version: '26200',
client_build_number: DESKTOP_BUILD_NUMBER,
native_build_number: NATIVE_BUILD_NUMBER,
client_event_source: null,
client_app_state: 'focused',
};
}
async function buildSuperProperties(launchSignature, heartbeatSessionId) {
let props;
try {
const res = await httpsRequest('cordapi.dolfi.es', '/api/v2/properties/windows', 'POST',
{ 'content-type': 'application/json', 'user-agent': USER_AGENT }, '{}');
if (res.status === 200 && res.data?.properties) {
props = res.data.properties;
} else {
props = localFallbackProps();
}
} catch {
props = localFallbackProps();
}
props.client_launch_id = crypto.randomUUID();
props.launch_signature = launchSignature;
props.client_heartbeat_session_id = heartbeatSessionId;
return Buffer.from(JSON.stringify(props)).toString('base64');
}
// ── Fetch Game Catalog ──────────────────────────────────────────────────────────
async function fetchGameCatalog() {
const payload = await httpsGet(CATALOG_URL);
const catalog = [];
const seenIds = new Set();
for (const item of payload) {
const id = String(item.id || '');
if (!id || !/^\d+$/.test(id) || seenIds.has(id)) continue;
// Must have a Windows executable
const exes = item.executables || [];
const winExe = exes.find((e) => e.os === 'win32' && e.name);
if (!winExe) continue;
seenIds.add(id);
catalog.push({
id,
name: item.name || 'Unknown Game',
exe: winExe.name,
});
}
return catalog;
}
// ── Analytics Token ─────────────────────────────────────────────────────────────
async function getAnalyticsToken(userToken, superProps) {
const res = await httpsRequest('discord.com', IDENTITY_URL, 'GET', {
authorization: userToken,
'user-agent': USER_AGENT,
'x-super-properties': superProps,
});
if (res.status === 401) {
throw new Error('UNAUTHORIZED');
}
if (res.status >= 400 || !res.data?.analytics_token) {
throw new Error(`Failed to obtain analytics_token (status ${res.status})`);
}
return res.data.analytics_token;
}
// ── Fetch Cookie ────────────────────────────────────────────────────────────────
// Fetches base Discord cookies (GET /app) — returns __dcfduid, __sdcfduid, __cfruid.
// Cloudflare's cf_clearance is NOT returned on this route (requires JS challenge in browser),
// so it needs to be provided by the user if necessary.
async function fetchBaseCookie() {
return new Promise((resolve) => {
const req = https.request({
hostname: 'discord.com',
path: '/app',
method: 'GET',
headers: {
'user-agent': USER_AGENT,
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-US,en;q=0.9',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
},
}, (res) => {
const setCookies = res.headers['set-cookie'] || [];
const pairs = setCookies.map((c) => c.split(';')[0].trim()).filter((p) => p.includes('='));
res.resume();
res.on('end', () => resolve(pairs.join('; ')));
});
req.on('error', () => resolve(''));
req.end();
});
}
// Merges base Discord cookies with an extra cookie from the user (e.g., cf_clearance).
// The extra cookie takes priority (overwrites duplicate keys).
function mergeCookies(baseCookie, extraCookie) {
if (!extraCookie) return baseCookie || '';
if (!baseCookie) return extraCookie;
const cookieMap = new Map();
// Parse base cookies
for (const pair of baseCookie.split(';')) {
const trimmed = pair.trim();
const eqIdx = trimmed.indexOf('=');
if (eqIdx > 0) cookieMap.set(trimmed.substring(0, eqIdx).trim(), trimmed);
}
// Parse extra cookies (overwrite)
for (const pair of extraCookie.split(';')) {
const trimmed = pair.trim();
const eqIdx = trimmed.indexOf('=');
if (eqIdx > 0) cookieMap.set(trimmed.substring(0, eqIdx).trim(), trimmed);
}
return Array.from(cookieMap.values()).join('; ');
}
// ── Telemetry Event Fabricator ──────────────────────────────────────────────────
class TelemetryFabricator {
constructor(heartbeatSessionId, launchSignature) {
this.heartbeatSessionId = heartbeatSessionId;
this.launchSignature = launchSignature;
this.sequenceIndex = 0;
}
nextSequence() {
return ++this.sequenceIndex;
}
buildLaunchEvent(game) {
const now = Date.now();
return {
type: 'launch_game',
properties: {
client_track_timestamp: now,
client_heartbeat_session_id: this.heartbeatSessionId,
event_sequence_number: this.nextSequence(),
game: game.name,
game_id: game.id,
verified: true,
elevated: false,
is_launcher: false,
game_platform: 'desktop',
detection_method: 'verified_game',
is_overlay_enabled: false,
is_overlay_game_enabled: true,
is_overlay_game_source: 'OOP_DEFAULT_DATABASE',
fullscreen_type: 'UNKNOWN',
hardware_display_count: 1,
overlay_method: 'Disabled',
activity_status_enabled: true,
activity_status_shared_guilds: [],
current_user_status: 'online',
game_detection_enabled: true,
executable_path: game.exe,
voice_channel_id: null,
voice_channel_type: null,
voice_channel_bitrate: null,
voice_channel_guild_id: null,
hidden_by_distributor: false,
game_metadata: null,
client_performance_cpu: null,
client_performance_memory: null,
cpu_core_count: null,
accessibility_features: 0,
rendered_locale: CLIENT_LOCALE,
launch_signature: this.launchSignature,
client_rtc_state: null,
client_app_state: 'focused',
client_send_timestamp: now,
},
};
}
buildHeartbeatEvent(game, durationMs, sessionId, isInitial, isFinal, eventTimeMs = null) {
const ts = eventTimeMs || Date.now();
return {
type: 'running_game_heartbeat',
properties: {
client_track_timestamp: ts,
client_heartbeat_session_id: this.heartbeatSessionId,
event_sequence_number: this.nextSequence(),
game_id: game.id,
game_name: game.name,
game_metadata: null,
game_executable: game.exe,
game_detection_enabled: true,
initial_heartbeat: isInitial,
final_heartbeat: isFinal,
game_session_id: sessionId,
duration_tracked_ms: durationMs,
rtc_connection_id: null,
media_session_id: null,
launch_signature: this.launchSignature,
client_app_state: 'focused',
client_send_timestamp: ts,
},
};
}
buildCompleteSession(game, durationMs, timeOffset = 0) {
const sessionId = crypto.randomUUID();
const now = Date.now() - timeOffset;
const origin = Math.max(0, now - durationMs);
return [
this.buildHeartbeatEvent(game, 0, sessionId, true, false, origin),
this.buildLaunchEvent(game),
this.buildHeartbeatEvent(game, durationMs, sessionId, false, true, now),
];
}
}
// ── Post Telemetry Batch ────────────────────────────────────────────────────────
async function postTelemetryBatch(analyticsToken, userToken, cookie, superProps, events) {
const envelope = { token: analyticsToken, events };
const headers = {
accept: '*/*',
'accept-language': CLIENT_LOCALE,
authorization: userToken,
'content-type': 'application/json',
cookie: cookie || '',
origin: 'https://discord.com',
referer: 'https://discord.com/channels/@me',
'user-agent': USER_AGENT,
'x-debug-options': 'bugReporterEnabled',
'x-discord-locale': CLIENT_LOCALE,
'x-discord-timezone': CLIENT_TIMEZONE,
'x-super-properties': superProps,
};
const res = await httpsRequest('discord.com', TELEMETRY_URL, 'POST', headers, envelope);
return res.status;
}
// ── Build DM Progress Message ───────────────────────────────────────────────────
function buildVarietyProgress(currentGameCount, totalGames, tiers) {
let text = `## ${LOADING} Game Variety — Progress\n\n`;
for (const tier of tiers) {
if (currentGameCount >= tier.games) {
text += `${TICK} **${tier.name}** — ${tier.games} games ✔\n`;
} else if (currentGameCount > 0 && currentGameCount < tier.games) {
text += `${LOADING} **${tier.name}** — ${tier.games} games (${currentGameCount}/${tier.games})\n`;
} else {
text += `⬛ **${tier.name}** — ${tier.games} games\n`;
}
}
text += `\n> Sending ${currentGameCount}/${totalGames} games...`;
text += `\n\n*Badge progress usually syncs within 24 to 48 hours.*`;
return text;
}
function buildTimeProgress(currentHours, tiers, totalTargetHours = 5000) {
let text = `## ${LOADING} Game Time — Progress\n\n`;
for (const tier of tiers) {
if (currentHours >= tier.hours) {
text += `${TICK} **${tier.name}** — ${tier.hours} hours ✔\n`;
} else if (currentHours > 0 && currentHours < tier.hours) {
text += `${LOADING} **${tier.name}** — ${tier.hours} hours (${currentHours.toFixed(0)}/${tier.hours}h)\n`;
} else {
text += `⬛ **${tier.name}** — ${tier.hours} hours\n`;
}
}
text += `\n> Sending ${currentHours.toFixed(0)}/${totalTargetHours} hours...`;
text += `\n\n*Badge progress usually syncs within 24 to 48 hours.*`;
return text;
}
function buildFinalMessage(type, success, error = null) {
if (success) {
return `## ${TICK} ${type} — Completed!\n\nAll tiers were processed successfully.\n\n*Badge progress usually syncs within 24 to 48 hours.*`;
}
return `## ${CROSS} ${type} — Error\n\n> ${error || 'Unknown error.'}`;
}
// ── Run Game Variety ────────────────────────────────────────────────────────────
async function runGameVariety(userToken, discordUser, extraCookie) {
let dmMessage = null;
try {
dmMessage = await discordUser.send({
content: `## ${LOADING} Game Variety — Starting...\n\n> Loading game catalog and preparing session...`,
});
} catch {
console.error('[GameVariety] DM closed.');
return;
}
try {
// 1. Load catalog
const catalog = await fetchGameCatalog();
if (!catalog.length) throw new Error('Game catalog is empty.');
// 2. Prepare session
const heartbeatSessionId = crypto.randomUUID();
const launchSignature = crypto.randomUUID();
const superProps = await buildSuperProperties(launchSignature, heartbeatSessionId);
const analyticsToken = await getAnalyticsToken(userToken, superProps);
const baseCookie = await fetchBaseCookie();
const cookie = mergeCookies(baseCookie, extraCookie);
const fabricator = new TelemetryFabricator(heartbeatSessionId, launchSignature);
// 3. For variety: send 100+ different games with 1h each
const targetGames = Math.min(catalog.length, 110);
const hoursPerGame = 1;
const durationMs = hoursPerGame * 60 * 60 * 1000;
// Shuffle catalog
const shuffled = [...catalog].sort(() => Math.random() - 0.5).slice(0, targetGames);
let processed = 0;
let failed = 0;
// Process in batches (each game generates 3 events, so ~16 games per batch of 50)
const gamesPerBatch = Math.floor(BATCH_LIMIT / 3);
for (let i = 0; i < shuffled.length; i += gamesPerBatch) {
const chunk = shuffled.slice(i, i + gamesPerBatch);
const events = [];
for (let j = 0; j < chunk.length; j++) {
const game = chunk[j];
// Space timestamps to simulate separate sessions
const timeOffset = (i + j) * durationMs;
events.push(...fabricator.buildCompleteSession(game, durationMs, timeOffset));
}
const status = await postTelemetryBatch(analyticsToken, userToken, cookie, superProps, events);
if (status === 204) {
processed += chunk.length;
} else if (status === 401 || status === 403) {
throw new Error(`Authentication failed (HTTP ${status}). Token or cookie expired.`);
} else {
failed += chunk.length;
console.warn(`[GameVariety] Batch failed with status ${status}`);
}
// Update DM
try {
if (dmMessage) {
await dmMessage.edit({ content: buildVarietyProgress(processed, targetGames, VARIETY_TIERS) });
}
} catch { /* ignore */ }
await sleep(NETWORK_COOLDOWN_MS);
}
// Final message
const finalText = failed === 0
? buildFinalMessage('Game Variety', true)
: `## ${TICK} Game Variety — Partially completed\n\n> ${processed} games sent, ${failed} failed.\n\n*Badge progress usually syncs within 24 to 48 hours.*`;
try {
if (dmMessage) await dmMessage.edit({ content: finalText });
} catch { /* ignore */ }
} catch (err) {
console.error('[GameVariety] Error:', err);
if (err.message === 'UNAUTHORIZED' || err.message?.includes('401')) {
const authGuard = require('../services/authGuard');
authGuard.handleUnauthorized(discordUser.id);
try {
if (dmMessage) {
await dmMessage.edit({
content: `## ${CROSS} Game Variety — Session Expired\n\n> Your session expired or the token is no longer valid.\n> Please go to the panel in the server and **Login** again to continue.`,
});
}
} catch { /* ignore */ }
return;
}
try {
if (dmMessage) {
await dmMessage.edit({ content: buildFinalMessage('Game Variety', false, err.message) });
}
} catch { /* ignore */ }
}
}
// ── Run Game Time ───────────────────────────────────────────────────────────────
async function runGameTime(userToken, discordUser, extraCookie) {
let dmMessage = null;
try {
dmMessage = await discordUser.send({
content: `## ${LOADING} Game Time — Starting...\n\n> Loading game catalog and preparing session...`,
});
} catch {
console.error('[GameTime] DM closed.');
return;
}
try {
// 1. Load catalog
const catalog = await fetchGameCatalog();
if (!catalog.length) throw new Error('Game catalog is empty.');
// 2. Prepare session
const heartbeatSessionId = crypto.randomUUID();
const launchSignature = crypto.randomUUID();
const superProps = await buildSuperProperties(launchSignature, heartbeatSessionId);
const analyticsToken = await getAnalyticsToken(userToken, superProps);
const baseCookie = await fetchBaseCookie();
const cookie = mergeCookies(baseCookie, extraCookie);
const fabricator = new TelemetryFabricator(heartbeatSessionId, launchSignature);
// 3. Strategy: 100 games × 50h each = 5,000h total (Tier 10 Eternal)
// Sends each game with spaced timestamps to simulate separate sessions.
// 50h per session stays within Discord's telemetry window (~48h).
const targetGames = Math.min(catalog.length, 100);
const hoursPerGame = 50;
const durationMs = hoursPerGame * 60 * 60 * 1000;
const totalTargetHours = targetGames * hoursPerGame;
// Shuffle catalog for variety
const shuffled = [...catalog].sort(() => Math.random() - 0.5).slice(0, targetGames);
let processedHours = 0;
let failed = 0;
// Process each game individually for better acceptance
// Each game generates 3 events, sends one batch per game for unique timestamps
const gamesPerBatch = Math.floor(BATCH_LIMIT / 3);
for (let i = 0; i < shuffled.length; i += gamesPerBatch) {
const chunk = shuffled.slice(i, i + gamesPerBatch);
const events = [];
for (let j = 0; j < chunk.length; j++) {
const game = chunk[j];
// No timeOffset — timestamps must stay within the current time window
// for Discord to accept and count the hours properly.
events.push(...fabricator.buildCompleteSession(game, durationMs, 0));
}
const status = await postTelemetryBatch(analyticsToken, userToken, cookie, superProps, events);
if (status === 204) {
processedHours += chunk.length * hoursPerGame;
} else if (status === 401 || status === 403) {
throw new Error(`Authentication failed (HTTP ${status}). Token or cookie expired.`);
} else {
failed += chunk.length;
console.warn(`[GameTime] Batch failed with status ${status}`);
}
// Update DM
try {
if (dmMessage) {
await dmMessage.edit({ content: buildTimeProgress(processedHours, TIME_TIERS, totalTargetHours) });
}
} catch { /* ignore */ }
await sleep(NETWORK_COOLDOWN_MS);
}
// Final message
const finalText = failed === 0
? buildFinalMessage('Game Time', true)
: `## ${TICK} Game Time — Partially completed\n\n> ${processedHours}h sent (${targetGames - failed}/${targetGames} games processed).\n\n*Badge progress usually syncs within 24 to 48 hours.*`;
try {
if (dmMessage) {
await dmMessage.edit({ content: finalText });
}
} catch { /* ignore */ }
} catch (err) {
console.error('[GameTime] Error:', err);
if (err.message === 'UNAUTHORIZED' || err.message?.includes('401')) {
const authGuard = require('../services/authGuard');
authGuard.handleUnauthorized(discordUser.id);
try {
if (dmMessage) {
await dmMessage.edit({
content: `## ${CROSS} Game Time — Session Expired\n\n> Your session expired or the token is no longer valid.\n> Please go to the panel in the server and **Login** again to continue.`,
});
}
} catch { /* ignore */ }
return;
}
try {
if (dmMessage) {
await dmMessage.edit({ content: buildFinalMessage('Game Time', false, err.message) });
}
} catch { /* ignore */ }
}
}
module.exports = { runGameVariety, runGameTime, VARIETY_TIERS, TIME_TIERS };
```[cite: 1]