-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
87 lines (65 loc) · 2.41 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Soul } from "@opensouls/engine";
import { config } from "dotenv";
import { Context, Telegraf } from "telegraf";
import { message } from "telegraf/filters";
const souls: Record<string, Soul> = {};
const lastMessageTimestamps: Record<number, number> = {};
async function connectToTelegram() {
const telegraf = new Telegraf<Context>(process.env.TELEGRAM_TOKEN!);
telegraf.launch();
const { username } = await telegraf.telegram.getMe();
console.log(`Start chatting here: https://t.me/${username}`);
process.once("SIGINT", () => telegraf.stop("SIGINT"));
process.once("SIGTERM", () => telegraf.stop("SIGTERM"));
return telegraf;
}
async function setupTelegramSoulBridge(telegram: Telegraf<Context>, telegramChatId: number) {
if (souls[telegramChatId]) {
return souls[telegramChatId];
}
const soul = new Soul({
soulId: `${process.env.SOUL_ID!}-${String(telegramChatId)}`,
organization: process.env.OPEN_SOULS_ORGANIZATION!,
blueprint: process.env.SOUL_ENGINE_BLUEPRINT!,
});
console.log(`Connected to ${String(telegramChatId)}`)
soul.on("says", async (event) => {
let content = await event.content();
if (content.length > 4096) {
content = content.substring(0, 4093) + '...';
}
await telegram.telegram.sendMessage(Number(telegramChatId), content);
});
await soul.connect();
souls[telegramChatId] = soul;
return soul;
}
async function connectToSoulEngine(telegram: Telegraf<Context>) {
const authorizedUserIds: number[] = process.env.AUTHORIZED_USER_IDS!.split(',').map(id => parseInt(id, 10));
for (const userId of authorizedUserIds) {
const telegramChatId = userId;
await setupTelegramSoulBridge(telegram, telegramChatId);
}
telegram.on(message("text"), async (ctx) => {
const telegramChatId = ctx.message.chat.id;
const currentTimestamp = Date.now();
lastMessageTimestamps[telegramChatId] = currentTimestamp;
const soul = await setupTelegramSoulBridge(telegram, telegramChatId);
if (authorizedUserIds.includes(ctx.from?.id)) {
const messageText = ctx.message.text;
soul.dispatch({
action: "said",
content: messageText,
});
await ctx.telegram.sendChatAction(telegramChatId, "typing");
} else {
await ctx.reply(`You're not authorized! Ignoring.`);
}
});
}
async function run() {
config();
const telegram = await connectToTelegram();
connectToSoulEngine(telegram);
}
run();