-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageQueue.js
More file actions
36 lines (31 loc) · 1.12 KB
/
MessageQueue.js
File metadata and controls
36 lines (31 loc) · 1.12 KB
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
export class MessageQueue {
constructor(bot, logger) {
this.bot = bot;
this.logger = logger;
this.queues = new Map();
this.processing = new Map();
}
async add(chatId, message, options = {}) {
if (!this.queues.has(chatId)) {
this.queues.set(chatId, []);
this.processing.set(chatId, false);
}
this.queues.get(chatId).push({ message, options });
await this.process(chatId);
}
async process(chatId) {
if (this.processing.get(chatId)) return;
this.processing.set(chatId, true);
while (this.queues.get(chatId).length > 0) {
const { message, options } = this.queues.get(chatId)[0];
try {
await this.bot.telegram.sendMessage(chatId, message, options);
await new Promise(resolve => setTimeout(resolve, 50)); // Rate limit protection
} catch (error) {
this.logger.logError(`Failed to send message: ${error.message}`);
}
this.queues.get(chatId).shift();
}
this.processing.set(chatId, false);
}
}