// discord-relay.cjs — mirror a Telegram group post into the Crypto Team Build Discord (relaunch 2026-10-09). // Drop-in for every app that posts with the shared CTB Rewards bot. Call mirror() right where the app calls // Telegram; it is fire-and-forget, never throws, and does nothing unless the DISCORD_WEBHOOK_* env is set. // mirror({ chatId, threadId, text, photo, buttons }) // chatId the Telegram chat the post goes to. Only the community group is mirrored; DMs / alert chats are skipped. // threadId forum topic: achievements (661565) -> #achievements, payments (632242) -> #payment-proofs, // no topic (General) -> #achievements. Override with DISCORD_TOPIC_ACH / DISCORD_TOPIC_PAY. // text Telegram HTML (converted to Discord markdown; user text is escaped so names with _ don't italicise) // photo Buffer (uploaded) or a public image URL (embedded), optional // buttons Telegram inline_keyboard (url buttons become links under the text), optional // Env: DISCORD_WEBHOOK_ACHIEVEMENTS, DISCORD_WEBHOOK_PAYMENT_PROOFS, DISCORD_WEBHOOK_PROMOS, DISCORD_WEBHOOK_ANNOUNCEMENTS, // DISCORD_WEBHOOK_OPS; DISCORD_TG_GROUP (default -1001258691510); DISCORD_RELAY=off to disable. // The same post twice within 15 minutes (e.g. a badge sent to a topic AND to General) is mirrored once. 'use strict'; const crypto = require('node:crypto'); const GROUP = () => String(process.env.DISCORD_TG_GROUP || '-1001258691510'); const TOPIC_ACH = () => String(process.env.DISCORD_TOPIC_ACH || '661565'); const TOPIC_PAY = () => String(process.env.DISCORD_TOPIC_PAY || '632242'); const HOOKS = { achievements: 'DISCORD_WEBHOOK_ACHIEVEMENTS', 'payment-proofs': 'DISCORD_WEBHOOK_PAYMENT_PROOFS', promos: 'DISCORD_WEBHOOK_PROMOS', announcements: 'DISCORD_WEBHOOK_ANNOUNCEMENTS', ops: 'DISCORD_WEBHOOK_OPS' }; function hookFor(feed) { const v = String(process.env[HOOKS[feed]] || ''); return v.startsWith('https://discord.com/api/webhooks/') ? v : ''; } function feedFor(threadId) { const t = String(threadId == null ? '' : threadId); if (t === TOPIC_PAY()) return 'payment-proofs'; if (t === TOPIC_ACH()) return 'achievements'; return 'achievements'; } // ---- Telegram HTML -> Discord markdown ---- const ENT = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'", ''': "'", ' ': ' ' }; const unesc = s => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, m => ENT[m] || m); const escMd = s => s.replace(/([\\*_~`|])/g, '\\$1').replace(/^(\s*)([>#-])/gm, '$1\\$2'); const WRAP = { b: '**', strong: '**', i: '*', em: '*', u: '__', ins: '__', s: '~~', strike: '~~', del: '~~', code: '`', 'tg-spoiler': '||', spoiler: '||' }; function htmlToMd(html) { const re = /<\/?([a-zA-Z-]+)(?:\s+[^>]*)?\/?>/g; const stack = []; let out = '', last = 0, inCode = 0, m; const emit = t => { if (!t) return; const u = unesc(t); out += inCode ? u : escMd(u); }; const close = mk => { const ws = (/\s+$/.exec(out) || [''])[0]; out = out.slice(0, out.length - ws.length) + mk + ws; }; while ((m = re.exec(html))) { emit(html.slice(last, m.index)); last = re.lastIndex; const raw = m[0], tag = m[1].toLowerCase(); if (tag === 'br') { out += '\n'; continue; } if (!raw.startsWith('= 0 && stack[i].tag !== tag) i--; if (i < 0) continue; const o = stack[i]; stack.length = i; if (tag === 'a') { const inner = out.slice(o.start); out = out.slice(0, o.start) + (o.href ? '[' + inner + '](' + o.href + ')' : inner); } else if (tag === 'pre') { out += '\n```'; inCode--; } else if (WRAP[tag]) { if (tag === 'code') inCode--; close(WRAP[tag]); } } } emit(html.slice(last)); return out.replace(/\n{3,}/g, '\n\n').trim(); } // ---- sending: one queue per webhook, 1.2 s apart, 429 honoured ---- const queues = new Map(); const seen = new Map(); const sleep = ms => new Promise(r => setTimeout(r, ms)); function content(text, buttons) { let c = htmlToMd(String(text || '')); const links = []; try { for (const row of (buttons && buttons.inline_keyboard) || []) for (const b of row) if (b && b.url) links.push('[' + String(b.text || 'Open').replace(/[\[\]]/g, '') + '](' + b.url + ')'); } catch (e) {} if (links.length) c += '\n\n' + links.join(' · '); return c.length > 1990 ? c.slice(0, 1989) + '…' : c; } async function post(url, msg, attempt) { const payload = { content: content(msg.text, msg.buttons), allowed_mentions: { parse: [] } }; let body, headers = {}; if (msg.photo && typeof msg.photo !== 'string') { payload.attachments = [{ id: 0, filename: 'card.jpg' }]; const fd = new FormData(); fd.append('payload_json', JSON.stringify(payload)); fd.append('files[0]', new Blob([msg.photo]), 'card.jpg'); body = fd; } else { if (typeof msg.photo === 'string' && msg.photo) payload.embeds = [{ image: { url: msg.photo } }]; else payload.flags = 1 << 2; body = JSON.stringify(payload); headers['Content-Type'] = 'application/json'; } const r = await fetch(url + '?wait=true', { method: 'POST', headers, body, signal: AbortSignal.timeout(20000) }); if (r.status === 429 && (attempt || 0) < 2) { const j = await r.json().catch(() => ({})); await sleep((Number(j.retry_after) || 2) * 1000 + 250); return post(url, msg, (attempt || 0) + 1); } if (!r.ok) console.error('[discord-relay] post failed http=' + r.status + ' ' + (await r.text().catch(() => '')).slice(0, 160)); } function mirror(msg) { try { if (String(process.env.DISCORD_RELAY || 'on').toLowerCase() === 'off') return; if (!msg || String(msg.chatId || '') !== GROUP()) return; const feed = msg.feed || feedFor(msg.threadId); const url = hookFor(feed); if (!url) return; const key = crypto.createHash('sha1').update(feed + '\n' + String(msg.text || '') + '\n' + (Buffer.isBuffer(msg.photo) ? msg.photo.length : String(msg.photo || ''))).digest('hex'); const now = Date.now(); for (const [k, t] of seen) if (now - t > 15 * 60000) seen.delete(k); if (seen.has(key)) return; seen.set(key, now); const prev = queues.get(url) || Promise.resolve(); queues.set(url, prev.then(() => post(url, msg, 0)).catch(e => console.error('[discord-relay]', e && e.message)).then(() => sleep(1200))); } catch (e) { console.error('[discord-relay]', e && e.message); } } module.exports = { mirror, htmlToMd, feedFor };