pr-hw1/src/assistant.ts
peppa-bot b4f907d1d5 PH-1: образ продукта, форматирование
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:02:48 +00:00

547 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** Ядро ассистента: приём сообщений из источников, синхронизация, Telegram, напоминания. */
import { randomInt } from "node:crypto";
import type { Config } from "./config.ts";
import { extractItems } from "./extract.ts";
import { type FetchFn, GoogleClient, GoogleError } from "./google.ts";
import { formatDateTime, formatTime, t } from "./i18n.ts";
import { buildPlan, type Proposal } from "./plan.ts";
import type { SourceKind, Store, Task } from "./store.ts";
import {
messageLink,
TelegramClient,
TelegramError,
type TgMessage,
type TgUpdate,
userName,
} from "./telegram.ts";
import { localDateKey, localDayStart, zonedParts } from "./time.ts";
export const CODE_TTL_MS = 30 * 60000;
const BOT_LANG = "ru" as const;
export interface IncomingMessage {
source: SourceKind;
sourceId: string;
sourceTitle: string;
from?: string;
link?: string;
text: string;
}
export interface Deps {
fetch?: FetchFn;
now?: () => Date;
log?: (msg: string, err?: unknown) => void;
}
export class Assistant {
google?: GoogleClient;
telegram?: TelegramClient;
readonly now: () => Date;
private log: (msg: string, err?: unknown) => void;
private lastSync = 0;
private polling = false;
readonly config: Config;
readonly store: Store;
constructor(config: Config, store: Store, deps: Deps = {}) {
this.config = config;
this.store = store;
this.now = deps.now ?? (() => new Date());
this.log = deps.log ?? ((m, e) => console.log(m, e ?? ""));
if (config.google)
this.google = new GoogleClient(config.google.clientId, config.google.clientSecret, deps.fetch);
if (config.telegram) this.telegram = new TelegramClient(config.telegram.token, deps.fetch);
}
get demo(): boolean {
return !this.config.password;
}
/** Новые задачи из сообщения; одно и то же сообщение второй раз не разбирается. */
ingest(msg: IncomingMessage): Task[] {
const st = this.store.state;
if (st.processed.includes(msg.sourceId)) return [];
st.processed.push(msg.sourceId);
const now = this.now();
const out: Task[] = [];
extractItems(msg.text, { now, tz: this.config.tz }).forEach((item, i) => {
const task = this.store.addTask(
{
kind: item.kind,
title: item.title,
due: item.due?.toISOString(),
dueHasTime: item.dueHasTime,
source: msg.source,
sourceId: i === 0 ? msg.sourceId : `${msg.sourceId}#${i}`,
sourceTitle: msg.sourceTitle,
sourceFrom: msg.from,
link: msg.link,
excerpt: item.excerpt,
},
now,
);
if (task) out.push(task);
});
this.store.save();
return out;
}
// ---------- Google ----------
async syncGoogle(): Promise<{ added: Task[] } | undefined> {
const g = this.store.state.google;
if (!this.google || !g) return undefined;
const added: Task[] = [];
try {
const skip = new Set(this.store.state.processed);
const mails = await this.google.recentMessages(
g.refreshToken,
g.email,
"newer_than:3d -category:promotions -category:social -category:forums -in:chats -in:sent",
20,
skip,
);
for (const m of mails) {
added.push(
...this.ingest({
source: "gmail",
sourceId: `gmail:${m.id}`,
sourceTitle: m.subject,
from: m.from,
link: m.link,
text: `${m.subject}\n${m.text}`,
}),
);
}
const now = this.now();
const events = await this.google.events(
g.refreshToken,
localDayStart(now, this.config.tz),
localDayStart(now, this.config.tz, 8),
);
this.store.state.events = events
.filter((e) => e.busy)
.map((e) => ({ id: e.id, title: e.title, start: e.start, end: e.end, link: e.link }));
for (const e of events) {
if (!e.description.trim()) continue;
added.push(
...this.ingest({
source: "calendar",
sourceId: `calendar:${e.id}`,
sourceTitle: e.title,
link: e.link,
text: e.description,
}),
);
}
g.lastSyncAt = now.toISOString();
g.lastError = undefined;
} catch (err) {
g.lastError = err instanceof GoogleError && err.revoked ? "revoked" : "failed";
this.log("google sync failed", err);
}
this.store.save();
if (added.length) await this.notifyAdded(added);
return { added };
}
async connectGoogle(code: string, redirectUri: string): Promise<void> {
if (!this.google) throw new Error("google not configured");
this.google.forget();
const { refreshToken, email } = await this.google.exchangeCode(code, redirectUri);
this.store.state.google = { refreshToken, email, connectedAt: this.now().toISOString() };
this.store.state.googleNotice = undefined;
this.store.save();
}
disconnectGoogle(): void {
this.store.state.google = undefined;
this.store.state.events = [];
this.google?.forget();
this.store.save();
}
async addToCalendar(taskId: string): Promise<Task> {
const task = this.store.task(taskId);
const g = this.store.state.google;
if (!task?.accepted || !this.google || !g) throw new Error("not possible");
if (task.calendarEventId) return task;
const ev = await this.google.createEvent(g.refreshToken, {
title: task.title,
description: [task.sourceTitle, task.link].filter(Boolean).join("\n"),
start: new Date(task.accepted.start),
end: new Date(task.accepted.end),
});
task.calendarEventId = ev.id;
task.calendarLink = ev.link;
this.store.state.events.push({
id: ev.id,
title: task.title,
start: task.accepted.start,
end: task.accepted.end,
link: ev.link,
});
this.store.save();
return task;
}
// ---------- План и напоминания ----------
plan(): Proposal[] {
return buildPlan(this.store.state.tasks, this.store.state.events, {
now: this.now(),
tz: this.config.tz,
});
}
/** Принять предложенное время. Возвращает, придёт ли напоминание в чат. */
accept(taskId: string): { ok: boolean; chatConfirmed: boolean } {
const task = this.store.task(taskId);
const p = this.plan().find((x) => x.taskId === taskId);
if (!task || !p) return { ok: false, chatConfirmed: this.chatId !== undefined };
task.accepted = { start: p.start.toISOString(), end: p.end.toISOString() };
task.reminderSentAt = undefined;
this.store.save();
return { ok: true, chatConfirmed: this.chatId !== undefined };
}
markDone(taskId: string): boolean {
const task = this.store.task(taskId);
if (!task) return false;
task.status = "done";
this.store.save();
return true;
}
get chatId(): number | string | undefined {
return (
this.store.state.telegram.chatId ??
(this.store.state.telegram.mode === "send-only" ? this.config.telegram?.chatId : undefined)
);
}
describeTask(task: Task): string {
const tz = this.config.tz;
const lines = [task.title];
if (task.due)
lines.push(
t(BOT_LANG, "bot.due", { due: formatDateTime(new Date(task.due), BOT_LANG, tz, task.dueHasTime) }),
);
lines.push(
t(BOT_LANG, "bot.source", { source: t(BOT_LANG, `source.${task.source}`), title: task.sourceTitle }),
);
if (task.link) lines.push(task.link);
return lines.join("\n");
}
async sendReminders(): Promise<number> {
const chat = this.chatId;
if (!this.telegram || chat === undefined) return 0;
const now = this.now().getTime();
let sent = 0;
for (const task of this.store.state.tasks) {
if (task.status !== "open" || !task.accepted || task.reminderSentAt) continue;
const start = Date.parse(task.accepted.start);
if (start > now) continue;
task.reminderSentAt = new Date(now).toISOString();
this.store.save();
if (now - start > 12 * 3600000) continue; // слишком старое — не шлём
try {
await this.telegram.sendMessage(chat, `${t(BOT_LANG, "bot.reminder")} ${this.describeTask(task)}`, [
[{ text: t(BOT_LANG, "bot.btnDone"), callback_data: `done:${task.id}` }],
]);
sent++;
} catch (err) {
this.log("reminder failed", err);
}
}
return sent;
}
/** Утренняя сводка в 08:30 один раз в день. */
async sendDailySummary(force = false): Promise<boolean> {
const chat = this.chatId;
if (!this.telegram || chat === undefined) return false;
const now = this.now();
const tz = this.config.tz;
const p = zonedParts(now, tz);
const key = localDateKey(now, tz);
if (!force && (this.store.state.lastSummaryDate === key || p.hour * 60 + p.minute < 8 * 60 + 30))
return false;
this.store.state.lastSummaryDate = key;
this.store.save();
const plan = this.plan().filter((x) => localDateKey(x.start, tz) === key);
const lines = [t(BOT_LANG, "bot.summaryTitle", { date: formatDateTime(now, BOT_LANG, tz, false) })];
if (!plan.length) lines.push(t(BOT_LANG, "bot.summaryEmpty"));
const buttons = [];
for (const item of plan) {
const task = this.store.task(item.taskId);
if (!task) continue;
lines.push(
`• ${formatTime(item.start, BOT_LANG, tz)} — ${task.title}${item.accepted ? "" : ` (${t(BOT_LANG, "bot.proposed")})`}`,
);
if (!item.accepted)
buttons.push([
{
text: `${t(BOT_LANG, "bot.btnAccept")} ${formatTime(item.start, BOT_LANG, tz)}: ${task.title}`.slice(
0,
60,
),
callback_data: `accept:${task.id}`,
},
]);
}
try {
await this.telegram.sendMessage(
chat,
lines.join("\n"),
buttons.length ? buttons.slice(0, 8) : undefined,
);
} catch (err) {
this.log("summary failed", err);
}
return true;
}
private async notifyAdded(tasks: Task[]): Promise<void> {
const chat = this.chatId;
if (!this.telegram || chat === undefined) return;
const plan = this.plan();
for (const task of tasks.slice(0, 5)) {
const p = plan.find((x) => x.taskId === task.id);
const lines = [
`${t(BOT_LANG, task.kind === "agreement" ? "bot.newAgreement" : "bot.newTask")} ${this.describeTask(task)}`,
];
if (p)
lines.push(t(BOT_LANG, "bot.proposal", { time: formatDateTime(p.start, BOT_LANG, this.config.tz) }));
try {
await this.telegram.sendMessage(
chat,
lines.join("\n"),
p
? [
[
{ text: t(BOT_LANG, "bot.btnAccept"), callback_data: `accept:${task.id}` },
{ text: t(BOT_LANG, "bot.btnDone"), callback_data: `done:${task.id}` },
],
]
: undefined,
);
} catch (err) {
this.log("notify failed", err);
}
}
}
// ---------- Telegram ----------
/** Код для ссылки подтверждения чата (30 минут). */
telegramCode(): string {
const tg = this.store.state.telegram;
const now = this.now().getTime();
if (tg.pendingCode && now - Date.parse(tg.pendingCode.createdAt) < CODE_TTL_MS - 5 * 60000)
return tg.pendingCode.code;
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
for (let i = 0; i < 8; i++) code += alphabet[randomInt(alphabet.length)];
tg.pendingCode = { code, createdAt: new Date(now).toISOString() };
this.store.save();
return code;
}
/**
* Проверка, не занят ли бот другим проектом. Если у бота уже есть приём сообщений (webhook),
* ничего не меняем и работаем только на отправку.
*/
async telegramInit(): Promise<void> {
const tg = this.store.state.telegram;
if (!this.telegram) {
tg.mode = "off";
return;
}
try {
const me = await this.telegram.getMe();
tg.botUsername = me.username;
const hook = await this.telegram.getWebhookInfo();
tg.mode = hook.url ? "send-only" : "polling";
tg.lastError = undefined;
} catch (err) {
tg.mode = "off";
tg.lastError =
err instanceof TelegramError && (err.code === 401 || err.code === 404) ? "token" : "failed";
this.log("telegram init failed", err);
}
this.store.save();
}
async telegramPollOnce(timeout = 0, signal?: AbortSignal): Promise<number> {
const tg = this.store.state.telegram;
if (!this.telegram || tg.mode !== "polling") return 0;
let updates: TgUpdate[];
try {
updates = await this.telegram.getUpdates(tg.offset, timeout, signal);
} catch (err) {
if (err instanceof TelegramError && err.code === 409) {
// Сообщения бота забирает другой проект — не мешаем ему.
tg.mode = "send-only";
this.store.save();
}
throw err;
}
for (const u of updates) {
tg.offset = u.update_id + 1;
this.store.save();
try {
await this.handleUpdate(u);
} catch (err) {
this.log("telegram update failed", err);
}
}
return updates.length;
}
async pollLoop(signal: AbortSignal): Promise<void> {
if (this.polling) return;
this.polling = true;
try {
while (!signal.aborted && this.store.state.telegram.mode === "polling") {
try {
await this.telegramPollOnce(25, signal);
} catch (err) {
if (signal.aborted) break;
this.log("telegram poll failed", err);
await new Promise((r) => setTimeout(r, 10000));
}
}
} finally {
this.polling = false;
}
}
async handleUpdate(u: TgUpdate): Promise<void> {
const bot = this.telegram;
if (!bot) return;
const tg = this.store.state.telegram;
if (u.callback_query) {
const q = u.callback_query;
if (tg.chatId === undefined || q.from.id !== tg.chatId) {
await bot.answerCallback(q.id);
return;
}
const [action, id] = (q.data ?? "").split(":");
let answer = t(BOT_LANG, "bot.notFound");
if (action === "accept" && id) {
const r = this.accept(id);
const task = this.store.task(id);
if (r.ok && task?.accepted)
answer = t(BOT_LANG, "bot.accepted", {
time: formatDateTime(new Date(task.accepted.start), BOT_LANG, this.config.tz),
});
} else if (action === "done" && id && this.markDone(id)) {
answer = t(BOT_LANG, "bot.doneOk");
}
await bot.answerCallback(q.id, answer);
return;
}
const m = u.message;
if (!m) return;
const text = (m.text ?? m.caption ?? "").trim();
if (m.chat.type === "private") {
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?/.exec(text);
if (start) {
await this.confirmChat(m, start[1]);
return;
}
if (tg.chatId === undefined || m.chat.id !== tg.chatId) {
await bot.sendMessage(m.chat.id, t(BOT_LANG, "bot.private"));
return;
}
if (/^\/plan/.test(text)) {
await this.sendDailySummary(true);
return;
}
if (!text || text.startsWith("/")) {
await bot.sendMessage(m.chat.id, t(BOT_LANG, "bot.help"));
return;
}
const from = m.forward_origin
? (userName(m.forward_origin.sender_user) ??
m.forward_origin.sender_user_name ??
m.forward_origin.chat?.title)
: undefined;
const added = this.ingest({
source: "telegram",
sourceId: `telegram:${m.chat.id}:${m.message_id}`,
sourceTitle: from ? t(BOT_LANG, "source.tgForwarded", { name: from }) : t(BOT_LANG, "source.tgOwn"),
from,
text,
});
if (!added.length) await bot.sendMessage(m.chat.id, t(BOT_LANG, "bot.nothing"));
else await this.notifyAdded(added);
return;
}
if (m.chat.type === "group" || m.chat.type === "supergroup") {
// Группу включает только владелец командой /watch; сообщения остальных групп не читаем.
if (/^\/watch/.test(text) && tg.chatId !== undefined && m.from?.id === tg.chatId) {
if (!tg.groups.includes(m.chat.id)) tg.groups.push(m.chat.id);
this.store.save();
await bot.sendMessage(m.chat.id, t(BOT_LANG, "bot.groupOn"));
return;
}
if (!tg.groups.includes(m.chat.id) || !text) return;
const added = this.ingest({
source: "telegram",
sourceId: `telegram:${m.chat.id}:${m.message_id}`,
sourceTitle: t(BOT_LANG, "source.tgGroup", { title: m.chat.title ?? "" }),
from: userName(m.from),
link: messageLink(m),
text,
});
if (added.length) await this.notifyAdded(added);
}
}
private async confirmChat(m: TgMessage, code: string | undefined): Promise<void> {
const bot = this.telegram;
if (!bot) return;
const tg = this.store.state.telegram;
const now = this.now().getTime();
const pending = tg.pendingCode;
if (!code || !pending) {
await bot.sendMessage(
m.chat.id,
tg.chatId === m.chat.id ? t(BOT_LANG, "bot.help") : t(BOT_LANG, "bot.private"),
);
return;
}
if (pending.code !== code.toUpperCase() || now - Date.parse(pending.createdAt) > CODE_TTL_MS) {
await bot.sendMessage(m.chat.id, t(BOT_LANG, "bot.codeExpired"));
return;
}
tg.chatId = m.chat.id;
tg.confirmedAt = new Date(now).toISOString();
tg.pendingCode = undefined;
this.store.save();
await bot.sendMessage(m.chat.id, `${t(BOT_LANG, "bot.confirmed")}\n\n${t(BOT_LANG, "bot.help")}`);
}
// ---------- Планировщик ----------
async tick(): Promise<void> {
const now = this.now().getTime();
if (now - this.lastSync >= this.config.syncIntervalMin * 60000) {
this.lastSync = now;
await this.syncGoogle();
}
await this.sendReminders();
await this.sendDailySummary();
}
async syncNow(): Promise<void> {
this.lastSync = this.now().getTime();
await this.syncGoogle();
}
}