cerebro-vip INEMA.CLUB
inícioINEMA.MAKE

Tópico sobre construção de um chatbot web com autenticação por email…

INEMA.MAKE · 2025-05-01 · ~8 min · ver no Telegram ↗

INEMA

youtube.com/watch ↗

huggingface.co ↗

huggingface.co ↗

huggingface.co ↗

enzostvs-deepsite.hf.space ↗

} else if (jsonData.message) { responseText = jsonData.message; } else if (jsonData.choices && jsonData.choices[0] && jsonData.choices[0].message) { responseText = jsonData.choices[0].message.content; } else { // Fallback to stringify if no known format responseText = JSON.stringify(jsonData, null, 2); }

                    addMessage('system', responseText);
                    return;
                }
            } catch (jsonError) {
                console.log("Response is not JSON, trying as text");
            }

            // If JSON parsing failed, try as plain text
            try {
                const textData = await responseClone.text();
                addMessage('system', textData || "Recebi uma resposta vazia do servidor.");
            } catch (textError) {
                console.error("Error reading response as text:", textError);
                addMessage('system', `Erro ao ler a resposta do servidor: ${textError.message}`);
            }
        } catch (error) {
            console.error('Error:', error);
            addMessage('system', `Desculpe, houve um erro ao processar sua solicitação: ${error.message}`);
        } finally {
            typingIndicator.classList.add('hidden');
            userInput.disabled = false;
            sendButton.disabled = false;
            isWaitingResponse = false;
            userInput.focus();
        }
    }

    function addMessage(sender, text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message-transition fade-in flex ' + (sender === 'user' ? 'justify-end' : 'justify-start');

        const bubble = document.createElement('div');
        bubble.className = sender === 'user' 
            ? 'max-w-xs sm:max-w-md md:max-w-lg bg-blue-600 text-white rounded-xl p-3'
            : 'max-w-xs sm:max-w-md md:max-w-lg bg-gray-100 text-gray-800 rounded-xl p-3';

        bubble.innerHTML = `<p>${text}</p>`;
        messageDiv.appendChild(bubble);

        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;

        // Trigger animation
        setTimeout(() => {
            messageDiv.classList.add('fade-in');
        }, 10);
    }

    // Close modal when clicking outside
    window.addEventListener('click', (event) => {
        if (event.target === authModal) {
            authModal.classList.add('hidden');
        }
    });
</script>

