Files
khb_microservices/packages/khbuild_assistant_prep/src/slack/api.ts
Yuri Yaryshev 4a32a08b6d
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m13s
Проектные каналы: тихий режим, recap для Daily Log; Huddle через message_changed; короткие напоминания
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 21:12:07 +03:00

196 lines
11 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.

import { mkdirSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
export interface SlackFile {
id: string;
name: string;
mimetype: string;
size: number;
urlPrivateDownload: string;
}
/** Сообщение из истории канала (для контекста агента проектного канала). */
export interface SlackHistoryMessage {
ts: string;
userId: string | null;
botId: string | null;
text: string;
threadTs: string | null;
fileNames: string[];
}
export interface SlackApi {
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
/** То же, но возвращает ts отправленного сообщения (null - не отправлено): по нему считается время ответа для chat_timing. */
postMessageTs?(channel: string, text: string, threadTs?: string): Promise<string | null>;
fileInfo(fileId: string): Promise<SlackFile | null>;
download(file: SlackFile, toPath: string): Promise<number>;
/** История канала с момента oldest (unix-секунды) по возрастанию времени, вместе с ответами в тредах. */
history?(channel: string, oldest: number): Promise<SlackHistoryMessage[]>;
/** Отображаемое имя пользователя Slack (кэшируется); null - не удалось узнать. */
userName?(userId: string): Promise<string | null>;
/** Ставит эмодзи-реакцию на сообщение (нужен scope reactions:write); ошибка already_reacted не считается сбоем. */
addReaction?(channel: string, ts: string, emoji: string): Promise<boolean>;
/** Slack id самого бота (чтобы пометить его сообщения в истории). */
botUserId?(): Promise<string | null>;
/** Загружает файл в канал (нужен scope files:write). */
uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise<void>;
}
/** Web API Slack под токеном бота (отправка сообщений и скачивание вложений). */
export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch): SlackApi {
const call = async (method: string, body: Record<string, unknown>) => {
const res = await fetchFn(`https://slack.com/api/${method}`, {
method: "POST",
headers: { "content-type": "application/json; charset=utf-8", authorization: `Bearer ${botToken}` },
body: JSON.stringify(body),
});
return (await res.json()) as { ok?: boolean; error?: string; ts?: string; file?: Record<string, unknown> };
};
const postTs = async (channel: string, text: string, threadTs?: string): Promise<string | null> => {
// Slack ограничивает текст ~40000 символов; режем с запасом
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
return r.ok === true ? (typeof r.ts === "string" ? r.ts : "") : null;
};
const get = async (method: string, params: Record<string, string>) => {
const res = await fetchFn(`https://slack.com/api/${method}?${new URLSearchParams(params)}`, { headers: { authorization: `Bearer ${botToken}` } });
return (await res.json()) as { ok?: boolean; error?: string; messages?: Record<string, unknown>[]; user?: Record<string, unknown>; user_id?: string; response_metadata?: { next_cursor?: string } };
};
const toMsg = (m: Record<string, unknown>): SlackHistoryMessage => ({
ts: String(m.ts),
userId: typeof m.user === "string" ? m.user : null,
botId: typeof m.bot_id === "string" ? m.bot_id : null,
text: String(m.text ?? ""),
threadTs: typeof m.thread_ts === "string" ? m.thread_ts : null,
fileNames: ((m.files as { name?: string }[] | undefined) ?? []).map((f) => String(f.name ?? "file")),
});
const names = new Map<string, string | null>();
let botId: string | null | undefined;
return {
postMessageTs: postTs,
async history(channel, oldest) {
const out = new Map<string, SlackHistoryMessage>();
let cursor = "";
for (let page = 0; page < 10; page++) {
const r = await get("conversations.history", { channel, oldest: String(oldest), limit: "200", ...(cursor ? { cursor } : {}) });
if (!r.ok) throw new Error(`Slack conversations.history: ${r.error}`);
for (const m of r.messages ?? []) out.set(String(m.ts), toMsg(m));
cursor = r.response_metadata?.next_cursor ?? "";
if (!cursor) break;
}
// ответы в тредах (в history только родители)
for (const m of [...out.values()].filter((x) => x.threadTs === x.ts).slice(0, 20)) {
const r = await get("conversations.replies", { channel, ts: m.ts, oldest: String(oldest), limit: "100" });
if (r.ok) for (const x of r.messages ?? []) out.set(String(x.ts), toMsg(x));
}
return [...out.values()].sort((a, b) => Number(a.ts) - Number(b.ts));
},
async userName(userId) {
if (names.has(userId)) return names.get(userId)!;
const r = await get("users.info", { user: userId });
const u = r.user as { real_name?: string; name?: string; profile?: { display_name?: string; real_name?: string } } | undefined;
const n = r.ok && u ? u.profile?.display_name || u.real_name || u.profile?.real_name || u.name || null : null;
names.set(userId, n);
return n;
},
async addReaction(channel, ts, emoji) {
const r = await call("reactions.add", { channel, timestamp: ts, name: emoji.replace(/:/g, "") });
return r.ok === true || r.error === "already_reacted";
},
async botUserId() {
if (botId === undefined) botId = (await get("auth.test", {})).user_id ?? null;
return botId;
},
async postMessage(channel, text, threadTs) {
return (await postTs(channel, text, threadTs)) !== null;
},
async fileInfo(fileId) {
const res = await fetchFn(`https://slack.com/api/files.info?file=${encodeURIComponent(fileId)}`, { headers: { authorization: `Bearer ${botToken}` } });
const j = (await res.json()) as { ok?: boolean; file?: Record<string, unknown> };
const f = j.file;
if (!j.ok || !f || typeof f.url_private_download !== "string") return null;
return { id: String(f.id), name: String(f.name ?? f.id), mimetype: String(f.mimetype ?? ""), size: Number(f.size ?? 0), urlPrivateDownload: f.url_private_download };
},
async uploadFile(channel, filename, data, title) {
const form = new URLSearchParams({ filename, length: String(data.length) });
const start = (await (await fetchFn("https://slack.com/api/files.getUploadURLExternal", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", authorization: `Bearer ${botToken}` },
body: form,
})).json()) as { ok?: boolean; error?: string; upload_url?: string; file_id?: string };
if (!start.ok || !start.upload_url || !start.file_id) throw new Error(`Slack files.getUploadURLExternal: ${start.error ?? "нет upload_url"}`);
const up = await fetchFn(start.upload_url, { method: "POST", body: new Uint8Array(data) });
if (!up.ok) throw new Error(`Slack upload: HTTP ${up.status}`);
const done = await call("files.completeUploadExternal", { files: [{ id: start.file_id, title: title ?? filename }], channel_id: channel });
if (!done.ok) throw new Error(`Slack files.completeUploadExternal: ${done.error}`);
},
async download(file, toPath) {
const res = await fetchFn(file.urlPrivateDownload, { headers: { authorization: `Bearer ${botToken}` } });
if (!res.ok) throw new Error(`скачивание ${file.name}: HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
mkdirSync(dirname(toPath), { recursive: true });
writeFileSync(toPath, buf);
return buf.length;
},
};
}
/** Постоянное соединение Socket Mode: события message и др. передаются в onEvent; переподключение при разрыве. */
export function startSocketMode(opts: {
appToken: string;
onEvent: (event: Record<string, unknown>) => void;
log: { info(o: object, m?: string): void; warn(o: object, m?: string): void; error(o: object, m?: string): void };
fetchFn?: typeof fetch;
WebSocketImpl?: new (url: string) => { onmessage: ((e: { data: unknown }) => void) | null; onclose: (() => void) | null; onerror: ((e: unknown) => void) | null; send(d: string): void; close(): void };
}): { stop(): void } {
const fetchFn = opts.fetchFn ?? fetch;
const WS = opts.WebSocketImpl ?? (globalThis as unknown as { WebSocket: NonNullable<typeof opts.WebSocketImpl> }).WebSocket;
let stopped = false;
let current: { close(): void } | null = null;
let backoff = 1000;
const connect = async (): Promise<void> => {
if (stopped) return;
try {
const r = (await (await fetchFn("https://slack.com/api/apps.connections.open", { method: "POST", headers: { authorization: `Bearer ${opts.appToken}` } })).json()) as {
ok?: boolean; url?: string; error?: string;
};
if (!r.ok || !r.url) throw new Error(r.error ?? "apps.connections.open failed");
const ws = new WS(r.url);
current = ws;
ws.onmessage = (e) => {
let m: { type?: string; envelope_id?: string; payload?: { event?: Record<string, unknown> } };
try {
m = JSON.parse(String(e.data));
} catch {
return;
}
if (m.envelope_id) ws.send(JSON.stringify({ envelope_id: m.envelope_id }));
if (m.type === "hello") {
backoff = 1000;
opts.log.info({}, "Slack Socket Mode: соединение установлено");
} else if (m.type === "events_api" && m.payload?.event) opts.onEvent(m.payload.event);
else if (m.type === "disconnect") ws.close();
};
ws.onerror = (e) => opts.log.warn({ err: String((e as { message?: string })?.message ?? e) }, "Slack Socket Mode: ошибка соединения");
ws.onclose = () => {
if (stopped) return;
opts.log.warn({ backoff }, "Slack Socket Mode: соединение закрыто, переподключение");
setTimeout(() => void connect(), backoff);
backoff = Math.min(backoff * 2, 30_000);
};
} catch (e) {
opts.log.error({ err: e instanceof Error ? e.message : String(e), backoff }, "Slack Socket Mode: не удалось подключиться");
setTimeout(() => void connect(), backoff);
backoff = Math.min(backoff * 2, 30_000);
}
};
void connect();
return {
stop() {
stopped = true;
current?.close();
},
};
}