top of page
bottom of page
document.addEventListener("DOMContentLoaded", function() {
if (window.location.pathname.includes("byte")) {
console.log("✅ Byte Page Detected – Activating Chatbot");
const OPENAI_API_KEY = "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";
let lastRequestTime = 0;
async function getAIResponse(userInput) {
const chatBox = document.getElementById("chat-box");
if (!userInput.trim()) return;
let userBubble = document.createElement("div");
userBubble.classList.add("chat-bubble", "user-message");
userBubble.innerHTML = userInput;
chatBox.appendChild(userBubble);
document.getElementById("chat-input").value = "";
// Prevent rate-limit issues
const now = Date.now();
if (now - lastRequestTime < 3000) {
console.log("⏳ Please wait before sending another message.");
return;
}
lastRequestTime = now;
simulateTalking();
try {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${OPENAI_API_KEY}`
},
body: JSON.stringify({
model: "gpt-4-turbo",
messages: [{ role: "user", content: userInput }]
})
});
if (!response.ok) {
throw new Error(`Error ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (data.choices && data.choices.length > 0) {
let botMessage = data.choices[0].message.content;
let botBubble = document.createElement("div");
botBubble.classList.add("chat-bubble", "bot-message");
botBubble.innerHTML = botMessage;
chatBox.appendChild(botBubble);
chatBox.scrollTop = chatBox.scrollHeight;
setTimeout(() => {
document.getElementById("byte").classList.remove("talking");
}, 3000);
} else {
console.error("❌ OpenAI API response error:", data);
}
} catch (error) {
console.error("❌ Error connecting to OpenAI:", error);
}
}
function sendMessage() {
let userInput = document.getElementById("chat-input").value;
getAIResponse(userInput);
}
// Ensure button is connected to sendMessage function
document.addEventListener("DOMContentLoaded", function() {
const sendBtn = document.getElementById("send-btn");
if (sendBtn) {
sendBtn.addEventListener("click", sendMessage);
} else {
console.error("⚠️ Send button not found!");
}
});
} else {
console.log("❌ Byte Page Not Detected – Skipping Chatbot.");
}
});