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 SlackApi { postMessage(channel: string, text: string, threadTs?: string): Promise; /** То же, но возвращает ts отправленного сообщения (null - не отправлено): по нему считается время ответа для chat_timing. */ postMessageTs?(channel: string, text: string, threadTs?: string): Promise; fileInfo(fileId: string): Promise; download(file: SlackFile, toPath: string): Promise; /** Загружает файл в канал (нужен scope files:write). */ uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise; } /** Web API Slack под токеном бота (отправка сообщений и скачивание вложений). */ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch): SlackApi { const call = async (method: string, body: Record) => { 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 }; }; const postTs = async (channel: string, text: string, threadTs?: string): Promise => { // 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; }; return { postMessageTs: postTs, 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 }; 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) => 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 }).WebSocket; let stopped = false; let current: { close(): void } | null = null; let backoff = 1000; const connect = async (): Promise => { 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 } }; 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(); }, }; }