-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
180 lines (151 loc) · 5.93 KB
/
Copy pathapp.js
File metadata and controls
180 lines (151 loc) · 5.93 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
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
require('dotenv').config();
const Centrifuge = require('centrifuge');
const WebSocket = require('ws');
global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// Функция для форматирования даты в UTC+3
function getTimestamp() {
const now = new Date();
// Устанавливаем UTC+3 (Московское время)
const utcOffset = 3; // UTC+3
const localTime = new Date(now.getTime() + (utcOffset * 60 * 60 * 1000));
const year = localTime.getUTCFullYear();
const month = String(localTime.getUTCMonth() + 1).padStart(2, '0');
const day = String(localTime.getUTCDate()).padStart(2, '0');
const hours = String(localTime.getUTCHours()).padStart(2, '0');
const minutes = String(localTime.getUTCMinutes()).padStart(2, '0');
const seconds = String(localTime.getUTCSeconds()).padStart(2, '0');
return `[${year}-${month}-${day} ${hours}:${minutes}:${seconds}]`;
}
// Переопределяем console.log
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
console.log = function(...args) {
originalLog(getTimestamp(), ...args);
};
console.error = function(...args) {
originalError(getTimestamp(), ...args);
};
console.warn = function(...args) {
originalWarn(getTimestamp(), ...args);
};
async function sendWebhook(data) {
const url = process.env.WEBHOOK_URL;
if (!url) {
console.error('URL-адрес Webhook не найден в переменных окружения');
return false;
}
try {
const lib = url.startsWith('https://') ? require('https') : require('http');
// Проверяем, что данные валидны
const jsonData = JSON.stringify(data);
if (!jsonData) {
console.error('Некорректные данные для отправки');
return false;
}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(jsonData)
},
timeout: 10000 // 10 секунд таймаут
};
return new Promise((resolve, reject) => {
const req = lib.request(url, options, (res) => {
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
console.log(`Webhook успешно отправлен (${res.statusCode})`);
resolve(true);
} else {
console.error(`Ошибка webhook: ${res.statusCode} - ${responseData}`);
reject(new Error(`HTTP ${res.statusCode}: ${responseData}`));
}
});
});
req.on('error', (error) => {
console.error('Ошибка отправки webhook:', error.message);
reject(error);
});
req.on('timeout', () => {
req.destroy();
console.error('Таймаут отправки webhook');
reject(new Error('Request timeout'));
});
req.write(jsonData);
req.end();
});
} catch (error) {
console.error('Ошибка при отправке webhook:', error);
return false;
}
}
// Функция для повторных попыток
async function sendWebhookWithRetry(data, maxRetries = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await sendWebhook(data);
if (result) return true;
} catch (error) {
console.error(`Попытка ${attempt} не удалась:`, error.message);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
console.error(`Не удалось отправить webhook после ${maxRetries} попыток`);
return false;
}
const access_token = process.env.DONATION_ALERTS_ACCESS_TOKEN;
const socket_token = process.env.DONATION_ALERTS_SOCKET_TOKEN;
const aUrl = 'wss://centrifugo.donationalerts.com/connection/websocket';
// Проверка наличия всех необходимых переменных
if (!access_token || !socket_token || !process.env.DONATION_ALERTS_USER_ID) {
console.error('Отсутствуют необходимые переменные окружения');
process.exit(1);
}
let centrifuge = new Centrifuge(aUrl, {
websocket: WebSocket,
subscribeEndpoint: 'https://www.donationalerts.com/api/v1/centrifuge/subscribe',
subscribeHeaders: {
'Authorization': `Bearer ${access_token}`
}
});
centrifuge.setToken(socket_token);
centrifuge.connect();
centrifuge.on('connect', async function(context) {
let clientID = context.client;
console.log('Вы подключились!', clientID);
centrifuge.subscribe('$alerts:donation_' + process.env.DONATION_ALERTS_USER_ID, async (message) => {
try {
console.log('Получен новый донат:', message.data);
// Проверяем данные
if (!message.data || typeof message.data !== 'object') {
console.error('Некорректные данные доната');
return;
}
// Отправляем с повторными попытками
const sent = await sendWebhookWithRetry(message.data);
if (sent) {
console.log('Донат успешно обработан');
} else {
console.error('Не удалось обработать донат');
}
} catch (error) {
console.error('Ошибка при обработке доната:', error);
}
});
});
centrifuge.on('disconnect', function(context) {
console.log('Вы отключились :(', context);
process.exit(1); // переподключимся через перезагрузку у PM2
});
// Обработка ошибок подключения
centrifuge.on('error', function(error) {
console.error('Ошибка центрифуги:', error);
process.exit(1);
});