Help desk in Telegram: @CTBTickets_bot pings with Close/Waiting/High/Open buttons, reply to a ping to answer (/note = internal), /tickets and /t <ref>; secret-header webhook, only Marty's private chat is obeyed; old one-way ping stays as fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+102
@@ -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 ? '\n<i>Reply to this message to answer. Start with /note for an internal note.</i>' : '';
|
||||
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('<b>' + t.ref + '</b> · ' + 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('<b>' + t.ref + '</b> · ' + STATUS_WORD[t.status] + ' · ' + escH(t.platform) + ' · ' + escH(t.category) + '\n' + escH(t.email) + '\n<b>' + escH(t.subject) + '</b>\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 <b>' + t.ref + '</b>.' : '✅ Sent to ' + escH(t.email) + ' on <b>' + t.ref + '</b> (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 };
|
||||
Reference in New Issue
Block a user