-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdmQueue.js
More file actions
70 lines (62 loc) · 2.22 KB
/
Copy pathdmQueue.js
File metadata and controls
70 lines (62 loc) · 2.22 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
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
// dmQueue.js (corrigido — não acessa db direto)
const { getNextDM, deleteDM, resetDmQueueSequence } = require('./database');
const { EmbedBuilder, ActionRowBuilder } = require('discord.js');
let _client; // aqui guardaremos o client após chamar init()
let isProcessing = false;
module.exports.init = (clientInstance) => {
_client = clientInstance;
};
async function sendOneDM(job) {
const { id, user_id, embed_json, row_json } = job;
try {
const embedObj = EmbedBuilder.from(JSON.parse(embed_json));
const rowObj = ActionRowBuilder.from(JSON.parse(row_json));
const payload = { embeds: [embedObj] };
if (rowObj.components && rowObj.components.length) payload.components = [rowObj];
const user = await _client.users.fetch(user_id);
await user.send(payload);
} catch (err) {
console.warn(`⚠️ DM failure to ${user_id}: ${err.message}`);
} finally {
// garante que a remoção da fila também fica centralizada no database.js
try { deleteDM(id); } catch (e) { console.warn('deleteDM failed:', e); }
}
}
async function processDMQueue() {
if (!_client) {
console.warn('⚠️ dmQueue not initialized with client yet');
return;
}
if (isProcessing) return;
isProcessing = true;
const batchSize = 1;
let jobs;
try {
do {
jobs = [];
for (let i = 0; i < batchSize; i++) {
const job = getNextDM();
if (!job) break;
jobs.push(job);
}
for (const job of jobs) {
await sendOneDM(job);
await new Promise(res => setTimeout(res, 2000));
}
if (jobs.length === batchSize) {
await new Promise(res => setTimeout(res, 2000));
}
} while (jobs.length === batchSize);
} catch (err) {
console.error('❌ dmQueue processing error:', err);
} finally {
// chama função no database.js para realizar o reset da sequência (se aplicável)
try { resetDmQueueSequence(); } catch (e) { /* swallow */ }
isProcessing = false;
}
}
// dispara automaticamente
processDMQueue();
setInterval(processDMQueue, 5 * 1000);
// exporta também o processDMQueue caso queira invocar manualmente
module.exports.processDMQueue = processDMQueue;