qwen-api-proxy 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ import { logInfo, logError, logWarn } from '../logger/index.js';
2
+ import { TELEGRAM_BOT_TOKEN, TELEGRAM_USER_IDS } from '../config.js';
3
+ import { fetchWithTelegramProxy } from './proxy.js';
4
+
5
+ /**
6
+ * Отправляет уведомление в Telegram
7
+ * @param {string} message - Текст сообщения
8
+ * @returns {Promise<boolean>} - Успешность отправки
9
+ */
10
+ export async function sendTelegramNotification(message) {
11
+ if (!TELEGRAM_BOT_TOKEN || TELEGRAM_USER_IDS.length === 0) {
12
+ logWarn('Telegram уведомления не настроены (отсутствует токен или ID пользователей)');
13
+ return false;
14
+ }
15
+
16
+ const telegramUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
17
+
18
+ const notifications = TELEGRAM_USER_IDS.map(async (userId) => {
19
+ try {
20
+ const response = await fetchWithTelegramProxy(telegramUrl, {
21
+ method: 'POST',
22
+ headers: {
23
+ 'Content-Type': 'application/json'
24
+ },
25
+ body: JSON.stringify({
26
+ chat_id: userId,
27
+ text: message,
28
+ parse_mode: 'HTML'
29
+ })
30
+ });
31
+
32
+ if (response.ok) {
33
+ logInfo(`Telegram уведомление отправлено пользователю ${userId}`);
34
+ return true;
35
+ } else {
36
+ const errorBody = await response.text();
37
+ logError(`Ошибка отправки Telegram пользователю ${userId}: ${errorBody}`);
38
+ return false;
39
+ }
40
+ } catch (error) {
41
+ logError(`Ошибка при отправке Telegram уведомления пользователю ${userId}`, error);
42
+ return false;
43
+ }
44
+ });
45
+
46
+ const results = await Promise.all(notifications);
47
+ const successCount = results.filter(r => r).length;
48
+
49
+ if (successCount > 0) {
50
+ logInfo(`Telegram уведомления отправлены: ${successCount}/${TELEGRAM_USER_IDS.length} успешно`);
51
+ return true;
52
+ }
53
+
54
+ logError('Не удалось отправить Telegram уведомления ни одному пользователю');
55
+ return false;
56
+ }
57
+
58
+ /**
59
+ * Форматирует сообщение о проблемах с токенами
60
+ * @param {Array} tokens - Массив токенов
61
+ * @returns {string} - Форматированное сообщение
62
+ */
63
+ export function formatTokenExpiryMessage(tokens) {
64
+ const now = Date.now();
65
+
66
+ let message = '🚨 <b>FreeQwenApi - Проблема с токенами</b>\n\n';
67
+ message += '❌ <b>Все токены недоступны:</b>\n\n';
68
+
69
+ tokens.forEach((token, index) => {
70
+ const isInvalid = token.invalid === true;
71
+ const resetTime = token.resetAt ? new Date(token.resetAt).getTime() : null;
72
+ const isExpired = resetTime && resetTime > now;
73
+
74
+ message += `<b>${index + 1}. ${token.id}</b>\n`;
75
+
76
+ if (isInvalid) {
77
+ message += ' Статус: ❌ Недействителен\n';
78
+ } else if (isExpired) {
79
+ const hoursLeft = Math.ceil((resetTime - now) / 3600000);
80
+ message += ` Статус: ⏰ Истекает через ${hoursLeft} ч.\n`;
81
+ message += ` Сброс: ${new Date(resetTime).toLocaleString('ru-RU')}\n`;
82
+ } else {
83
+ message += ' Статус: ❓ Неизвестно\n';
84
+ }
85
+
86
+ message += '\n';
87
+ });
88
+
89
+ message += '⚠️ <b>Требуется действие:</b>\n';
90
+ message += ' • Перезапустите авторизацию для обновления токенов\n';
91
+ message += ' • Или дождитесь автоматического сброса лимитов\n';
92
+
93
+ return message;
94
+ }