mirror of
https://github.com/orangecoding/fredy.git
synced 2026-06-16 12:31:07 +00:00
feat: telegram chat throttle cleanup
This commit is contained in:
@@ -7,6 +7,15 @@ const MAX_ENTITIES_PER_CHUNK = 8;
|
|||||||
const RATE_LIMIT_INTERVAL = 1000;
|
const RATE_LIMIT_INTERVAL = 1000;
|
||||||
const chatThrottleMap = new Map();
|
const chatThrottleMap = new Map();
|
||||||
|
|
||||||
|
function cleanupOldThrottles() {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [chatId, chatThrottle] of chatThrottleMap.entries()) {
|
||||||
|
if (now - chatThrottle.lastUsedAt > RATE_LIMIT_INTERVAL) {
|
||||||
|
chatThrottleMap.delete(chatId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a throttled async function for sending messages to a specific chat.
|
* Returns a throttled async function for sending messages to a specific chat.
|
||||||
* Telegram enforces a rate limit of 1 message per second per chat (chatId).
|
* Telegram enforces a rate limit of 1 message per second per chat (chatId).
|
||||||
@@ -15,11 +24,24 @@ const chatThrottleMap = new Map();
|
|||||||
* @param {Function} fn - The async function to throttle (should send the message).
|
* @param {Function} fn - The async function to throttle (should send the message).
|
||||||
* @returns {Function} Throttled async function for sending messages.
|
* @returns {Function} Throttled async function for sending messages.
|
||||||
*/
|
*/
|
||||||
function getThrottled(chatId, fn) {
|
function getThrottled(chatId, call) {
|
||||||
if (!chatThrottleMap.has(chatId)) {
|
cleanupOldThrottles();
|
||||||
chatThrottleMap.set(chatId, pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(fn));
|
|
||||||
|
const now = Date.now();
|
||||||
|
const chatThrottle = chatThrottleMap.get(chatId);
|
||||||
|
|
||||||
|
if (chatThrottle) {
|
||||||
|
chatThrottle.lastUsedAt = now;
|
||||||
|
return chatThrottle.throttled;
|
||||||
}
|
}
|
||||||
return chatThrottleMap.get(chatId);
|
|
||||||
|
// Create new throttled function
|
||||||
|
const newThrottle = {
|
||||||
|
lastUsedAt: now,
|
||||||
|
throttled: pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(call),
|
||||||
|
};
|
||||||
|
chatThrottleMap.set(chatId, newThrottle);
|
||||||
|
return newThrottle.throttled;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user