Código HTML
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chat com Wikipedia</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
}
#chat {
flex: 1;
padding: 20px;
background: #f4f4f4;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.message {
max-width: 70%;
margin: 6px 0;
padding: 10px 14px;
border-radius: 12px;
line-height: 1.4;
}
.user {
background: #cce4ff;
align-self: flex-end;
text-align: right;
}
.bot {
background: #d6f5d6;
align-self: flex-start;
text-align: left;
white-space: pre-wrap;
}
#input-area {
display: flex;
padding: 10px;
border-top: 1px solid #ccc;
background: white;
}
#input {
flex: 1;
padding: 10px;
font-size: 16px;
border: 1px solid #aaa;
border-radius: 8px;
}
#send {
padding: 10px 16px;
margin-left: 8px;
font-size: 16px;
cursor: pointer;
background: #4a90e2;
border: none;
color: white;
border-radius: 8px;
}
#send:active {
background: #357abd;
}
</style>
</head>
<body>
<div id="chat"></div>
<div id="input-area">
<input id="input" type="text" placeholder="Digite sua pergunta..." />
<button id="send">Enviar</button>
</div>
<script>
const chat = document.getElementById('chat');
const input = document.getElementById('input');
const sendBtn = document.getElementById('send');
function addMessage(text, sender) {
const div = document.createElement('div');
div.classList.add('message', sender);
div.textContent = text;
chat.appendChild(div);
chat.scrollTop = chat.scrollHeight;
return div;
}
async function escreverGradualmente(elemento, texto) {
elemento.textContent = '';
for (let i = 0; i < texto.length; i++) {
elemento.textContent += texto[i];
await new Promise(r => setTimeout(r, 20)); // velocidade da digitação
chat.scrollTop = chat.scrollHeight;
}
}
async function buscarNaWikipedia(pergunta) {
const termo = encodeURIComponent(pergunta);
const url = `https://pt.wikipedia.org/api/rest_v1/page/summary/${termo}`;
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Não encontrado');
const data = await res.json();
return data.extract || 'Desculpa, não encontrei nada sobre isso.';
} catch {
return 'Desculpa, não encontrei nada sobre isso.';
}
}
async function responder(pergunta) {
addMessage(pergunta, 'user');
input.value = '';
const resposta = await buscarNaWikipedia(pergunta);
const divBot = addMessage('', 'bot');
await escreverGradualmente(divBot, resposta);
}
sendBtn.addEventListener('click', () => {
const pergunta = input.value.trim();
if (pergunta) {
responder(pergunta);
}
});
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendBtn.click();
}
});
</script>
</body>
</html>
Comments
Post a Comment