From 6f6412d908cfa8037508dbee94d6d0ad59db5db5 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 16 Oct 2026 16:56:54 -0500 Subject: [PATCH] Help desk in Telegram: @CTBTickets_bot pings with Close/Waiting/High/Open buttons, reply to a ping to answer (/note = internal), /tickets and /t ; secret-header webhook, only Marty's private chat is obeyed; old one-way ping stays as fallback Co-Authored-By: Claude Opus 5.5 --- server.js | 15 +++++++- supportbot.js | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++ tickets.js | 2 +- 3 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 supportbot.js diff --git a/server.js b/server.js index 621873d..70035f0 100644 --- a/server.js +++ b/server.js @@ -59,6 +59,7 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S const refill = require('./refill'); const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16) const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16) const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) @@ -532,6 +533,7 @@ async function boot() { coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram }); + supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' }); badge.init({ publicDir: PUBLIC_DIR }); gamestats.init({ dataDir: DATA_DIR }); snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT())).map(g => g.name), @@ -996,7 +998,9 @@ function tgSendAs(token, chatId, text, threadId) { } // Help desk pings (2026-10-16): Marty's PRIVATE Telegram chat only, never a group, topic or feed. tgSendAs skips the // Discord relay entirely. Site bot (telegramBotToken) first, Marty's Hermes bot if that one cannot reach him. -async function supportTelegram(text) { +async function supportTelegram(text, ref) { + // the dedicated support bot (two-way: buttons + replies) goes first; the old one-way path stays as the fallback + if (supportbot.enabled() && await supportbot.ping(text, ref)) return true; const sc = siteConfig(); const chat = String(sc.supportTelegramChat || '1289244227').trim(); if (!/^\d{4,15}$/.test(chat)) { console.error('support ping refused: supportTelegramChat must be a private chat id (positive number), not', chat); return false; } @@ -2097,6 +2101,11 @@ const server = http.createServer(async (req, res) => { } // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off + if (p === '/api/telegram/support' && req.method === 'POST') { // the support bot's webhook: secret header checked inside, always 200 + let b = {}; try { b = await readBody(req); } catch (e) {} + try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); } + return json(res, 200, { ok: true }); + } if (p === '/api/support' && req.method === 'POST') { const b = await readBody(req); const s = await auth.fromRequest(req); @@ -4540,6 +4549,10 @@ const server = http.createServer(async (req, res) => { return json(res, 200, { admin: true, email: ADMIN_EMAIL }); } // -- help desk, admin side (2026-10-16): the Support pane + if (p === '/api/admin/support/telegram/register' && req.method === 'POST') { // point @CTBTickets_bot's webhook at this server + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await supportbot.register('https://instantadpay.com/api/telegram/support')); + } if (p === '/api/admin/support' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(await tickets.adminList({ status: u.searchParams.get('status'), platform: u.searchParams.get('platform'), category: u.searchParams.get('category'), q: u.searchParams.get('q') }), diff --git a/supportbot.js b/supportbot.js new file mode 100644 index 0000000..e5369fe --- /dev/null +++ b/supportbot.js @@ -0,0 +1,102 @@ +// Help desk in Telegram (Marty, 2026-10-16): @CTBTickets_bot pings Marty's PRIVATE chat for every new ticket and member +// reply, with buttons (Close, Waiting, High, Open in admin), and takes his answers back: reply to a ticket message and +// the text goes to the requester exactly as an admin reply would; start it with /note to keep it internal. /tickets +// lists what is open, /t IAP-1042 shows a thread. Updates arrive on a webhook guarded by a secret header, and only +// the configured private chat is obeyed. Token: env SUPPORT_BOT_TOKEN; webhook secret: env SUPPORT_TG_SECRET. +'use strict'; +const https = require('https'); + +let deps = null; // { tickets, chatId: () => string, site } +const token = () => String(process.env.SUPPORT_BOT_TOKEN || '').trim(); +const secret = () => String(process.env.SUPPORT_TG_SECRET || '').trim(); +function init(d) { deps = d; } +const enabled = () => !!token(); + +function api(method, payload) { + return new Promise(resolve => { + const body = JSON.stringify(payload); + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + token() + '/' + method, method: 'POST', timeout: 12000, + headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, + r => { let d = ''; r.on('data', c => { d += c; }); r.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { resolve({ ok: false }); } }); }); + rq.on('error', () => resolve({ ok: false })); + rq.on('timeout', () => { rq.destroy(); resolve({ ok: false }); }); + rq.end(body); + }); +} +const escH = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +const adminUrl = ref => (deps.site || 'https://instantadpay.com') + '/admin#support?t=' + ref; +const keyboard = ref => ({ inline_keyboard: [ + [{ text: 'Close', callback_data: 'tk|' + ref + '|closed' }, { text: 'Waiting', callback_data: 'tk|' + ref + '|waiting_on_member' }, { text: 'High', callback_data: 'tk|' + ref + '|high' }], + [{ text: 'Open in admin', url: adminUrl(ref) }]] }); +const say = (text, extra) => api('sendMessage', Object.assign({ chat_id: deps.chatId(), text, parse_mode: 'HTML', disable_web_page_preview: true }, extra || {})); + +// the ticket ping: same text the desk builds, plus buttons and a hint; true when Telegram accepted it +async function ping(text, ref) { + if (!enabled()) return false; + const tail = ref ? '\nReply to this message to answer. Start with /note for an internal note.' : ''; + const r = await say(text + tail, ref ? { reply_markup: keyboard(ref) } : {}); + return !!(r && r.ok); +} + +const REF_RE = /\b((?:IAP|LS)-\d{4,9})\b/; +const STATUS_WORD = { open: 'open', waiting_on_member: 'waiting on member', closed: 'closed' }; +async function listOpen() { + const out = []; + for (const st of ['open', 'waiting_on_member']) { + const r = await deps.tickets.adminList({ status: st }); + for (const t of (r.tickets || []).slice(0, 15)) out.push('' + t.ref + ' · ' + STATUS_WORD[t.status] + (t.priority === 'high' ? ' · high' : '') + '\n' + escH(t.subject)); + } + return out.length ? out.join('\n\n') : 'No open tickets.'; +} +async function showThread(ref) { + const t = await deps.tickets.byRef(ref); if (!t) return say('No ticket ' + escH(ref) + '.'); + const v = await deps.tickets.adminView(t.id); + const msgs = (v.messages || []).slice(-6).map(m => (m.internal ? '📝 note' : m.author === 'admin' ? '↩️ you' : '👤 ' + escH(t.name || t.email)) + ': ' + escH(String(m.body).slice(0, 500))); + return say('' + t.ref + ' · ' + STATUS_WORD[t.status] + ' · ' + escH(t.platform) + ' · ' + escH(t.category) + '\n' + escH(t.email) + '\n' + escH(t.subject) + '\n\n' + msgs.join('\n\n'), { reply_markup: keyboard(t.ref) }); +} + +// webhook: returns nothing; the caller always answers 200 so Telegram does not retry forever +async function handle(req, update) { + if (!enabled() || !secret() || req.headers['x-telegram-bot-api-secret-token'] !== secret()) return 'denied'; + const me = String(deps.chatId()); + const cq = update.callback_query; + if (cq) { + if (String(cq.from && cq.from.id) !== me) return 'ignored'; + const [kind, ref, action] = String(cq.data || '').split('|'); + let note = 'Done'; + if (kind === 'tk' && REF_RE.test(ref || '')) { + const t = await deps.tickets.byRef(ref); + if (!t) note = 'No such ticket'; + else { + const r = await deps.tickets.setFields(t.id, action === 'high' ? { priority: 'high' } : { status: action }); + note = r.error ? r.error : ref + (action === 'high' ? ' marked high priority' : ' is now ' + (STATUS_WORD[action] || action)); + } + } + await api('answerCallbackQuery', { callback_query_id: cq.id, text: note }); + return 'callback'; + } + const msg = update.message; + if (!msg || String(msg.chat && msg.chat.id) !== me || String(msg.from && msg.from.id) !== me) return 'ignored'; + const text = String(msg.text || '').trim(); if (!text) return 'empty'; + if (/^\/start\b/.test(text)) return say('Support desk connected. New tickets and member replies land here.\nReply to a ticket message to answer it, start with /note for an internal note.\n/tickets lists what is open, /t IAP-1042 shows a thread.'); + if (/^\/tickets\b/.test(text)) return say(await listOpen()); + const tm = /^\/t\s+((?:IAP|LS)-\d{4,9})/i.exec(text); + if (tm) return showThread(tm[1].toUpperCase()); + const replied = msg.reply_to_message && (msg.reply_to_message.text || msg.reply_to_message.caption || ''); + const rm = replied && REF_RE.exec(replied); + if (!rm) return say('Reply to a ticket message to answer it, or use /tickets.'); + const t = await deps.tickets.byRef(rm[1]); if (!t) return say('No ticket ' + escH(rm[1]) + '.'); + const internal = /^\/note\b/i.test(text); + const body = internal ? text.replace(/^\/note\b\s*/i, '') : text; + if (!body) return say('Write the note after /note.'); + const r = await deps.tickets.addMessage(t.id, { author: 'admin', body, internal, via: 'telegram' }); + if (r.error) return say('Not sent: ' + escH(r.error)); + return say(internal ? '📝 Note saved on ' + t.ref + '.' : '✅ Sent to ' + escH(t.email) + ' on ' + t.ref + ' (now waiting on member).', { reply_to_message_id: msg.message_id }); +} + +// point Telegram at our webhook (run once after deploy, and again if the URL or secret changes) +async function register(url) { + if (!enabled() || !secret()) return { ok: false, error: 'SUPPORT_BOT_TOKEN and SUPPORT_TG_SECRET must both be set' }; + return api('setWebhook', { url, secret_token: secret(), allowed_updates: ['message', 'callback_query'], drop_pending_updates: true }); +} +module.exports = { init, enabled, ping, handle, register }; diff --git a/tickets.js b/tickets.js index 4b599e8..0b47741 100644 --- a/tickets.js +++ b/tickets.js @@ -176,7 +176,7 @@ function pingAdmin(kind, t, m) { if (newPings.skipped) { extra = '\n(+' + newPings.skipped + ' more new tickets earlier were not pinged)'; newPings.skipped = 0; } } const text = head + ' · ' + t.platform + ' · ' + escH(t.category) + '\n' + escH(who(t)) + '\n' + escH(t.subject) + '\n“' + escH(firstLine(last.body)) + '”\n' + adminLink(t) + extra; - if (deps.telegram) deps.telegram(text).catch(() => {}); + if (deps.telegram) deps.telegram(text, t.ref).catch(() => {}); if (deps.adminEmail && deps.mailer && deps.mailer.hasKey()) { const body = items.map(i => i.body).join('\n\n---\n\n'); deps.mailer.send(deps.adminEmail, '[' + t.ref + '] ' + (kind === 'new' ? 'New ticket: ' : 'Reply: ') + t.subject,