diff --git a/api/chat.php b/api/chat.php new file mode 100644 index 0000000..dbe026c --- /dev/null +++ b/api/chat.php @@ -0,0 +1,64 @@ + "I didn't catch that. Could you repeat?"]); + exit; +} + +try { + // 1. Fetch Knowledge Base (FAQs) + $stmt = db()->query("SELECT keywords, answer FROM faqs"); + $faqs = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $knowledgeBase = "Here is the knowledge base for this website:\n\n"; + foreach ($faqs as $faq) { + $knowledgeBase .= "Q: " . $faq['keywords'] . "\nA: " . $faq['answer'] . "\n---\n"; + } + + // 2. Construct Prompt for AI + $systemPrompt = "You are a helpful, friendly AI assistant for this website. " . + "Use the provided Knowledge Base to answer user questions accurately. " . + "If the answer is found in the Knowledge Base, rephrase it naturally. " . + "If the answer is NOT in the Knowledge Base, use your general knowledge to help, " . + "but politely mention that you don't have specific information about that if it seems like a site-specific question. " . + "Keep answers concise and professional.\n\n" . + $knowledgeBase; + + // 3. Call AI API + $response = LocalAIApi::createResponse([ + 'model' => 'gpt-4o-mini', + 'input' => [ + ['role' => 'system', 'content' => $systemPrompt], + ['role' => 'user', 'content' => $message], + ] + ]); + + if (!empty($response['success'])) { + $aiReply = LocalAIApi::extractText($response); + + // 4. Save to Database + try { + $stmt = db()->prepare("INSERT INTO messages (user_message, ai_response) VALUES (?, ?)"); + $stmt->execute([$message, $aiReply]); + } catch (Exception $e) { + error_log("DB Save Error: " . $e->getMessage()); + // Continue even if save fails, so the user still gets a reply + } + + echo json_encode(['reply' => $aiReply]); + } else { + // Fallback if AI fails + error_log("AI Error: " . ($response['error'] ?? 'Unknown')); + echo json_encode(['reply' => "I'm having trouble connecting to my brain right now. Please try again later."]); + } + +} catch (Exception $e) { + error_log("Chat Error: " . $e->getMessage()); + echo json_encode(['reply' => "An internal error occurred."]); +} diff --git a/api/telegram_webhook.php b/api/telegram_webhook.php new file mode 100644 index 0000000..fa4899c --- /dev/null +++ b/api/telegram_webhook.php @@ -0,0 +1,91 @@ +query("SELECT setting_value FROM settings WHERE setting_key = 'telegram_token'"); +$token = $stmt->fetchColumn(); + +if (!$token) { + error_log("Telegram Error: No bot token found in settings."); + exit; +} + +function sendTelegramMessage($chatId, $text, $token) { + $url = "https://api.telegram.org/bot$token/sendMessage"; + $data = [ + 'chat_id' => $chatId, + 'text' => $text, + 'parse_mode' => 'Markdown' + ]; + + $options = [ + 'http' => [ + 'header' => "Content-type: application/x-www-form-urlencoded\r\n", + 'method' => 'POST', + 'content' => http_build_query($data), + ], + ]; + $context = stream_context_create($options); + return file_get_contents($url, false, $context); +} + +// Process with AI (Similar logic to api/chat.php) +try { + // 1. Fetch Knowledge Base + $stmt = db()->query("SELECT keywords, answer FROM faqs"); + $faqs = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $knowledgeBase = "Here is the knowledge base for this website:\n\n"; + foreach ($faqs as $faq) { + $knowledgeBase .= "Q: " . $faq['keywords'] . "\nA: " . $faq['answer'] . "\n---\n"; + } + + $systemPrompt = "You are a helpful AI assistant integrated with Telegram. " . + "Use the provided Knowledge Base to answer user questions. " . + "Keep answers concise for mobile reading. Use Markdown for formatting.\n\n" . + $knowledgeBase; + + // 2. Call AI + $response = LocalAIApi::createResponse([ + 'model' => 'gpt-4o-mini', + 'input' => [ + ['role' => 'system', 'content' => $systemPrompt], + ['role' => 'user', 'content' => $text], + ] + ]); + + if (!empty($response['success'])) { + $aiReply = LocalAIApi::extractText($response); + + // 3. Save History + try { + $stmt = db()->prepare("INSERT INTO messages (user_message, ai_response) VALUES (?, ?)"); + $stmt->execute(["[Telegram] " . $text, $aiReply]); + } catch (Exception $e) {} + + // 4. Send back to Telegram + sendTelegramMessage($chatId, $aiReply, $token); + } else { + sendTelegramMessage($chatId, "I'm sorry, I encountered an error processing your request.", $token); + } + +} catch (Exception $e) { + error_log("Telegram Webhook Error: " . $e->getMessage()); +} diff --git a/assets/js/main.js b/assets/js/main.js new file mode 100644 index 0000000..d349598 --- /dev/null +++ b/assets/js/main.js @@ -0,0 +1,39 @@ +document.addEventListener('DOMContentLoaded', () => { + const chatForm = document.getElementById('chat-form'); + const chatInput = document.getElementById('chat-input'); + const chatMessages = document.getElementById('chat-messages'); + + const appendMessage = (text, sender) => { + const msgDiv = document.createElement('div'); + msgDiv.classList.add('message', sender); + msgDiv.textContent = text; + chatMessages.appendChild(msgDiv); + chatMessages.scrollTop = chatMessages.scrollHeight; + }; + + chatForm.addEventListener('submit', async (e) => { + e.preventDefault(); + const message = chatInput.value.trim(); + if (!message) return; + + appendMessage(message, 'visitor'); + chatInput.value = ''; + + try { + const response = await fetch('api/chat.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message }) + }); + const data = await response.json(); + + // Artificial delay for realism + setTimeout(() => { + appendMessage(data.reply, 'bot'); + }, 500); + } catch (error) { + console.error('Error:', error); + appendMessage("Sorry, something went wrong. Please try again.", 'bot'); + } + }); +});