AI Chatbot | Hasan

Chatbot

Hey there
How can I help you today?
{ const div = document.createElement("div"); div.classList.add("message", ...classes); div.innerHTML = content; return div; }; // Generate bot response using API const generateBotResponse = async (incomingMessageDiv) => { const messageElement = incomingMessageDiv.querySelector(".message-text"); // Add user message to chat history chatHistory.push({ role: "user", parts: [{ text: userData.message }, ...(userData.file.data ? [{ inline_data: userData.file }] : [])], }); // API request options const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ contents: chatHistory, }), }; try { // Fetch bot response from API const response = await fetch(API_URL, requestOptions); const data = await response.json(); if (!response.ok) throw new Error(data.error.message); // Extract and display bot's response text const apiResponseText = data.candidates[0].content.parts[0].text.replace(/\*\*(.*?)\*\*/g, "$1").trim(); messageElement.innerText = apiResponseText; // Add bot response to chat history chatHistory.push({ role: "model", parts: [{ text: apiResponseText }], }); } catch (error) { // Handle error in API response console.log(error); messageElement.innerText = error.message; messageElement.style.color = "#ff0000"; } finally { // Reset user's file data, removing thinking indicator and scroll chat to bottom userData.file = {}; incomingMessageDiv.classList.remove("thinking"); chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" }); } }; // Handle outgoing user messages const handleOutgoingMessage = (e) => { e.preventDefault(); userData.message = messageInput.value.trim(); messageInput.value = ""; messageInput.dispatchEvent(new Event("input")); fileUploadWrapper.classList.remove("file-uploaded"); // Create and display user message const messageContent = `
${userData.file.data ? `` : ""}`; const outgoingMessageDiv = createMessageElement(messageContent, "user-message"); outgoingMessageDiv.querySelector(".message-text").innerText = userData.message; chatBody.appendChild(outgoingMessageDiv); chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" }); // Simulate bot response with thinking indicator after a delay setTimeout(() => { const messageContent = `
`; const incomingMessageDiv = createMessageElement(messageContent, "bot-message", "thinking"); chatBody.appendChild(incomingMessageDiv); chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" }); generateBotResponse(incomingMessageDiv); }, 600); }; // Adjust input field height dynamically messageInput.addEventListener("input", () => { messageInput.style.height = `${initialInputHeight}px`; messageInput.style.height = `${messageInput.scrollHeight}px`; document.querySelector(".chat-form").style.borderRadius = messageInput.scrollHeight > initialInputHeight ? "15px" : "32px"; }); // Handle Enter key press for sending messages messageInput.addEventListener("keydown", (e) => { const userMessage = e.target.value.trim(); if (e.key === "Enter" && !e.shiftKey && userMessage && window.innerWidth > 768) { handleOutgoingMessage(e); } }); // Handle file input change and preview the selected file fileInput.addEventListener("change", () => { const file = fileInput.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = (e) => { fileInput.value = ""; fileUploadWrapper.querySelector("img").src = e.target.result; fileUploadWrapper.classList.add("file-uploaded"); const base64String = e.target.result.split(",")[1]; // Store file data in userData userData.file = { data: base64String, mime_type: file.type, }; }; reader.readAsDataURL(file); }); // Cancel file upload fileCancelButton.addEventListener("click", () => { userData.file = {}; fileUploadWrapper.classList.remove("file-uploaded"); }); // Initialize emoji picker and handle emoji selection const picker = new EmojiMart.Picker({ theme: "light", skinTonePosition: "none", previewPosition: "none", onEmojiSelect: (emoji) => { const { selectionStart: start, selectionEnd: end } = messageInput; messageInput.setRangeText(emoji.native, start, end, "end"); messageInput.focus(); }, onClickOutside: (e) => { if (e.target.id === "emoji-picker") { document.body.classList.toggle("show-emoji-picker"); } else { document.body.classList.remove("show-emoji-picker"); } }, }); document.querySelector(".chat-form").appendChild(picker); sendMessage.addEventListener("click", (e) => handleOutgoingMessage(e)); document.querySelector("#file-upload").addEventListener("click", () => fileInput.click()); closeChatbot.addEventListener("click", () => document.body.classList.remove("show-chatbot")); chatbotToggler.addEventListener("click", () => document.body.classList.toggle("show-chatbot"));

Leave a Comment

Notice ⚠️Don;t make any nasty comments.
By Noticed Abir Ahmad 𝓐𝓫𝓲𝓻 𝓐𝓱𝓶𝓪𝓭 🅰🅱🅸🆁 🅰🅷🅼🅰🅳 🄰🄱🄸🅁 🄰🄷🄼🄰🄳