-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
444 lines (382 loc) · 11.9 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import { Sentry } from "./sentry.ts";
import {
Client,
GatewayIntentBits,
Partials,
ChannelType,
TextChannel,
Message,
Events,
BaseGuildTextChannel,
} from "discord.js";
import { RateLimiter } from "limiter";
import "dotenv/config";
import { copilot } from "./copilot.ts";
import { throttle } from "throttle-debounce";
import { checkMatchingWords, keyTriggerAIWords } from "./stemmer.ts";
import { broadcastMessage, db, dbchannel } from "./ProfileDB.ts";
import { initTg } from "./telegram.ts";
// Stateful data for each user and interfaces
type ChannelIdKey = string;
type ChannelUserIdKey = string;
type UserIdKey = string;
export interface UserChannelData {
userId: UserIdKey;
messageId: string;
// username: string;
userText: string;
channel: ChannelIdKey; //BaseGuildTextChannel;
react: (emoji: string) => void;
reply: (msg: string) => void;
isAdmin: boolean;
isTelegram: boolean;
}
const limiterGlobal = new Map<ChannelIdKey, RateLimiter>();
// new RateLimiter({ tokensPerInterval: 150, interval: "hour" });
const history = new Map<ChannelUserIdKey, UserChannelData>();
export function addHistory(msg: UserChannelData) {
const { userText, userId, isAdmin, messageId, reply } = msg;
// Rate limiting
let limiter = limiterGlobal.get(msg.channel);
if (!limiter) {
limiterGlobal.set(
msg.channel,
(limiter = new RateLimiter({ tokensPerInterval: 80, interval: "hour" }))
);
} else if (!limiter.tryRemoveTokens(1)) {
reply(
"Rate limit exceeded. Please try again in an hour. Contact [email protected] for rate increase."
);
return;
}
// If group chat, check if the bot was mentioned
if (userText.length > 600) {
reply("600 characters limit please for my brain. Thanks friend!");
return true;
}
// ignore idle or met chat
if (
/^(\/\/|#|\^|@|meta|note|hm|hrm|!|\?)/.test(userText) ||
/\b(btw|lol|rofl)\b/.test(userText)
) {
return true;
}
let c = userText.trim();
if (c.startsWith("/help")) {
reply(
"Commands: \n /requests shows all open user requests\n /profile shows user profile\n /reset_all - to reset all your data \n /recent - show recent rows \n /help - to view this message"
);
return true;
}
if (c.startsWith("/profile")) {
c = msg.userText = "show me my user profile in full detail";
// return false;
}
if (
c.startsWith("/bugs") ||
c.startsWith("/issues") ||
c.startsWith("/requests")
) {
c = msg.userText = "show me all issues or bugs or feature requests";
// return false;
}
if (c.startsWith("/todo") || c.startsWith("/task")) {
c = msg.userText = "show me all todo tasks";
// return false;
}
if (c.startsWith(process.env.SECRET_BROADCAST_CMD || "/adminbroadcast")) {
const msg = c.split(" ").slice(1).join(" ");
// push event to all users using supabase pg
// broadcastMessage("broadcast to all users");
client.channels.cache.forEach((channel) => {
if (channel.type === ChannelType.GuildText) {
(channel as TextChannel).send("SYSTEM MESSAGE: " + msg);
}
});
return false;
}
if (c.startsWith("/reset_all")) {
db.from("documents")
.delete()
.eq("userid", userId)
.eq("channelid", msg.channel);
reply("Resetting your profile");
// reset profile
return true;
}
if (c.startsWith("/recent")) {
db.from("documents")
.select("*")
.eq("updated_by", userId)
.eq("channelid", msg.channel)
.limit(3)
.order("updated_at", { ascending: false })
.then((r) => {
reply(
"Recent updates: \n" +
r.data
?.map((x, i) => i + ": " + x.content)
.join("\n")
.slice(0, 1800)
);
});
return true;
}
if (c.startsWith("/")) {
reply("Invalid command. Type /help to see available commands.");
return true;
}
const key = `${msg.channel}-${msg.userId}-${msg.isTelegram ? "tg" : ""}`;
if (history.has(key)) {
msg.userText = `${history.get(key)?.userText}\n<MESSAGE>\n${msg.userText}`;
if (msg.userText.length > 2000) {
reply("message thread too long");
return true;
}
}
const everyWordNotMatching = checkMatchingWords(msg.userText);
if (!everyWordNotMatching) {
console.log("No AI trigger words found in message");
return;
}
console.log("msg", msg);
msg.react("🤔");
history.set(key, msg);
throttleResponse(0);
}
// Core function to process incoming messages
const throttleResponse = throttle(3000, async (n) => {
try {
await gptcompletionOnHistory();
} catch (e) {
console.error("Error throttling:", e);
Sentry.captureException(e);
}
});
// Telegram init for message handling
initTg();
// Discord client setup
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.Message,
Partials.GuildMember,
Partials.User,
],
});
client.on("error", (e) => {
console.error("Discord error:", e);
Sentry.captureException(e);
});
client.on("ready", async () => {
console.log("Bot is ready!");
// dbchannel
// .on("broadcast", { event: "adminbroadcast" }, (payload) => {
// })
// .subscribe();
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isCommand()) {
console.log("Not a command");
return;
}
// if (!interaction.inGuild()) return; // only guilds
// if (!interaction.member) return; // only members
// if (!interaction.channel) return; // only channels
// if (!interaction.user) return; // only users
interaction.reply({ content: "can you see this?", ephemeral: true });
});
client.on("messageCreate", async (message) => {
// if (message.channel.type === ChannelType.DM && !message.author.bot) {
// ignore bot messages
if (
!message?.content ||
message.author.bot ||
message.author.username === "ThriveTogether" ||
message.author.username.toLowerCase().startsWith("thrive")
) {
return;
}
// must be added to a channel first
if (message.channel.type === ChannelType.DM) {
message.channel.send(
"Please add me to a channel first. Install link: https://discord.com/oauth2/authorize?client_id=1220895933563277332"
);
return;
}
// include mentions
if (message.reference?.messageId) {
try {
const repliedMessage = await message.channel.messages.fetch(
message.reference.messageId
);
// console.log(`Original message content: ${repliedMessage.content}`);
message.content = `${message.content}`;
message.content += `\n\n<POSSIBLY_RELATED_SEARCH>${repliedMessage.content.slice(
0,
320
)}`;
// Do something with the replied message content
} catch (error) {
console.error("Error fetching the replied message:", error);
}
} else {
}
Sentry.setUser({
id: message.author.id,
username: message.author.username,
});
try {
handleDiscordIncomingMessage(message);
throttleResponse(0);
} catch (e) {
console.error("Error handling incoming message:", e);
Sentry.captureException(e);
}
});
});
// only one global operation at a time for logging
let _active = false;
async function gptcompletionOnHistory() {
if (_active) return;
if (history.size === 0) return;
// clone histrory
const historyClone = new Map(history);
history.clear();
for (const [__channelid, val] of historyClone.entries()) {
const channelid = val.channel;
const { userText, userId, isAdmin, messageId, reply, isTelegram } = val;
if (!userText) {
console.log("No userText found in history", val);
return;
}
// const channel = (await client.channels.fetch(channelid)) as TextChannel;
try {
_active = true;
console.log("userText::", userText);
// return;
let { r, saved, fetched } = await copilot(
userText,
channelid,
userId,
isAdmin,
isTelegram ? 1 : 0
);
val.react("");
// console.log("userText::r", r, saved, fetched);
// bot reactions
if (r.includes("INVALID") || r.includes("ERROR")) {
val.react("❌");
reply("Error: " + r);
return;
}
// else if (isAdmin && saved) val.react("👍");
else if (r.includes("NOT_FOUND")) {
val.react("🤷");
reply("No results found");
return;
} else if (r.includes("Please")) {
// question mark emoji
val.react("❓");
}
if (r.includes("SILENCE") || r.includes("STOP")) {
console.log('x Silence or stop command detected: "', r);
return;
} else {
}
// if (saved) return; // don't log saved messages]
if (!userText.includes("?") && saved) {
val.react("👍");
//console.log("fetched or saved");
// if(isAdmin) return; // don't bother replying if admin
}
// channel.send(r);
// Message post reply to the user messageId
// const message = await channel.messages.fetch(messageId);
reply(r);
} catch (err: any) {
// Error
val.react("❌");
console.error("Error processing completion:", err);
console.error(JSON.stringify(err));
reply("Error: " + JSON.stringify(err));
// throw err;
} finally {
_active = false;
}
}
}
async function replaceUserMentions(r: string) {
const mentionRegex = /#userid_(\d+)/g;
const mentions = Array.from(r.matchAll(mentionRegex));
for (const m of mentions) {
const userId = m[1];
const user = await client.users.fetch(userId);
r = r.replace(m[0], `${user.displayName} [${user.username}]`);
}
return r;
}
function handleDiscordIncomingMessage(message: Message<boolean>) {
// console.log("handleIncomingMessage", message.content);
// let content = message.content;
let c = message.content.replace(/$<@.*>\s*/, "");
// console.log("c", c);
// const username = message.author.username;
const channelId = message.channel.id;
// check if message @mentions a username and add that user's ID to the message
if (message.attachments?.first()?.url) {
const allowedExtensions = /\.(png|jpg|jpeg|gif|mp4|webm|webp|txt|md|pdf)/i;
c = `${c} \n<attachments>\n${message.attachments
.filter((x) => allowedExtensions.test(x.url))
.map((a) => a.url)
.join(" \n")}`;
}
// console.log("content after mentions", content);
// return;
Sentry.setExtra("msg", c);
// check for mentions like <@1220895933563277332> and convert into #userid_1220895933563277332
const mentionRegex = /<@[!]*(\d+)>/g; // <@!1220895933563277332>
const mentions = Array.from(c.matchAll(mentionRegex)); // use where we remove self mention
for (const m of mentions) {
const userId = m[1];
c = c.replace(m[0], `#userid_${userId}`);
}
// check if message is a guild administrator or can kick members
let isAdmin = false;
if (
message.member?.permissions.has("Administrator") ||
message.member?.permissions.has("ManageChannels") ||
message.member?.permissions.has("ManageMessages")
) {
isAdmin = true;
}
addHistory({
react: (msg: string) => {
message.reactions.removeAll();
if (msg) message.react(msg);
},
isAdmin: isAdmin,
userText: c,
channel: channelId,
messageId: message.id,
reply: async (msg: string) => {
// convert all #userid_ID into DisplayName
if (!msg.toLowerCase().includes(" id"))
msg = await replaceUserMentions(msg);
message.reply(msg);
},
// username: username,
userId: message.author.id,
isTelegram: false,
});
// console.log(key, "history:", history.get(key)?.userText);
}
if (!process.env.DISCORD_TOKEN)
throw new Error("No Discord token DISCORD_TOKEN found in .env file");
client.login(process.env.DISCORD_TOKEN);