alert('Por favor, digite um email válido.'); } });

    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && isAuthenticated && !isWaitingResponse) {
            sendMessage();
        }
    });

    sendButton.addEventListener('click', () => {
        if (isAuthenticated && !isWaitingResponse) {
            sendMessage();
        }
    });

    newChatBtn.addEventListener('click', () => {
        if (isAuthenticated) {
            clearChat();
        }
    });

    logoutBtn.addEventListener('click', () => {
        logoutUser();
    });

    // Functions
    function authenticateUser(email) {
        userEmail = email;
        isAuthenticated = true;
        localStorage.setItem('chatbot_email', email);

        // Update UI
        userEmailDisplay.textContent = email;
        userActions.classList.remove('hidden');
        userInput.disabled = false;
        sendButton.disabled = false;
        authPrompt.classList.add('hidden');
        authEmail.value = '';

        // Add welcome message
        addMessage('system', `Olá! Estou aqui para ajudar. Como posso te ajudar hoje?`);
    }

    function logoutUser() {
        // Clear session
        userEmail = null;
        isAuthenticated = false;
        localStorage.removeItem('chatbot_email');

        // Update UI
        userActions.classList.add('hidden');
        userInput.disabled = true;
        sendButton.disabled = true;
        authPrompt.classList.remove('hidden');

        // Clear chat and show initial message
        clearChat();
        addMessage('system', 'Você saiu da sessão. Para começar uma nova conversa, autentique-se novamente.');
    }

    function clearChat() {
        // Clear all messages except the first one
        while (chatMessages.children.length > 1) {
            chatMessages.removeChild(chatMessages.lastChild);
        }

        // If no messages left, add a new starting message
        if (chatMessages.children.length === 0) {
            addMessage('system', 'Nova conversa iniciada. Como posso te ajudar?');
        }
    }

    async function sendMessage() {
        const message = userInput.value.trim();
        if (message === '' || isWaitingResponse) return;

        // Add user message to chat
        addMessage('user', message);
        userInput.value = '';

        // Show typing indicator
        isWaitingResponse = true;
        typingIndicator.classList.remove('hidden');
        userInput.disabled = true;
        sendButton.disabled = true;

        // Prepare data for webhook
        const data = {
            email: userEmail,
            message: message,
            timestamp: new Date().toISOString()
        };

        try {
            // Send to webhook
            const response = await fetch(WEBHOOK_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            // Clone the response to read it multiple times if needed
            const responseClone = response.clone();

            // First try to parse as JSON
            try {
                const jsonData = await response.json();
                if (jsonData && typeof jsonData === 'object') {
                    // Handle different response formats
                    let responseText = "Desculpe, não consegui processar sua solicitação.";

                    if (jsonData.response) {
                        responseText = jsonData.response;

<!-- Messages Area -->

Olá! 👋 Sou seu assistente virtual. Para começarmos, por favor, digite seu email no campo abaixo.

        <!-- Input Area -->
        <div class="border-t border-gray-200 p-4 bg-gray-50">
            <div id="input-container" class="flex items-center space-x-2">
                <input type="text" id="user-input" placeholder="Digite sua mensagem..." disabled class="flex-1 px-4 py-2 border border-gray-300 rounded-full focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50">
                <button id="send-button" disabled class="bg-blue-600 hover:bg-blue-700 text-white rounded-full w-10 h-10 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
            <div id="auth-prompt" class="mt-2 text-center">
                <button id="show-auth" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                    <i class="fas fa-sign-in-alt mr-1"></i> Autenticar para conversar
                </button>
            </div>
        </div>
    </div>

    <!-- Typing Indicator -->
    <div id="typing-indicator" class="hidden mt-2 ml-4">
        <div class="flex space-x-1 typing-indicator">
            <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse"></div>
            <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-100"></div>
            <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-200"></div>
            <span class="ml-2 text-sm text-gray-600">Digitando...</span>
        </div>
    </div>
</div>

<script>
    // DOM Elements
    const authModal = document.getElementById('auth-modal');
    const closeAuth = document.getElementById('close-auth');
    const showAuth = document.getElementById('show-auth');
    const authSubmit = document.getElementById('auth-submit');
    const authEmail = document.getElementById('auth-email');
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-button');
    const chatMessages = document.getElementById('chat-messages');
    const typingIndicator = document.getElementById('typing-indicator');
    const userActions = document.getElementById('user-actions');
    const userEmailDisplay = document.getElementById('user-email');
    const inputContainer = document.getElementById('input-container');
    const authPrompt = document.getElementById('auth-prompt');
    const newChatBtn = document.getElementById('new-chat-btn');
    const logoutBtn = document.getElementById('logout-btn');

    // Webhook URL
    const WEBHOOK_URL = 'https://hook.us2.make.com/8lc4wn8e1wa2g6gxvnh27y068emdpuud';

    // User session
    let userEmail = localStorage.getItem('chatbot_email') || null;
    let isAuthenticated = userEmail !== null;
    let isWaitingResponse = false;

    // Initialize
    if (isAuthenticated) {
        authenticateUser(userEmail);
    }

    // Event Listeners
    showAuth.addEventListener('click', () => {
        authModal.classList.remove('hidden');
    });

    closeAuth.addEventListener('click', () => {
        authModal.classList.add('hidden');
    });

    authSubmit.addEventListener('click', () => {
        const email = authEmail.value.trim();
        if (email) {
            authenticateUser(email);
            authModal.classList.add('hidden');
        } else {

overflow-hidden">

<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ChatBot Acessível</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"> <style> @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; } .chat-container { height: calc(100vh - 180px); } @media (max-width: 640px) { .chat-container { height: calc(100vh - 160px); } } .message-transition { transition: all 0.3s ease; } .fade-in { animation: fadeIn 0.3s ease-in; } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .action-btn { transition: all 0.2s ease; } .action-btn:hover { transform: translateY(-2px); } .typing-indicator { display: inline-flex; align-items: center; background-color: #f3f4f6; padding: 8px 12px; border-radius: 18px; } </style> </head> <body class="bg-gray-100 font-sans"> <div class="max-w-4xl mx-auto p-4"> <!-- Header --> <header class="bg-blue-600 text-white rounded-lg shadow-md p-4 mb-6"> <div class="flex items-center justify-between"> <div class="flex items-center space-x-3"> <i class="fas fa-robot text-2xl"></i> <h1 class="text-xl font-bold">Assistente Virtual</h1> </div> <div id="user-actions" class="hidden items-center space-x-2"> <button id="new-chat-btn" class="action-btn bg-blue-700 hover:bg-blue-800 px-3 py-1 rounded-full text-sm flex items-center"> <i class="fas fa-plus mr-1"></i> Novo Chat </button> <button id="logout-btn" class="action-btn bg-red-600 hover:bg-red-700 px-3 py-1 rounded-full text-sm flex items-center"> <i class="fas fa-sign-out-alt mr-1"></i> Sair </button> <div id="user-info" class="bg-blue-700 px-3 py-1 rounded-full flex items-center"> <i class="fas fa-user-circle mr-1"></i> <span id="user-email" class="text-sm"></span> </div> </div> </div> </header>

<!-- Auth Modal --> <div id="auth-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"> <div class="bg-white rounded-lg p-6 w-full max-w-md"> <div class="flex justify-between items-center mb-4"> <h2 class="text-xl font-bold text-gray-800">Acesso Rápido</h2> <button id="close-auth" class="text-gray-500 hover:text-gray-700"> <i class="fas fa-times"></i> </button> </div> <p class="text-gray-600 mb-4">Digite seu email para começar a conversar. Não precisa verificação!</p> <input type="email" id="auth-email" placeholder="seu@email.com" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 mb-4"> <button id="auth-submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-200 flex items-center justify-center"> <i class="fas fa-sign-in-alt mr-2"></i> Entrar </button> </div> </div>

<!-- Chat Container --> <div class="bg-white rounded-xl shadow-md

usando o webhooks com o grok

1

Recursos

↑ voltar ao topo · ver no Telegram ↗