45 lines
2.5 KiB
TypeScript
45 lines
2.5 KiB
TypeScript
import type { SlackApi, SlackFile, SlackMessage } from "./slack.js";
|
||
|
||
/** Фейк Slack: сообщения лежат в history по каналам, ответы - в replies, отправленное - в posted. */
|
||
export class FakeSlack implements SlackApi {
|
||
dms: string[] = [];
|
||
top = new Map<string, SlackMessage[]>();
|
||
threads = new Map<string, SlackMessage[]>();
|
||
files = new Map<string, Buffer>();
|
||
posted: { channel: string; text: string; threadTs?: string; ts: string }[] = [];
|
||
private n = 0;
|
||
async post(channel: string, text: string): Promise<void> {
|
||
await this.postMessage(channel, text);
|
||
}
|
||
async postMessage(channel: string, text: string, threadTs?: string): Promise<{ channel: string; ts: string }> {
|
||
const ts = `${1_800_000_000 + ++this.n}.000100`;
|
||
const ch = /^U/.test(channel) ? `D${channel}` : channel; // id пользователя открывает личный диалог
|
||
this.posted.push({ channel: ch, text, threadTs, ts });
|
||
return { channel: ch, ts };
|
||
}
|
||
async listDmChannels(): Promise<string[]> { return this.dms; }
|
||
async history(channel: string): Promise<SlackMessage[]> { return this.top.get(channel) ?? []; }
|
||
async replies(channel: string, threadTs: string): Promise<SlackMessage[]> { return this.threads.get(`${channel}:${threadTs}`) ?? []; }
|
||
async downloadFile(file: SlackFile): Promise<Buffer> {
|
||
const b = this.files.get(file.url);
|
||
if (!b) throw new Error(`нет файла ${file.url}`);
|
||
return b;
|
||
}
|
||
/** Добавить сообщение; files - содержимое «картинок» (его читает фейковый Claude). */
|
||
msg(channel: string, ts: string, user: string, text: string, fileContents: string[] = [], threadTs?: string): SlackMessage {
|
||
const files: SlackFile[] = fileContents.map((c, i) => {
|
||
const url = `https://files.slack/${channel}/${ts}/${i}`;
|
||
this.files.set(url, Buffer.from(c));
|
||
return { id: `F${ts}${i}`, name: `photo${i}.jpg`, mimetype: "image/jpeg", url };
|
||
});
|
||
const m: SlackMessage = { channel, ts, threadTs, user, text, files, isBot: false, replyCount: 0 };
|
||
if (threadTs && threadTs !== ts) {
|
||
const k = `${channel}:${threadTs}`;
|
||
this.threads.set(k, [...(this.threads.get(k) ?? []), m]);
|
||
} else this.top.set(channel, [...(this.top.get(channel) ?? []), m]);
|
||
return m;
|
||
}
|
||
/** Сообщение бота (ранее отправленное) как оно было бы видно в history. */
|
||
lastPostedTs(): string { return this.posted[this.posted.length - 1]!.ts; }
|
||
}
|