From fe61842525544fffea469c14152d1ff4e8d43b8b Mon Sep 17 00:00:00 2001 From: Marty Bostick Date: Fri, 9 Oct 2026 13:57:38 +0000 Subject: [PATCH] Mirror Telegram group posts into the Crypto Team Build Discord Discord relaunch 2026-10-09: the shared discord-relay.cjs fans every post that goes to the community group out to the matching Discord channel (achievements topic -> #achievements, payments topic -> #payment-proofs) through DISCORD_WEBHOOK_* webhooks. Telegram HTML is converted to Discord markdown, buttons become links, cards post as images. DMs and alert chats are not mirrored. Fire-and-forget; off when the env is unset. Co-Authored-By: Claude Fable 5.1 --- discord-relay.cjs | 86 +++++++++++++++++++++++++++++++++++++++++++++++ server.js | 2 ++ 2 files changed, 88 insertions(+) create mode 100644 discord-relay.cjs diff --git a/discord-relay.cjs b/discord-relay.cjs new file mode 100644 index 0000000..26284fa --- /dev/null +++ b/discord-relay.cjs @@ -0,0 +1,86 @@ +// 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 }; diff --git a/server.js b/server.js index 9a77336..5ed235b 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,7 @@ // Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'. 'use strict'; const http = require('http'); +const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09) const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); @@ -55,6 +56,7 @@ async function telegramPhoto(file, caption, general, topicOverride) { if (!outbound()) return false; const tok = process.env.DR_TG_TOKEN, chat = process.env.DR_TG_PUBLIC_CHAT || process.env.DR_TG_CHAT, topic = process.env.DR_TG_PUBLIC_CHAT ? (topicOverride || process.env.DR_TG_PUBLIC_TOPIC) : null; if (!tok || !chat || !file) return false; + discordRelay.mirror({ chatId: chat, threadId: topic && !general ? Number(topic) : undefined, text: caption, photo: fs.readFileSync(file) }); try { const fd = new FormData(); fd.append('chat_id', chat); fd.append('caption', caption); fd.append('parse_mode', 'HTML'); if (topic && !general) fd.append('message_thread_id', String(topic)); fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg');