Проектные каналы: тихий режим, recap для Daily Log; Huddle через message_changed; короткие напоминания
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,12 +9,30 @@ export interface SlackFile {
|
||||
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>;
|
||||
}
|
||||
@@ -34,8 +52,55 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
|
||||
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;
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user