// Peppa Telegram bot: forwards PM questions (approvals, questions, permissions, session
// alerts) to the paired chat and turns button presses / replies into answers delivered
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
// it can only answer a specific pending question or resume/stop the session it is about.
import {
acceptPairing,
beat,
checkServices,
claimUpdate,
dueOutbox,
enqueueTelegram,
finishUpdate,
listenEvents,
answeredQuestionMessages,
projectForUser,
buildDigest,
deliverToUser,
flushPushOutbox,
projectAudience,
questionEvent,
renderDigest,
type NotifyEvent,
telegramUser,
userProjectIds,
type User,
getOffset,
getIncident,
getQuestion,
getSession,
listSessions,
markOutboxRetry,
markOutboxSent,
pendingQuestions,
questionByTelegramMessage,
setOffset,
setSetting,
createTask,
getGoal,
listGoals,
listUserProjects,
type Project,
type OutboxRow,
type Question,
type SessionView,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts";
/** Longest voice note the bot transcribes (seconds). */
const VOICE_MAX_SEC = 5 * 60;
export interface BotOptions {
db: Db;
api: TelegramApi;
/** Server-side secret for hashing pairing codes (the bot token). */
secret: string;
webUrl: string;
pollTimeoutSec?: number;
outboxIntervalMs?: number;
reconcileIntervalMs?: number;
/** Heartbeat + check on the watchdog and the web (PEP-20). */
heartbeatIntervalMs?: number;
// How often to check PRAGMA data_version for writes the notify() poke missed.
changesIntervalMs?: number;
log?: (msg: string) => void;
}
const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя.
• Кнопки под сообщением — быстрый ответ.
• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию.
• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
• /status — активные сессии и открытые вопросы.
• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
const PUSH_MAX_AGE_MS = 30 * 60_000;
const PUSH_TITLE: Record = {
questions: "Агент ждёт ответа",
review: "Готово к ревью",
failures: "Раннер остановился",
releases: "Релиз",
incidents: "Ошибка в проде",
monitoring: "Мониторинг",
digest: "Сводка",
};
/** Browser notification text for a question. */
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`;
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
return { title, body };
}
export function createBot(o: BotOptions) {
const { db, api } = o;
const log = o.log ?? (() => {});
const abort = new AbortController();
let reconcileQueued = false;
let wakeOutbox: (() => void) | null = null;
// ── questions → outbox ─────────────────────────────────────────────────────────
async function context(q: Question) {
let session: SessionView | null = null;
if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null);
const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : [];
const taskStatus = st?.status ?? null;
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl };
if (q.taskId) {
const [t] = await db
.select({ key: projects.key, number: tasks.number, title: tasks.title })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(eq(tasks.id, q.taskId));
if (t) return { taskKey: formatTaskKey(t.key, t.number), taskTitle: t.title, taskStatus, session: null, webUrl: o.webUrl };
}
return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl };
}
/**
* Makes sure every open question reaches each person of its project by their notification
* settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit.
*/
async function reconcile(): Promise {
const open = await pendingQuestions(db);
const projectsOf = new Map>();
const waitingFor = async (userId: number) => {
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
const ids = projectsOf.get(userId)!;
return open.filter((x) => ids.has(x.projectId)).length;
};
for (const q of open) {
const audience = await projectAudience(db, q.projectId);
if (!audience.length) continue;
const ctx = await context(q);
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
const r = renderQuestion(q, ctx);
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
for (const u of audience) {
await deliverToUser(db, u, {
event,
projectId: q.projectId,
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
pushKey: `q:${q.id}:u${u.id}`,
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
urgency: event === "questions" || event === "failures" ? "high" : "normal",
});
}
}
for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) {
await enqueueTelegram(db, {
dedupeKey: `qa:${q.id}:${sent.params.chat_id}`,
method: "editMessageText",
questionId: q.id,
params: {
chat_id: sent.params.chat_id,
message_id: sent.telegramMessageId,
text: renderAnswered(String(sent.params.text), q),
parse_mode: "HTML",
reply_markup: { inline_keyboard: [] },
},
});
}
wakeOutbox?.();
}
async function projectKey(projectId: number): Promise {
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
return p?.key ?? "";
}
function scheduleReconcile() {
if (reconcileQueued) return;
reconcileQueued = true;
setTimeout(() => {
reconcileQueued = false;
reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`));
}, 150);
}
// ── outbox → Telegram ──────────────────────────────────────────────────────────
async function deliver(row: OutboxRow): Promise {
if (row.method === "sendMessage" && row.questionId) {
// Answered before we got to it (e.g. in the terminal): no point in asking.
const q = await getQuestion(db, row.questionId).catch(() => null);
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
}
try {
const res = await api.call(row.method, row.params);
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
} catch (e) {
if (!(e instanceof TelegramError)) throw e;
if (e.code === 400 && /not modified/i.test(e.description)) return markOutboxSent(db, row, null);
log(`outbox #${row.id} ${row.method}: ${e.message}`);
// 400/403 won't get better by retrying.
if (e.code === 400 || e.code === 403) return markOutboxRetry(db, { ...row, attempts: 99 }, e.message);
await markOutboxRetry(db, row, e.message, e.retryAfter);
}
}
async function flushOutbox(): Promise {
for (const row of await dueOutbox(db)) await deliver(row);
// Browser pushes (PEP-55) go out of the same loop.
await flushPushOutbox(db, { log });
}
// ── Telegram → answers ─────────────────────────────────────────────────────────
async function reply(chatId: number, text: string, replyTo?: number) {
await api.sendMessage(chatId, text, replyTo ? { reply_parameters: { message_id: replyTo } } : {}).catch((e) => log(`reply: ${e.message}`));
}
async function answer(q: Question, text: string): Promise {
const fresh = await getQuestion(db, q.id);
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
scheduleReconcile();
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори.";
}
const canAccess = (user: User, projectId: number) =>
projectForUser(db, user.id, projectId).then(
() => true,
() => false,
);
async function status(user: User): Promise {
const ids = new Set(await userProjectIds(db, user.id));
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
const lines = [`Активные сессии: ${sessions.length}`];
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`);
lines.push("", `Открытых вопросов: ${open.length}`);
return lines.join("\n");
}
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }];
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
/** Send (or, for a button press, edit in place) a bot message with buttons. */
async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
const params = { chat_id: chatId, text, parse_mode: "HTML", reply_markup: { inline_keyboard: buttons }, link_preview_options: { is_disabled: true } };
if (editId) await api.call("editMessageText", { ...params, message_id: editId }).catch((e) => log(`edit: ${(e as Error).message}`));
else await api.call("sendMessage", params).catch((e) => log(`send: ${(e as Error).message}`));
}
async function askProject(d: Draft, projects: Project[], editId?: number) {
// Most recently active first (the latest story touched), then newest projects.
const touched = new Map();
for (const r of await db.select({ projectId: tasks.projectId, at: sql`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
const more = projects.length > 12 ? "\nНет нужного — напиши заново с ключом: «KEY: …»." : "";
await show(d.chatId, `📝 Новая стори ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId);
}
async function askEpic(d: Draft, project: Project, editId?: number) {
const epics = (await listGoals(db, project.id)).slice(0, 10);
const buttons = epics.length
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }]
: [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }];
await show(d.chatId, `📝 Новая стори в ${esc(project.key)}: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId);
}
/** A plain message (or a transcribed voice note) → a draft and the next question. */
async function startStory(user: User, chatId: number, text: string, voice: boolean) {
const projects = await listUserProjects(db, user.id);
if (!projects.length) return reply(chatId, `У тебя пока нет проектов — создай первый: ${esc(o.webUrl)}/projects/new`);
const parsed = parseStoryText(text, projects);
if (!parsed.body) return reply(chatId, "Пустая стори — напиши, что сделать.");
const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
if (project) await askEpic(d, project);
else await askProject(d, projects);
}
async function onVoice(user: User, m: TgMessage) {
const f = m.voice ?? m.audio!;
const cfg = transcribeConfig();
if (!cfg) return reply(m.chat.id, "Голосовые пока не настроены — напиши задачу текстом.", m.message_id);
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) — запиши короче или напиши текстом.`, m.message_id);
let text: string;
try {
const file = await api.getFile(f.file_id);
if (!file.file_path) throw new TranscribeError("Telegram не отдал файл");
const audio = await api.downloadFile(file.file_path);
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
} catch (e) {
log(`voice: ${(e as Error).message}`);
return reply(m.chat.id, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, m.message_id);
}
if (!text) return reply(m.chat.id, "Не разобрал ни слова — попробуй ещё раз или напиши текстом.", m.message_id);
await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id);
await startStory(user, m.chat.id, text, true);
}
/** Buttons of a draft (`d::p:` / `d::g:` / `d::x`) and of a new story (`t::start|keep`). */
async function onStoryButton(user: User, c: TgCallbackQuery, parts: string[]): Promise {
const msgId = c.message?.message_id;
const chatId = c.message!.chat.id;
if (parts[0] === "t") {
const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
if (!t || !(await canAccess(user, t.projectId))) return "Стори не найдена";
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
if (parts[2] === "keep") {
await show(chatId, `${head}\nВ бэклоге.`, [], msgId);
return "Оставил в бэклоге";
}
if (parts[2] !== "start") return "Неизвестная кнопка";
if (t.status !== "backlog") {
await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId);
return `${ref.key} уже ${t.status}`;
}
try {
await moveTask(db, ref, "in_progress");
} catch (e) {
return (e as Error).message;
}
await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId);
return `${ref.key}: агент взялся ▶️`;
}
const d = await loadDraft(db, Number(parts[1]), user.id);
if (!d) {
await show(chatId, "Черновик не найден или устарел — напиши заново.", [], msgId);
return "Черновик устарел";
}
if (parts[2] === "x") {
await dropDraft(db, d.id);
await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId);
return "Отменено";
}
if (parts[2] === "p") {
const projectId = Number(parts[3]);
const project = await projectForUser(db, user.id, projectId).catch(() => null);
if (!project) return "Проект не найден";
await updateDraft(db, { ...d, projectId });
await askEpic(d, project, msgId);
return project.key;
}
if (parts[2] === "g" && d.projectId) {
const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
if (!project) return "Проект не найден";
const goalId = Number(parts[3]) || undefined;
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден";
const { title, rest } = splitStory(d.text);
const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`;
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
await dropDraft(db, d.id);
await show(
chatId,
`📥 Создал ${esc(ref.key)}: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`,
[[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]],
msgId,
);
return `Создал ${ref.key}`;
}
return "Неизвестная кнопка";
}
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
if (b) {
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
scheduleReconcile();
return "done";
}
await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`);
return "done";
}
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
if (!user) return "ignored";
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
if (/^\/digest\b/.test(text)) {
const d = await buildDigest(db, user);
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
return "done";
}
if (m.reply_to_message) {
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
if (!q || !(await canAccess(user, q.projectId))) {
await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id);
return "done";
}
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
return "done";
}
if (m.voice || m.audio) {
await onVoice(user, m);
return "done";
}
if (!text || text.startsWith("/")) {
await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею.");
return "done";
}
// PEP-45: any other text is a new story (created only after a button press).
await startStory(user, m.chat.id, text, false);
return "done";
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
if (!user) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
}
const parts = (c.data ?? "").split(":");
if (parts[0] === "d" || parts[0] === "t") {
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
const [kind, idStr, choice] = parts;
const id = Number(idStr);
let toast = "Неизвестная кнопка";
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
const i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null;
const projectId = q0?.projectId ?? s0?.projectId ?? i0?.projectId;
if (projectId == null || !(await canAccess(user, projectId))) {
// Unknown or someone else's question/session: don't reveal which.
await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : kind === "i" ? "Ошибка не найдена" : "Вопрос не найден").catch(() => {});
return "done";
}
if (kind === "q" && choice === "accept") {
try {
const ref = await acceptTask(db, id, "telegram");
toast = `${ref.key} принята ✅`;
} catch (e) {
toast = (e as Error).message;
}
scheduleReconcile();
} else if (kind === "q") {
const q = await getQuestion(db, id).catch(() => null);
const text = q && choice ? choiceToAnswer(q, choice) : null;
toast = q && text ? await answer(q, text) : "Вопрос не найден";
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
// Decision on a new production error (PEP-58).
try {
const r = await decideIncident(db, id, choice, user.login);
toast = r.task ? `${r.task.key}: ${choice === "start" ? "агент взялся ▶️" : "в бэклоге 📥"}` : "Игнорируем 🙈";
} catch (e) {
toast = (e as Error).message;
}
wakeOutbox?.();
} else if (kind === "s") {
const s = await getSession(db, id).catch(() => null);
if (!s) toast = "Сессия не найдена";
else if (choice === "resume") {
try {
const r = await resumeSession(db, s.id);
toast = `Перезапущено (поколение ${r.generation}) 🔁`;
} catch (e) {
toast = (e as Error).message;
}
} else if (choice === "stop") {
await stopSession(db, s.id);
toast = "Сессия остановлена ⏹";
}
scheduleReconcile();
}
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
async function handleUpdate(u: TgUpdate): Promise {
if (!(await claimUpdate(db, u.update_id))) return;
try {
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
await finishUpdate(db, u.update_id, r);
} catch (e) {
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
await finishUpdate(db, u.update_id, "failed");
}
}
// ── loops ──────────────────────────────────────────────────────────────────────
const sleep = (ms: number) =>
new Promise((r) => {
const t = setTimeout(r, ms);
abort.signal.addEventListener("abort", () => (clearTimeout(t), r()), { once: true });
});
async function pollLoop() {
while (!abort.signal.aborted) {
try {
let offset = await getOffset(db);
const updates = await api.getUpdates(offset, o.pollTimeoutSec ?? 25, abort.signal);
for (const u of updates) {
await handleUpdate(u);
offset = u.update_id + 1;
await setOffset(db, offset);
}
} catch (e) {
log(`poll: ${(e as Error).message}`);
await sleep(3000);
}
}
}
async function outboxLoop() {
while (!abort.signal.aborted) {
await flushOutbox().catch((e) => log(`outbox: ${(e as Error).message}`));
await Promise.race([sleep(o.outboxIntervalMs ?? 1000), new Promise((r) => (wakeOutbox = r))]);
wakeOutbox = null;
}
}
async function reconcileLoop() {
while (!abort.signal.aborted) {
await reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`));
await sleep(o.reconcileIntervalMs ?? 10_000);
}
}
// Writes by other processes the poke missed (PRAGMA data_version moves on every commit
// from another connection): at most a second late instead of waiting for reconcileLoop.
async function changesLoop() {
let seen = db.$client.dataVersion();
while (!abort.signal.aborted) {
await sleep(o.changesIntervalMs ?? 1000);
const v = db.$client.dataVersion();
if (v !== seen) {
seen = v;
scheduleReconcile();
}
}
}
async function monitorLoop() {
while (!abort.signal.aborted) {
try {
await beat(db, "bot");
if (await checkServices(db, { self: "bot", log })) wakeOutbox?.();
} catch (e) {
log(`monitor: ${(e as Error).message}`);
}
await sleep(o.heartbeatIntervalMs ?? 30_000);
}
}
let loops: Promise | null = null;
let unlisten: (() => Promise) | null = null;
return {
reconcile,
flushOutbox,
handleUpdate,
async start() {
const me = await api.getMe();
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
log(`bot @${me.username} started`);
unlisten = await listenEvents("bot", () => scheduleReconcile());
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
return me;
},
async stop() {
abort.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
},
};
}
export type Bot = ReturnType;