From 0b25a1d9323c1ddedce8a3edae42922ffecf9995 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 10 Nov 2026 17:05:54 +0300 Subject: [PATCH] Updated telegram && whatsapp api links --- balancer-example.js | 146 ++++++++++++++++++++++++++++++++++++ src/api/telegramManagers.ts | 2 +- src/api/whatsappManagers.ts | 2 +- 3 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 balancer-example.js diff --git a/balancer-example.js b/balancer-example.js new file mode 100644 index 0000000..b7a6ad6 --- /dev/null +++ b/balancer-example.js @@ -0,0 +1,146 @@ +const BALANCER_URL = 'https://72.56.235.246.nip.io/balancer/api/balancer/send'; +const BALANCER_PUBLIC = '68929830b9a07e7c6fa1d4bdfbcafe798a50de4da2969e743fee690dfaec3fb4'; +const BALANCER_PRIVATE = '89bab1c15544e7bb667b773df786e65f9aed0bf173a84e66e2a88aec3f0014d89a289807c34f71c876b79f67997c9ac281ffd19d00fe8582ebcda97660bddaa3'; +const BITRIX_WEBHOOK = 'https://thebest.bitrix24.ru/rest/{USER}/{METHOD_ID}/'; + +function generateBalancerSignature_(timestampStr) { + const message = `${BALANCER_PUBLIC}:${timestampStr}`; + const signature = Utilities.computeHmacSha256Signature(message, BALANCER_PRIVATE); + return signature.map(b => ('0' + (b & 0xFF).toString(16)).slice(-2)).join(''); +} + +// ── Балансировщик: одиночный запрос +// Используется для get, update, add, delete и любых методов +// которые не возвращают next (не список). +function balancerPost_(method, body) { + const timestamp = Math.floor(Date.now() / 1000).toString(); + + const payload = { + url: BITRIX_WEBHOOK + method + '.json', + method: 'POST', + body: body || {}, + }; + + const options = { + method: 'post', + contentType: 'application/json', + headers: { + 'X-Timestamp': timestamp, + 'X-Signature': generateBalancerSignature_(timestamp), + }, + payload: JSON.stringify(payload), + muteHttpExceptions: true, + }; + + let attempt = 0; + const maxRetries = 5; + const baseRetryMs = 1000; + const limitWaitMs = 5000; + + while (attempt <= maxRetries) { + let res, data; + try { + res = UrlFetchApp.fetch(BALANCER_URL, options); + const httpCode = res.getResponseCode(); + const rawText = res.getContentText(); + + if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`); + if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`); + if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`); + + data = JSON.parse(rawText); + } catch (e) { + attempt++; + const wait = baseRetryMs * attempt; + Logger.log(`⚠️ balancerPost_ сетевая ошибка (попытка ${attempt}): ${e} — ждём ${wait}ms`); + if (attempt > maxRetries) throw new Error(`Сетевая ошибка после ${maxRetries} попыток: ${e}`); + Utilities.sleep(wait); + continue; + } + + if (res.getResponseCode() !== 200) { + attempt++; + const wait = baseRetryMs * attempt; + Logger.log(`🔴 balancerPost_ HTTP ${res.getResponseCode()} (попытка ${attempt}) — ждём ${wait}ms`); + if (attempt > maxRetries) throw new Error(`balancer HTTP ${res.getResponseCode()}`); + Utilities.sleep(wait); + continue; + } + + const bitrixBody = data?.body; + const errCode = bitrixBody?.error; + + if (errCode === 'QUERY_LIMIT_EXCEEDED') { + attempt++; + const wait = limitWaitMs * attempt; + Logger.log(`🚦 QUERY_LIMIT_EXCEEDED (попытка ${attempt}) — ждём ${wait}ms`); + if (attempt > maxRetries) throw new Error('QUERY_LIMIT_EXCEEDED: превышен лимит'); + Utilities.sleep(wait); + continue; + } + + if (errCode === 'INTERNAL_SERVER_ERROR') { + attempt++; + const wait = baseRetryMs * attempt; + Logger.log(`🔴 INTERNAL_SERVER_ERROR (попытка ${attempt}) — ждём ${wait}ms`); + if (attempt > maxRetries) throw new Error('INTERNAL_SERVER_ERROR после нескольких попыток'); + Utilities.sleep(wait); + continue; + } + + if (errCode) { + throw new Error(`Битрикс API [${method}]: ${errCode} — ${bitrixBody?.error_description || ''}`); + } + + Logger.log(`🟢 balancerPost_ [${method}] OK`); + + return bitrixBody; + } + + throw new Error('balancerPost_: исчерпаны все попытки'); +} + +// Выполняет рекуррентный запрос через балансировщик. +// Балансировщик сам крутит пагинацию и возвращает все записи одним массивом. +function balancerRecurrentPost_(method, body, resultKey) { + const timestamp = Math.floor(Date.now() / 1000).toString(); + + const payload = { + url: BITRIX_WEBHOOK + method + '.json', + method: 'POST', + is_recurrent: true, + result_key: resultKey || null, + body: body, + }; + + const options = { + method: 'post', + contentType: 'application/json', + headers: { + 'X-Timestamp': timestamp, + 'X-Signature': generateBalancerSignature_(timestamp), + }, + payload: JSON.stringify(payload), + muteHttpExceptions: true, + }; + + const sig = generateBalancerSignature_(timestamp); + Logger.log('Timestamp: ' + timestamp); + Logger.log('Signature: ' + sig); + Logger.log('Message: ' + BALANCER_PUBLIC + ':' + timestamp); + + res = UrlFetchApp.fetch(BALANCER_URL, options); + const httpCode = res.getResponseCode(); + const rawText = res.getContentText(); + + if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`); + if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`); + if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`); + + data = JSON.parse(rawText); + + if (data.error) throw new Error(`balancer error [${method}]: ${JSON.stringify(data.error)}`); + + // Возвращает { body: [...], total_fetched: N, quota_left: N } + return data.body || []; +} diff --git a/src/api/telegramManagers.ts b/src/api/telegramManagers.ts index 8324c04..4de58b9 100644 --- a/src/api/telegramManagers.ts +++ b/src/api/telegramManagers.ts @@ -2,7 +2,7 @@ import axios from 'axios' // Изолированный клиент ТОЛЬКО для сервера менеджеров const managerApiClient = axios.create({ - baseURL: 'https://37.252.5.229.nip.io/tg-api/api', + baseURL: 'https://38.180.230.177.nip.io/tg-api/api', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'supersecretkey', diff --git a/src/api/whatsappManagers.ts b/src/api/whatsappManagers.ts index f898e16..0c48840 100644 --- a/src/api/whatsappManagers.ts +++ b/src/api/whatsappManagers.ts @@ -1,7 +1,7 @@ import axios from 'axios' const waApiClient = axios.create({ - baseURL: 'https://37.252.5.229.nip.io/wa-api/api', + baseURL: 'https://38.180.230.177.nip.io/wa-api/api', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'supersecretkey',