-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
518 lines (456 loc) · 14.8 KB
/
app.js
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import { configDotenv } from "dotenv";
import TelegramBot from "node-telegram-bot-api";
import { encrypt, decrypt } from "./encryption.js";
import isUrl from "is-url";
import chat from "./genai.js";
import { connectToDatabase } from "./config.js";
import { addToConversationHistory, getConversationHistory } from "./userHistory.js";
import MutedChats from "./model/muted-chats.js"
import gTTS from "gtts"
import { changeAudioSpeed } from "./audo-editor.js";
import { generate } from "randomstring";
import fs from "fs"
import ddg from "ddg"
import music from "./music.js";
import path from "path";
import { createReadStream } from "fs";
configDotenv()
connectToDatabase()
const token = process.env.KEY;
const botID = 7814437622
const masterID = 7671963344
const bot = new TelegramBot(token, {polling: true});
function escapeCode(code) {
return code
.replace(/&/g, '&') // Escape &
.replace(/</g, '<') // Escape <
.replace(/>/g, '>') // Escape >
.replace(/"/g, '"') // Escape "
.replace(/'/g, '''); // Escape '
}
function sanitizeHtmlForTelegram(input) {
// Replace paragraphs with new lines
let sanitized = input
// Convert H1 headers (# Header) to <b>Header</b><br/>
.replace(/^# (.*?)$/gm, '<b>$1</b><br/>')
// Convert H2 headers (## Header) to <b><i>Header</i></b><br/>
.replace(/^## (.*?)$/gm, '<b><i>$1</i></b><br/>')
// Convert H3 headers (### Header) to <i>Header</i><br/>
.replace(/^### (.*?)$/gm, '<i>$1</i><br/>')
// Convert bold (**text**) to <b>text</b>
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
// Convert italic (*text* or _text_) to <i>text</i>
.replace(/_(.*?)_/g, '<i>$1</i>')
// Underline -> <u>text</u> (using __text__ in MarkdownV2)
.replace(/__(.*?)__/g, '<u>$1</u>')
// Strikethrough -> <s>text</s> (using ~text~ in MarkdownV2)
.replace(/~(.*?)~/g, '<s>$1</s>')
// Convert unordered lists (* or -) to bullet points
.replace(/(?:\n|^)[*-]/g, `
• `)
// Convert ordered lists (1. 2. etc.) to numbers
.replace(/(?:\n|^)(\d+)\./g, `
$1. `)
// Convert preformatted blocks (```text```) to <pre>text</pre>
.replace(/```(.*?)```/gs, (_, code) => `<pre>${escapeCode(code)}</pre>`)
.replace(/`(.*?)`/gs, (_, code) => `<pre>${escapeCode(code)}</pre>`)
// Convert links [text](url) to <a href="url">text</a>
.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
// Convert newlines (two spaces or more) to <br/>
//.replace(/\n\n+/g, '<br/><br/>')
// Escape non-HTML < and >
//.replace(/</g, '<').replace(/>/g, '>');
return sanitized;
}
function sanitizeForVoice(input) {
//input = await formatEmojis(input)
// Replace paragraphs with new lines
let sanitized = input
// Convert H1 headers (# Header) to <b>Header</b><br/>
.replace(/^# (.*?)$/gm, '')
// Convert H2 headers (## Header) to <b><i>Header</i></b><br/>
.replace(/^## (.*?)$/gm, '')
// Convert H3 headers (### Header) to <i>Header</i><br/>
.replace(/^### (.*?)$/gm, '')
// Convert bold (**text**) to <b>text</b>
.replace(/\*\*(.*?)\*\*/g, '')
// Convert italic (*text* or _text_) to <i>text</i>
.replace(/_(.*?)_/g, '')
// Underline -> <u>text</u> (using __text__ in MarkdownV2)
.replace(/__(.*?)__/g, '')
// Strikethrough -> <s>text</s> (using ~text~ in MarkdownV2)
.replace(/~(.*?)~/g, '')
// Convert unordered lists (* or -) to bullet points
.replace(/(?:\n|^)[*-]/g, ``)
// Convert ordered lists (1. 2. etc.) to numbers
.replace(/(?:\n|^)(\d+)\./g, ``)
// Convert inline code (`code`) to <code>code</code>
.replace(/`(.*?)`/g, '')
// Convert preformatted blocks (```text```) to <pre>text</pre>
.replace(/```(.*?)```/gs, '')
// Convert links [text](url) to <a href="url">text</a>
.replace(/\[(.*?)\]\((.*?)\)/g, '')
// Convert newlines (two spaces or more) to <br/>
//.replace(/\n\n+/g, '<br/><br/>')
// Escape non-HTML < and >
//.replace(/</g, '<').replace(/>/g, '>');
return sanitized;
}
const sendMessage = (chatId, text, options = {}) => {
bot.sendMessage(chatId, text, options)
.then()
.catch((error) => {
console.error('Failed to send message:', error);
});
};
bot.onText(/\/start/, (msg, match) => {
const chatId = msg.chat.id;
const options = {
reply_markup: {
keyboard: [
[{ text: '🎲 Random', callback_data: 'random' }],
//[{ text: '😎 share contact with robot', request_contact: true }],
//[{ text: '🙌 share location with robot', request_location: true }]
]
}
};
sendMessage(chatId,
`
Welcome to @gideon_from_2024_bot Bot.
This is just a random bot.
Opps! 😎😎
You can choose any of these options
send /help for list of commands
use /ask or send a message containing "gideon" to chat with the AI
`
);
});
bot.onText(/\/music (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const input = msg.text.substring(7).trim()
await music(input, (result, song) => {
if(result === false || result === "No songs found")
return sendMessage(chatId,
`
<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
🎶
${result === false ? "Something went wrong" : result}
`, {parse_mode : "HTML"})
const audio = path.resolve(result)
bot.sendAudio(chatId, audio, {
caption : `<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>`,
thumbnail :"./thumbnail.jpg",
parse_mode : "HTML"
})
.then(() => {
fs.unlink(audio, (err) => {
if (err) {
return;
}
});
})
/**/
})
})
bot.onText(/\$voice/, async (msg, match) => {
const chatId = msg.chat.id;
let input = `${msg.text} ${msg.from.id === masterID ? "user" + msg.from.id : ""}`
const userID = msg.from.id
const history = await getConversationHistory(userID)
if(msg.reply_to_message && msg.reply_to_message?.text && msg.reply_to_message.from.id === botID)
history.push({
role: "model",
parts: [
{text: msg.reply_to_message.text},
],
}
)
const response = sanitizeForVoice(await chat(input, history))
const speech = new gTTS(response, "en-uk", false)
const inVoice = generate(9)
const outVoice = generate(9)
speech.save(`./${inVoice}.mp3`, async (err, result) => {
changeAudioSpeed(`./${inVoice}.mp3`, `./${outVoice}.mp3`, async () => {
try {
bot.sendVoice(chatId, `./${outVoice}.mp3`, {reply_to_message_id : msg.message_id})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
}
catch(err) {
sendMessage(chatId,
`<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
${sanitizeHtmlForTelegram(response)}
Could not send as a voice message
`, {parse_mode : "HTML"})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
}
finally {
fs.unlink(`./${inVoice}.mp3`, (err) => {
if (err) {
return;
}
});
fs.unlink(`./${outVoice}.mp3`, (err) => {
if (err) {
return;
}
});
}
})
})
});
bot.onText(/\/search (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const input = msg.text.substring(7).trim()
ddg.query(input, {
"useragent": "My duckduckgo app",
"no_redirects": "1",
"no_html": "0",
}, (err, data) => {
if(err)
return
let message = `<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a> 🔎\n\n\n`
if(data.RelatedTopics.length === 0)
message += "Could not find result"
message += data.AbstractText
data.RelatedTopics.forEach(element => {
message += element.FirstURL + "\n" ?? "" + "\n"
message += element.Text ?? "" + "\n"
message += "\n\n"
});
data.Results.forEach(element => {
message += element.FirstURL + "\n" ?? "" + "\n"
message += element.Text ?? "" + "\n"
message += "\n\n"
});
return sendMessage(chatId, message, {parse_mode : "HTML"})
})
});
bot.onText(/\/ignore/, async (msg, match) => {
const chatID = msg.chat.id;
if(msg.from.id !== masterID)
return sendMessage(chatID,
`
<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
You are not the Creator
`, {parse_mode : "HTML"}
);
else if(!msg?.reply_to_message?.from?.id || msg?.reply_to_message?.from?.id === masterID) {
return sendMessage(chatID, "You have to reply to the message of the person to be ignored")
}
else if(msg.reply_to_message.from.id === botID)
return
else {
const isMuted = await MutedChats.findOne({chatID : `${msg.reply_to_message.from.id}`})
if(!isMuted) {
await MutedChats.create({
chatID : `${msg.reply_to_message.from.id}`
})
}
return sendMessage(chatID,
`
<a href="tg://user?id=${msg.reply_to_message.from.id}">${msg.reply_to_message.from.first_name}</a>
Has been blacklisted
`, {parse_mode : "HTML"}
)
}
})
bot.onText(/\/canuse/, async (msg, match) => {
const chatID = msg.chat.id;
if(msg.from.id !== masterID)
return sendMessage(chatID,
`
<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
You are not the Creator
`, {parse_mode : "HTML"}
);
else if(!msg?.reply_to_message?.from?.id) {
return sendMessage(chatID, "You have to reply to the message of the person to be freed")
}
else if(msg.reply_to_message.from.id === botID)
return
else {
await MutedChats.deleteOne({chatID : `${msg.reply_to_message.from.id}`})
return sendMessage(chatID,
`
<a href="tg://user?id=${msg.reply_to_message.from.id}">${msg.reply_to_message.from.first_name}</a>
Has been whitelisted. Can now use the bot.
`, {parse_mode : "HTML"}
)
}
})
bot.onText(/\/url (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const link = decrypt(match[1])
if(link && isUrl(link)) {
return sendMessage(chatId,
`
Link from <a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
<a href="${link}" >Link</a>
` , {
reply_markup: {
inline_keyboard: [
[{ text: 'visit link', callback_data: 'link', url : link }],
]
}, parse_mode : "HTML", reply_to_message_id: msg.message_id
})
}
});
bot.onText(/\/ask (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const prompt = `${match[1].trim()} ${msg.from.id === masterID ? "user" + msg.from.id : ""}`
const response = await chat(prompt)
return sendMessage(chatId,
`<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
${sanitizeHtmlForTelegram(response)}
`, {parse_mode : "HTML"})
});
bot.on('message', async (msg) => {
const isMuted = await MutedChats.findOne({chatID : `${msg.from.id}`})
if(isMuted)
return 0
const chatId = msg.chat.id;
const ignoringCommands = ["/url","/ask","/search", "$voice", "/ignore", "/canuse", "/music"]
const triggerWords = [
"gideon",
// Greetings
/*
"hi",
"hello",
"hey",
"good morning",
"good afternoon",
"good evening",
"what's up",
"howdy",
"greetings",
"sup",
// Cry for Help
"help",
"please help",
"i need help",
"can someone help",
"emergency",
"i'm in trouble",
"i need assistance",
"help me",
"sos",
"save me",
// Common Questions/Statements
"anyone here?",
"is anyone there?",
"i'm new here",
"how are you?",
"hru",
"what's going on?",
"what's happening?",
"where is everyone?",
"can you help me?",
"i need advice",
// Expressions of Emotion
"i'm sad",
"i'm happy",
"i feel lonely",
"i'm angry",
"i'm scared",
"i'm excited",
"i'm confused",
"i'm lost",
"i'm frustrated",
"i need a friend"
*/
];
if(msg.text === undefined || msg.text === "/start" || msg.text === "/search" || ignoringCommands.some( c => msg.text.startsWith(c)) || msg.contact || msg.location)
return
else if(msg.text.toLowerCase() === "/help") {
return sendMessage(chatId,
`
Here is a list of all commands
/start - Start / View robots options
/search - Search google with the bot
/help - view all bot's commands
/ask - Use generative AI
$voice - for the ai to use voice messages
/music - /music <music name> to request a song
`
)
}
else if(msg.chat.type === "private") {
let input = `${msg.text} ${msg.from.id === masterID ? "user" + msg.from.id : ""}`
const userID = msg.from.id
const history = await getConversationHistory(userID)
const response = await chat(input, history)
try {
sendMessage(chatId, `${sanitizeHtmlForTelegram(response)}`, {reply_to_message_id : msg.message_id, parse_mode : "HTML"})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
return
}
catch(err) {
sendMessage(chatId,
`<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
${sanitizeHtmlForTelegram(response)}
`, {parse_mode : "HTML"})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
return
}
}
else if(triggerWords.some( word => msg.text.toLowerCase().includes(word)) || (msg.reply_to_message && msg.reply_to_message.from.id === botID)) {
let input = `${msg.text} ${msg.from.id === masterID ? "user" + msg.from.id : ""}`
const userID = msg.from.id
const history = await getConversationHistory(userID)
if(msg.reply_to_message && msg.reply_to_message?.text && msg.reply_to_message.from.id === botID)
history.push({
role: "model",
parts: [
{text: msg.reply_to_message.text},
],
}
)
const response = await chat(input, history)
try {
sendMessage(chatId, `${sanitizeHtmlForTelegram(response)}`, {reply_to_message_id : msg.message_id, parse_mode : "HTML"})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
return
}
catch(err) {
sendMessage(chatId,
`<a href="tg://user?id=${msg.from.id}">${msg.from.first_name}</a>
${sanitizeHtmlForTelegram(response)}
`, {parse_mode : "HTML"})
await addToConversationHistory(userID, input, "user")
await addToConversationHistory(userID, response, "model")
return
}
}
else {
/**/return
}
});
bot.on("contact", (msg) => {
const chatId = msg.chat.id;
sendMessage(chatId, 'Your number has been received');
})
bot.on("location", (msg) => {
const chatId = msg.chat.id;
sendMessage(chatId, "Wow, you are from : " + msg.location.latitude)
})
bot.on('inline_query', (query) => {
if(isUrl(query.query))
return bot.answerInlineQuery(query.id, [{
id: 0,
type : "article",
title: "🔗🔏 URL",
description: "You are sending an encrypted link :",
message_text: "/url " + encrypt(query.query),
url : query.query,
}]);
return bot.answerInlineQuery(query.id, []);
});
bot.on("polling_error", (err) => {
console.error(err)
})
console.info("Robot online")