// 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) }]] }); // the persistent button keyboard under the chat (the "menu" Marty works from) + the command list behind the Menu button const MENU = { keyboard: [[{ text: '๐Ÿ“‹ Open tickets' }, { text: 'โณ Waiting on member' }], [{ text: '๐Ÿ”ฅ High priority' }, { text: 'โœ… Recently closed' }], [{ text: 'โ“ Help' }]], resize_keyboard: true, is_persistent: true }; const COMMANDS = [{ command: 'tickets', description: 'Open tickets' }, { command: 'waiting', description: 'Waiting on member' }, { command: 'high', description: 'High priority' }, { command: 'closed', description: 'Recently closed' }, { command: 't', description: 'Show a ticket: /t IAP-1042' }, { command: 'menu', description: 'Show the button menu' }, { command: 'help', description: 'How the desk works' }]; const HELP = 'Tickets land here as they arrive.\n\nโ€ข Reply to a ticket message to answer it (the member gets it by email, and in the dashboard).\nโ€ข Start the reply with /note to keep it internal.\nโ€ข Buttons under a ticket: Close, Waiting, High, Open in admin.\nโ€ข The menu below lists tickets; tap one to open its thread.'; 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 fetchList(which) { const get = async st => ((await deps.tickets.adminList({ status: st })).tickets || []); if (which === 'waiting') return { title: 'โณ Waiting on member', rows: await get('waiting_on_member') }; if (which === 'closed') return { title: 'โœ… Recently closed', rows: (await get('closed')).slice(0, 10) }; const live = (await get('open')).concat(await get('waiting_on_member')); if (which === 'high') return { title: '๐Ÿ”ฅ High priority', rows: live.filter(t => t.priority === 'high') }; return { title: '๐Ÿ“‹ Open tickets', rows: await get('open') }; } // a list = one tappable button per ticket; tapping opens the thread (callback tv|) async function sendList(which) { const { title, rows } = await fetchList(which); if (!rows.length) return say(title + ': none right now.', { reply_markup: MENU }); const shown = rows.slice(0, 20); const buttons = shown.map(t => [{ text: (t.priority === 'high' ? '๐Ÿ”ฅ ' : '') + t.ref + ' ยท ' + String(t.subject).slice(0, 40), callback_data: 'tv|' + t.ref }]); return say('' + title + ' (' + rows.length + ')' + (rows.length > shown.length ? ', newest 20 shown' : '') + '\nTap one to open it.', { reply_markup: { inline_keyboard: buttons } }); } 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('|'); if (kind === 'tv' && REF_RE.test(ref || '')) { await api('answerCallbackQuery', { callback_query_id: cq.id }); await showThread(ref); return 'view'; } 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|menu)\b/.test(text)) return say('Support desk connected. Use the buttons below, or reply to any ticket message to answer it.', { reply_markup: MENU }); if (/^\/help\b/.test(text) || text === 'โ“ Help') return say(HELP, { reply_markup: MENU }); if (/^\/tickets\b/.test(text) || text === '๐Ÿ“‹ Open tickets') return sendList('open'); if (/^\/waiting\b/.test(text) || text === 'โณ Waiting on member') return sendList('waiting'); if (/^\/high\b/.test(text) || text === '๐Ÿ”ฅ High priority') return sendList('high'); if (/^\/closed\b/.test(text) || text === 'โœ… Recently closed') return sendList('closed'); 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('To answer a ticket, reply to its message. Or pick a list below.', { reply_markup: MENU }); 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' }; const hook = await api('setWebhook', { url, secret_token: secret(), allowed_updates: ['message', 'callback_query'], drop_pending_updates: true }); const cmds = await api('setMyCommands', { commands: COMMANDS, scope: { type: 'chat', chat_id: Number(deps.chatId()) } }); return { ok: !!(hook.ok && cmds.ok), webhook: hook.description || hook.ok, commands: !!cmds.ok }; } module.exports = { init, enabled, ping, handle, register };