Spaces:
Running
Running
Download index.html from ANTONGAS44/what: direct link, hf CLI and curl.
- Browser
- Download file 40.9 kB
-
https://huggingface.co/spaces/ANTONGAS44/what/resolve/main/index.html
- Command line
-
hf download hf://spaces/ANTONGAS44/what/index.html
-
curl -L -o index.html https://huggingface.co/spaces/ANTONGAS44/what/resolve/main/index.html
40.9 kB
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>WhatsApp AutoResponder with DeepSeek</title> | |
| <script src="https://cdn.tailwindcss.com"></script> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> | |
| <script src="https://cdn.jsdelivr.net/npm/whatsapp-web.js@1.19.4/dist/index.min.js"></script> | |
| <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script> | |
| <style> | |
| .tab-content { display: none; } | |
| .tab-content.active { display: block; } | |
| .status-connected { background-color: #10B981; } | |
| .status-disconnected { background-color: #EF4444; } | |
| .status-waiting { background-color: #F59E0B; } | |
| .log-entry { animation: fadeIn 0.3s ease-in; } | |
| @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } | |
| #qr-code-container { | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| justify-content: center; | |
| padding: 20px; | |
| background: white; | |
| border-radius: 8px; | |
| margin-bottom: 20px; | |
| } | |
| #qr-code { | |
| width: 200px; | |
| height: 200px; | |
| margin: 10px 0; | |
| } | |
| .qr-instruction { | |
| text-align: center; | |
| margin-top: 10px; | |
| color: #666; | |
| font-size: 14px; | |
| } | |
| #browser-container { | |
| width: 100%; | |
| height: 500px; | |
| border: 1px solid #ddd; | |
| border-radius: 8px; | |
| overflow: hidden; | |
| display: none; | |
| } | |
| #browser-toolbar { | |
| background: #f3f4f6; | |
| padding: 8px; | |
| display: flex; | |
| align-items: center; | |
| border-bottom: 1px solid #ddd; | |
| } | |
| #browser-url { | |
| flex-grow: 1; | |
| margin: 0 10px; | |
| padding: 5px 10px; | |
| border: 1px solid #ddd; | |
| border-radius: 20px; | |
| outline: none; | |
| } | |
| #browser-content { | |
| width: 100%; | |
| height: calc(100% - 40px); | |
| border: none; | |
| } | |
| .browser-btn { | |
| background: #fff; | |
| border: 1px solid #ddd; | |
| border-radius: 50%; | |
| width: 30px; | |
| height: 30px; | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| cursor: pointer; | |
| margin: 0 2px; | |
| } | |
| .browser-btn:hover { | |
| background: #e5e7eb; | |
| } | |
| </style> | |
| </head> | |
| <body class="bg-gray-100 min-h-screen"> | |
| <div class="container mx-auto px-4 py-8"> | |
| <div class="bg-white rounded-xl shadow-lg overflow-hidden"> | |
| <div class="p-6 bg-green-600 text-white"> | |
| <h1 class="text-2xl font-bold flex items-center"> | |
| <i class="fab fa-whatsapp mr-3"></i> | |
| WhatsApp AutoResponder with DeepSeek AI | |
| </h1> | |
| <p class="mt-2 opacity-90">Автоматические ответы на сообщения WhatsApp через DeepSeek API</p> | |
| </div> | |
| <div class="p-6"> | |
| <div class="flex border-b border-gray-200"> | |
| <button class="tab-btn py-2 px-4 font-medium text-green-600 border-b-2 border-green-600" data-tab="control">Управление</button> | |
| <button class="tab-btn py-2 px-4 font-medium text-gray-500 hover:text-green-600" data-tab="settings">Настройки</button> | |
| <button class="tab-btn py-2 px-4 font-medium text-gray-500 hover:text-green-600" data-tab="logs">Логи</button> | |
| </div> | |
| <!-- Панель управления --> | |
| <div id="control" class="tab-content active mt-4"> | |
| <div class="grid grid-cols-1 md:grid-cols-3 gap-6"> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <h3 class="font-bold text-gray-800 mb-3 flex items-center"> | |
| <i class="fas fa-mobile-alt mr-2"></i> Авторизация WhatsApp | |
| </h3> | |
| <div class="flex flex-col items-center"> | |
| <div id="qr-code-container"> | |
| <div class="text-center font-medium mb-2">Отсканируйте QR-код в WhatsApp</div> | |
| <div id="qr-code"></div> | |
| <div class="qr-instruction"> | |
| Откройте WhatsApp на телефоне > Настройки > WhatsApp Web > Сканировать QR-код | |
| </div> | |
| </div> | |
| <button id="open-whatsapp-btn" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded flex items-center justify-center mt-4"> | |
| <i class="fas fa-external-link-alt mr-2"></i> Открыть WhatsApp Web | |
| </button> | |
| <div id="browser-container"> | |
| <div id="browser-toolbar"> | |
| <button class="browser-btn" id="browser-back"><i class="fas fa-arrow-left"></i></button> | |
| <button class="browser-btn" id="browser-forward"><i class="fas fa-arrow-right"></i></button> | |
| <button class="browser-btn" id="browser-refresh"><i class="fas fa-sync-alt"></i></button> | |
| <input type="text" id="browser-url" value="https://web.whatsapp.com" readonly> | |
| <button class="browser-btn" id="browser-close"><i class="fas fa-times"></i></button> | |
| </div> | |
| <iframe id="browser-content" src="about:blank"></iframe> | |
| </div> | |
| <button id="start-btn" class="w-full bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded flex items-center justify-center hidden"> | |
| <i class="fas fa-play mr-2"></i> Запустить | |
| </button> | |
| <button id="stop-btn" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-800 py-2 px-4 rounded mt-2 flex items-center justify-center" disabled> | |
| <i class="fas fa-stop mr-2"></i> Остановить | |
| </button> | |
| </div> | |
| </div> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <h3 class="font-bold text-gray-800 mb-3 flex items-center"> | |
| <i class="fas fa-robot mr-2"></i> Статус бота | |
| </h3> | |
| <div class="space-y-4"> | |
| <div class="flex items-center"> | |
| <div id="connection-status" class="w-3 h-3 rounded-full mr-2 status-disconnected"></div> | |
| <span>Соединение с WhatsApp: <span id="connection-status-text">Не активно</span></span> | |
| </div> | |
| <div class="flex items-center"> | |
| <div id="ai-status" class="w-3 h-3 rounded-full mr-2 status-disconnected"></div> | |
| <span>Соединение с DeepSeek: <span id="ai-status-text">Не активно</span></span> | |
| </div> | |
| <div class="pt-4"> | |
| <h4 class="font-medium text-gray-700 mb-2">Статистика:</h4> | |
| <div class="grid grid-cols-2 gap-2 text-sm"> | |
| <div class="bg-white p-2 rounded border"> | |
| <div class="text-gray-500">Обработано:</div> | |
| <div id="processed-count" class="font-bold">0</div> | |
| </div> | |
| <div class="bg-white p-2 rounded border"> | |
| <div class="text-gray-500">Ошибок:</div> | |
| <div id="error-count" class="font-bold">0</div> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <h3 class="font-bold text-gray-800 mb-3 flex items-center"> | |
| <i class="fas fa-bolt mr-2"></i> Быстрые действия | |
| </h3> | |
| <div class="space-y-3"> | |
| <button id="test-ai-btn" class="w-full bg-blue-100 hover:bg-blue-200 text-blue-800 py-2 px-4 rounded flex items-center justify-center"> | |
| <i class="fas fa-vial mr-2"></i> Тест DeepSeek API | |
| </button> | |
| <button id="clear-logs-btn" class="w-full bg-yellow-100 hover:bg-yellow-200 text-yellow-800 py-2 px-4 rounded flex items-center justify-center"> | |
| <i class="fas fa-trash-alt mr-2"></i> Очистить логи | |
| </button> | |
| <button id="export-logs-btn" class="w-full bg-purple-100 hover:bg-purple-200 text-purple-800 py-2 px-4 rounded flex items-center justify-center"> | |
| <i class="fas fa-file-export mr-2"></i> Экспорт логов | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Настройки --> | |
| <div id="settings" class="tab-content mt-4"> | |
| <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <h3 class="font-bold text-gray-800 mb-3 flex items-center"> | |
| <i class="fas fa-key mr-2"></i> Настройки API | |
| </h3> | |
| <div class="space-y-4"> | |
| <div> | |
| <label class="block text-sm font-medium text-gray-700 mb-1">DeepSeek API Key</label> | |
| <input type="password" id="api-key" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500" placeholder="Введите ваш API ключ"> | |
| </div> | |
| <div> | |
| <label class="block text-sm font-medium text-gray-700 mb-1">URL API</label> | |
| <input type="text" id="api-url" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500" placeholder="https://api.deepseek.com/v1" value="https://api.deepseek.com/v1"> | |
| </div> | |
| <div> | |
| <label class="block text-sm font-medium text-gray-700 mb-1">Модель</label> | |
| <select id="ai-model" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500"> | |
| <option value="deepseek-chat">deepseek-chat</option> | |
| <option value="deepseek-coder">deepseek-coder</option> | |
| </select> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <h3 class="font-bold text-gray-800 mb-3 flex items-center"> | |
| <i class="fas fa-cog mr-2"></i> Настройки бота | |
| </h3> | |
| <div class="space-y-4"> | |
| <div> | |
| <label class="block text-sm font-medium text-gray-700 mb-1">Промт для поведения</label> | |
| <textarea id="behavior-prompt" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500" placeholder="Например: Ты полезный ассистент, который отвечает кратко и вежливо...">Ты полезный ассистент, который отвечает на вопросы вежливо и информативно. Отвечай кратко, если не указано иное.</textarea> | |
| </div> | |
| <div> | |
| <label class="block text-sm font-medium text-gray-700 mb-1">Задержка между ответами (сек)</label> | |
| <input type="number" id="response-delay" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500" value="2" min="1"> | |
| </div> | |
| <div class="flex items-center"> | |
| <input type="checkbox" id="reply-to-groups" class="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"> | |
| <label for="reply-to-groups" class="ml-2 block text-sm text-gray-700">Отвечать в групповых чатах</label> | |
| </div> | |
| <div class="flex items-center"> | |
| <input type="checkbox" id="reply-to-self" class="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"> | |
| <label for="reply-to-self" class="ml-2 block text-sm text-gray-700">Отвечать на свои сообщения</label> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="mt-6 flex justify-end"> | |
| <button id="save-settings-btn" class="bg-green-600 hover:bg-green-700 text-white py-2 px-6 rounded-md flex items-center"> | |
| <i class="fas fa-save mr-2"></i> Сохранить настройки | |
| </button> | |
| </div> | |
| </div> | |
| <!-- Логи --> | |
| <div id="logs" class="tab-content mt-4"> | |
| <div class="bg-gray-50 p-4 rounded-lg"> | |
| <div class="flex justify-between items-center mb-3"> | |
| <h3 class="font-bold text-gray-800 flex items-center"> | |
| <i class="fas fa-terminal mr-2"></i> Журнал событий | |
| </h3> | |
| <div class="flex space-x-2"> | |
| <select id="log-level" class="text-sm border-gray-300 rounded"> | |
| <option value="all">Все события</option> | |
| <option value="info">Только информация</option> | |
| <option value="error">Только ошибки</option> | |
| </select> | |
| </div> | |
| </div> | |
| <div id="log-container" class="bg-black text-green-400 font-mono text-sm p-3 rounded-md h-96 overflow-y-auto"> | |
| <div class="log-entry">Система запущена. Готов к работе.</div> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-between items-center"> | |
| <div class="text-sm text-gray-500"> | |
| <i class="far fa-clock mr-1"></i> <span id="current-date"></span> | |
| </div> | |
| <div class="text-sm text-gray-500"> | |
| Версия: 1.0.0 | <a href="#" class="text-green-600 hover:underline">Документация</a> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| // Состояние приложения | |
| const state = { | |
| isRunning: false, | |
| isConnected: false, | |
| isAiConnected: false, | |
| processedCount: 0, | |
| errorCount: 0, | |
| client: null, | |
| settings: { | |
| apiKey: '', | |
| apiUrl: 'https://api.deepseek.com/v1', | |
| aiModel: 'deepseek-chat', | |
| behaviorPrompt: 'Ты полезный ассистент, который отвечает на вопросы вежливо и информативно. Отвечай кратко, если не указано иное.', | |
| responseDelay: 2, | |
| replyToGroups: false, | |
| replyToSelf: false | |
| } | |
| }; | |
| // Элементы DOM | |
| const elements = { | |
| startBtn: document.getElementById('start-btn'), | |
| stopBtn: document.getElementById('stop-btn'), | |
| testAiBtn: document.getElementById('test-ai-btn'), | |
| clearLogsBtn: document.getElementById('clear-logs-btn'), | |
| exportLogsBtn: document.getElementById('export-logs-btn'), | |
| saveSettingsBtn: document.getElementById('save-settings-btn'), | |
| connectionStatus: document.getElementById('connection-status'), | |
| connectionStatusText: document.getElementById('connection-status-text'), | |
| aiStatus: document.getElementById('ai-status'), | |
| aiStatusText: document.getElementById('ai-status-text'), | |
| processedCount: document.getElementById('processed-count'), | |
| errorCount: document.getElementById('error-count'), | |
| logContainer: document.getElementById('log-container'), | |
| logLevel: document.getElementById('log-level'), | |
| apiKey: document.getElementById('api-key'), | |
| apiUrl: document.getElementById('api-url'), | |
| aiModel: document.getElementById('ai-model'), | |
| behaviorPrompt: document.getElementById('behavior-prompt'), | |
| responseDelay: document.getElementById('response-delay'), | |
| replyToGroups: document.getElementById('reply-to-groups'), | |
| replyToSelf: document.getElementById('reply-to-self'), | |
| qrCodeContainer: document.getElementById('qr-code-container'), | |
| qrCode: document.getElementById('qr-code'), | |
| openWhatsappBtn: document.getElementById('open-whatsapp-btn'), | |
| browserContainer: document.getElementById('browser-container'), | |
| browserContent: document.getElementById('browser-content'), | |
| browserUrl: document.getElementById('browser-url'), | |
| browserBack: document.getElementById('browser-back'), | |
| browserForward: document.getElementById('browser-forward'), | |
| browserRefresh: document.getElementById('browser-refresh'), | |
| browserClose: document.getElementById('browser-close') | |
| }; | |
| // Инициализация приложения | |
| function initApp() { | |
| // Установка текущей даты | |
| document.getElementById('current-date').textContent = new Date().toLocaleDateString('ru-RU'); | |
| // Загрузка сохраненных настроек | |
| loadSettings(); | |
| // Настройка обработчиков событий | |
| setupEventListeners(); | |
| // Настройка вкладок | |
| setupTabs(); | |
| // Настройка мини-браузера | |
| setupBrowser(); | |
| // Автоматическая инициализация WhatsApp клиента | |
| initializeWhatsAppClient(); | |
| } | |
| // Настройка мини-браузера | |
| function setupBrowser() { | |
| // Открытие WhatsApp Web в мини-браузере | |
| elements.openWhatsappBtn.addEventListener('click', () => { | |
| elements.qrCodeContainer.style.display = 'none'; | |
| elements.browserContainer.style.display = 'block'; | |
| elements.browserContent.src = 'https://web.whatsapp.com'; | |
| addLog('Открыт WhatsApp Web в мини-браузере', 'info'); | |
| }); | |
| // Управление мини-браузером | |
| elements.browserBack.addEventListener('click', () => { | |
| elements.browserContent.contentWindow.history.back(); | |
| }); | |
| elements.browserForward.addEventListener('click', () => { | |
| elements.browserContent.contentWindow.history.forward(); | |
| }); | |
| elements.browserRefresh.addEventListener('click', () => { | |
| elements.browserContent.contentWindow.location.reload(); | |
| }); | |
| elements.browserClose.addEventListener('click', () => { | |
| elements.browserContainer.style.display = 'none'; | |
| elements.qrCodeContainer.style.display = 'flex'; | |
| addLog('Мини-браузер закрыт', 'info'); | |
| }); | |
| // Обновление URL в адресной строке | |
| elements.browserContent.addEventListener('load', () => { | |
| try { | |
| elements.browserUrl.value = elements.browserContent.contentWindow.location.href; | |
| } catch (e) { | |
| // Игнорируем ошибки CORS | |
| } | |
| }); | |
| } | |
| // Загрузка настроек из localStorage | |
| function loadSettings() { | |
| const savedSettings = localStorage.getItem('whatsappBotSettings'); | |
| if (savedSettings) { | |
| state.settings = JSON.parse(savedSettings); | |
| // Применение настроек к UI | |
| elements.apiKey.value = state.settings.apiKey; | |
| elements.apiUrl.value = state.settings.apiUrl; | |
| elements.aiModel.value = state.settings.aiModel; | |
| elements.behaviorPrompt.value = state.settings.behaviorPrompt; | |
| elements.responseDelay.value = state.settings.responseDelay; | |
| elements.replyToGroups.checked = state.settings.replyToGroups; | |
| elements.replyToSelf.checked = state.settings.replyToSelf; | |
| } | |
| } | |
| // Сохранение настроек в localStorage | |
| function saveSettings() { | |
| state.settings = { | |
| apiKey: elements.apiKey.value, | |
| apiUrl: elements.apiUrl.value, | |
| aiModel: elements.aiModel.value, | |
| behaviorPrompt: elements.behaviorPrompt.value, | |
| responseDelay: parseInt(elements.responseDelay.value), | |
| replyToGroups: elements.replyToGroups.checked, | |
| replyToSelf: elements.replyToSelf.checked | |
| }; | |
| localStorage.setItem('whatsappBotSettings', JSON.stringify(state.settings)); | |
| addLog('Настройки успешно сохранены', 'info'); | |
| } | |
| // Настройка обработчиков событий | |
| function setupEventListeners() { | |
| // Кнопки управления | |
| elements.startBtn.addEventListener('click', startBot); | |
| elements.stopBtn.addEventListener('click', stopBot); | |
| elements.testAiBtn.addEventListener('click', testAiConnection); | |
| elements.clearLogsBtn.addEventListener('click', clearLogs); | |
| elements.exportLogsBtn.addEventListener('click', exportLogs); | |
| elements.saveSettingsBtn.addEventListener('click', saveSettings); | |
| // Фильтр логов | |
| elements.logLevel.addEventListener('change', filterLogs); | |
| } | |
| // Настройка вкладок | |
| function setupTabs() { | |
| document.querySelectorAll('.tab-btn').forEach(btn => { | |
| btn.addEventListener('click', function() { | |
| // Убираем активный класс у всех кнопок и контента | |
| document.querySelectorAll('.tab-btn').forEach(b => { | |
| b.classList.remove('border-b-2', 'border-green-600', 'text-green-600'); | |
| b.classList.add('text-gray-500'); | |
| }); | |
| document.querySelectorAll('.tab-content').forEach(content => { | |
| content.classList.remove('active'); | |
| }); | |
| // Добавляем активный класс к текущей кнопке и контенту | |
| this.classList.add('border-b-2', 'border-green-600', 'text-green-600'); | |
| this.classList.remove('text-gray-500'); | |
| const tabId = this.getAttribute('data-tab'); | |
| document.getElementById(tabId).classList.add('active'); | |
| }); | |
| }); | |
| } | |
| // Инициализация WhatsApp клиента | |
| function initializeWhatsAppClient() { | |
| if (!state.settings.apiKey) { | |
| addLog('Ошибка: Не указан API ключ DeepSeek', 'error'); | |
| return; | |
| } | |
| addLog('Инициализация WhatsApp Web...', 'info'); | |
| // Инициализация WhatsApp клиента | |
| const { Client } = window.WhatsappWeb; | |
| state.client = new Client({ | |
| puppeteer: { | |
| headless: true, | |
| }, | |
| authStrategy: new window.WhatsappWeb.LocalAuth({ | |
| clientId: 'whatsapp-bot-client' | |
| }) | |
| }); | |
| // Генерация QR-кода | |
| state.client.on('qr', (qr) => { | |
| addLog('QR-код сгенерирован. Отсканируйте его в приложении WhatsApp.', 'info'); | |
| // Очищаем предыдущий QR-код | |
| elements.qrCode.innerHTML = ''; | |
| // Генерируем QR-код с помощью библиотеки QRCode.js | |
| QRCode.toCanvas(elements.qrCode, qr, { | |
| width: 200, | |
| margin: 0, | |
| color: { | |
| dark: '#000000', | |
| light: '#ffffff' | |
| } | |
| }, (error) => { | |
| if (error) { | |
| addLog('Ошибка генерации QR-кода: ' + error.message, 'error'); | |
| // Альтернативный способ - ссылка на официальный QR-код | |
| elements.qrCode.innerHTML = ` | |
| <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qr)}" | |
| alt="WhatsApp QR Code" class="mx-auto"> | |
| `; | |
| } | |
| }); | |
| // Показываем кнопку запуска | |
| elements.startBtn.classList.remove('hidden'); | |
| }); | |
| // При успешном подключении | |
| state.client.on('ready', () => { | |
| state.isConnected = true; | |
| state.isRunning = true; | |
| updateUI(); | |
| addLog('Успешное подключение к WhatsApp Web', 'info'); | |
| // Скрываем QR-код и мини-браузер после успешного подключения | |
| elements.qrCodeContainer.style.display = 'none'; | |
| elements.browserContainer.style.display = 'none'; | |
| elements.startBtn.classList.add('hidden'); | |
| // Проверка подключения к DeepSeek | |
| testAiConnection(); | |
| // Настройка обработки сообщений | |
| setupMessageHandler(); | |
| }); | |
| // При ошибке подключения | |
| state.client.on('auth_failure', () => { | |
| addLog('Ошибка аутентификации WhatsApp', 'error'); | |
| stopBot(); | |
| }); | |
| // При отключении | |
| state.client.on('disconnected', () => { | |
| addLog('Отключено от WhatsApp Web', 'info'); | |
| stopBot(); | |
| }); | |
| // Запуск клиента | |
| state.client.initialize().catch(err => { | |
| addLog('Ошибка инициализации WhatsApp: ' + err.message, 'error'); | |
| stopBot(); | |
| }); | |
| } | |
| // Запуск бота | |
| function startBot() { | |
| if (!state.client) { | |
| initializeWhatsAppClient(); | |
| } | |
| state.isRunning = true; | |
| updateUI(); | |
| addLog('Бот запущен', 'info'); | |
| } | |
| // Остановка бота | |
| async function stopBot() { | |
| if (state.client) { | |
| try { | |
| await state.client.destroy(); | |
| addLog('WhatsApp клиент остановлен', 'info'); | |
| } catch (err) { | |
| addLog('Ошибка при остановке WhatsApp клиента: ' + err.message, 'error'); | |
| } | |
| state.client = null; | |
| } | |
| state.isRunning = false; | |
| state.isConnected = false; | |
| state.isAiConnected = false; | |
| updateUI(); | |
| addLog('Бот остановлен', 'info'); | |
| // Показываем QR-код снова | |
| elements.qrCodeContainer.style.display = 'flex'; | |
| elements.browserContainer.style.display = 'none'; | |
| // Перезапускаем клиент для нового QR-кода | |
| initializeWhatsAppClient(); | |
| } | |
| // Настройка обработчика сообщений | |
| function setupMessageHandler() { | |
| state.client.on('message', async msg => { | |
| // Проверка настроек (отвечать ли в группах/на свои сообщения) | |
| const isGroup = msg.from.includes('@g.us'); | |
| const isFromMe = msg.fromMe; | |
| if ((isGroup && !state.settings.replyToGroups) || | |
| (isFromMe && !state.settings.replyToSelf)) { | |
| addLog(`Сообщение пропущено по настройкам: ${msg.body}`, 'info'); | |
| return; | |
| } | |
| addLog(`Новое сообщение от ${msg.from}: ${msg.body}`, 'info'); | |
| try { | |
| // Генерация ответа через DeepSeek API | |
| const response = await generateAiResponse(msg.body); | |
| // Отправка ответа с задержкой | |
| setTimeout(async () => { | |
| await msg.reply(response); | |
| addLog(`Отправлен ответ: ${response}`, 'info'); | |
| state.processedCount++; | |
| updateUI(); | |
| }, state.settings.responseDelay * 1000); | |
| } catch (err) { | |
| addLog('Ошибка обработки сообщения: ' + err.message, 'error'); | |
| state.errorCount++; | |
| updateUI(); | |
| } | |
| }); | |
| } | |
| // Генерация ответа через DeepSeek API | |
| async function generateAiResponse(message) { | |
| if (!state.settings.apiKey) { | |
| throw new Error('API ключ не установлен'); | |
| } | |
| const prompt = `${state.settings.behaviorPrompt}\n\nПользователь: ${message}\nАссистент:`; | |
| try { | |
| const response = await fetch(state.settings.apiUrl + '/chat/completions', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${state.settings.apiKey}` | |
| }, | |
| body: JSON.stringify({ | |
| model: state.settings.aiModel, | |
| messages: [ | |
| { | |
| role: "user", | |
| content: prompt | |
| } | |
| ], | |
| temperature: 0.7, | |
| max_tokens: 1000 | |
| }) | |
| }); | |
| if (!response.ok) { | |
| throw new Error(`API ошибка: ${response.status}`); | |
| } | |
| const data = await response.json(); | |
| return data.choices[0].message.content; | |
| } catch (err) { | |
| throw new Error('Ошибка запроса к DeepSeek API: ' + err.message); | |
| } | |
| } | |
| // Тестирование подключения к DeepSeek API | |
| async function testAiConnection() { | |
| if (!state.settings.apiKey) { | |
| addLog('Ошибка: Не указан API ключ DeepSeek', 'error'); | |
| return; | |
| } | |
| addLog('Тестирование подключения к DeepSeek API...', 'info'); | |
| try { | |
| const testMessage = "Привет! Это тестовое сообщение. Ответь просто 'OK'"; | |
| const response = await generateAiResponse(testMessage); | |
| state.isAiConnected = true; | |
| updateUI(); | |
| addLog(`Подключение к DeepSeek API успешно. Ответ: ${response}`, 'info'); | |
| } catch (err) { | |
| state.isAiConnected = false; | |
| updateUI(); | |
| addLog('Ошибка подключения к DeepSeek API: ' + err.message, 'error'); | |
| } | |
| } | |
| // Добавление записи в лог | |
| function addLog(message, level = 'info') { | |
| const logEntry = document.createElement('div'); | |
| logEntry.className = `log-entry text-${level === 'error' ? 'red' : 'green'}-400`; | |
| const timestamp = new Date().toLocaleTimeString(); | |
| logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${message}`; | |
| elements.logContainer.appendChild(logEntry); | |
| elements.logContainer.scrollTop = elements.logContainer.scrollHeight; | |
| if (level === 'error') { | |
| state.errorCount++; | |
| updateUI(); | |
| } | |
| } | |
| // Фильтрация логов | |
| function filterLogs() { | |
| const level = elements.logLevel.value; | |
| const entries = elements.logContainer.querySelectorAll('.log-entry'); | |
| entries.forEach(entry => { | |
| const isError = entry.classList.contains('text-red-400'); | |
| const isInfo = entry.classList.contains('text-green-400'); | |
| if (level === 'all' || | |
| (level === 'info' && isInfo) || | |
| (level === 'error' && isError)) { | |
| entry.style.display = 'block'; | |
| } else { | |
| entry.style.display = 'none'; | |
| } | |
| }); | |
| } | |
| // Очистка логов | |
| function clearLogs() { | |
| elements.logContainer.innerHTML = ''; | |
| addLog('Логи очищены', 'info'); | |
| } | |
| // Экспорт логов | |
| function exportLogs() { | |
| const entries = elements.logContainer.querySelectorAll('.log-entry'); | |
| let logText = 'WhatsApp AutoResponder Logs\n=======================\n\n'; | |
| entries.forEach(entry => { | |
| if (entry.style.display !== 'none') { | |
| logText += entry.textContent + '\n'; | |
| } | |
| }); | |
| const blob = new Blob([logText], { type: 'text/plain' }); | |
| const url = URL.createObjectURL(blob); | |
| const a = document.createElement('a'); | |
| a.href = url; | |
| a.download = `whatsapp-bot-logs-${new Date().toISOString().slice(0, 10)}.txt`; | |
| document.body.appendChild(a); | |
| a.click(); | |
| document.body.removeChild(a); | |
| URL.revokeObjectURL(url); | |
| addLog('Логи экспортированы в файл', 'info'); | |
| } | |
| // Обновление UI в соответствии с состоянием | |
| function updateUI() { | |
| // Кнопки | |
| elements.startBtn.disabled = state.isRunning; | |
| elements.stopBtn.disabled = !state.isRunning; | |
| // Статус подключения | |
| elements.connectionStatus.className = `w-3 h-3 rounded-full mr-2 ${state.isConnected ? 'status-connected' : 'status-disconnected'}`; | |
| elements.connectionStatusText.textContent = state.isConnected ? 'Активно' : 'Не активно'; | |
| // Статус AI | |
| elements.aiStatus.className = `w-3 h-3 rounded-full mr-2 ${state.isAiConnected ? 'status-connected' : 'status-disconnected'}`; | |
| elements.aiStatusText.textContent = state.isAiConnected ? 'Активно' : 'Не активно'; | |
| // Счетчики | |
| elements.processedCount.textContent = state.processedCount; | |
| elements.errorCount.textContent = state.errorCount; | |
| } | |
| // Инициализация приложения при загрузке страницы | |
| window.addEventListener('DOMContentLoaded', initApp); | |
| </script> | |
| <p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=ANTONGAS44/what" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body> | |
| </html> |