En este ejercicio nos conectamos a la API de Openweather para obtener los datos en un Bot interactivo
Escribe el nombre de la ciudad del Mundo que quieras y el bot te dará los datos en tiempo real
Chat-Bot del Clima
🌟 ¡Aprende a consumir API´s para Tu Chat-Bot! 🌟
🔹 Paso a Paso:
Estructura HTML:
- Crear una estructura básica para el chat-bot.
Estilo CSS:
- Añadir transparencia, desenfoque y animaciones.
- Usa
backdrop-filter: blur()
para el efecto de desenfoque. 🌫️ - Anima la entrada de los mensajes con
@keyframes
. 🚀
Lógica JavaScript:
- Usar la API de OpenWeatherMap para obtener el clima y mostrarlo en el chat.
HTML
Chat-Bot del Clima
Chat-Bot del Clima
CSS
body {
font-family: Arial, sans-serif;
background: url('background.jpg') no-repeat center center fixed;
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.chat-container {
width: 400px;
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
overflow: hidden;
animation: fadeIn 1s ease-in-out;
}
.chat-header {
background-color: rgba(98, 0, 234, 0.8);
color: #fff;
padding: 20px;
text-align: center;
}
.chat-messages {
flex: 1;
padding: 20px;
overflow-y: auto;
border-top: 1px solid rgba(255, 255, 255, 0.1);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.message {
margin-bottom: 15px;
animation: slideIn 0.5s ease-in-out;
}
.message.user {
text-align: right;
}
.message.bot {
text-align: left;
}
.message .content {
display: inline-block;
padding: 10px 20px;
border-radius: 20px;
max-width: 70%;
}
.message.user .content {
background-color: rgba(98, 0, 234, 0.8);
color: #fff;
}
.message.bot .content {
background-color: rgba(224, 224, 224, 0.8);
color: #000;
}
.chat-input {
display: flex;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
#user-input {
flex: 1;
padding: 15px;
border: none;
outline: none;
font-size: 16px;
background: rgba(255, 255, 255, 0.1);
color: #fff;
backdrop-filter: blur(5px);
}
#send-btn {
padding: 15px;
background-color: rgba(98, 0, 234, 0.8);
color: #fff;
border: none;
cursor: pointer;
transition: background-color 0.3s ease;
}
#send-btn:hover {
background-color: rgba(55, 0, 179, 0.8);
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideIn {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
JS
document.getElementById('send-btn').addEventListener('click', sendMessage);
document.getElementById('user-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
async function sendMessage() {
const inputElement = document.getElementById('user-input');
const message = inputElement.value.trim();
if (message === '') return;
displayMessage('user', message);
inputElement.value = '';
const response = await fetchWeather(message);
displayMessage('bot', response);
}
function displayMessage(sender, text) {
const chatMessages = document.getElementById('chat-messages');
const messageElement = document.createElement('div');
messageElement.classList.add('message', sender);
const contentElement = document.createElement('div');
contentElement.classList.add('content');
contentElement.innerText = text;
messageElement.appendChild(contentElement);
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
async function fetchWeather(city) {
const apiKey = 'Tu clave API de Openweather';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=es`;
try {
console.log(`Fetching weather for: ${city}`);
const response = await fetch(apiUrl);
console.log(`Response status: ${response.status}`);
if (!response.ok) throw new Error('Ciudad no encontrada');
const data = await response.json();
console.log(`Data received: ${JSON.stringify(data)}`);
return `El clima en ${data.name} es ${data.weather[0].description} con una temperatura de ${data.main.temp}°C.`;
} catch (error) {
console.error(`Error fetching weather data: ${error.message}`);
return `Error: ${error.message}`;
}
}
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
229
Módulo 1: Fundamentos Avanzados de UI
Comprender y aplicar principios de diseño
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
203
Image Accordion Slider with CSS and JS
🚀 Efecto accordion slider 🖼️ que combina imágenes con animaciones suaves y diseño interactivo.💻🔥
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
347
¿Qué es View Transitions?
View Transitions es una API moderna del navegador que permite crear transiciones fluidas entre diferentes vistas o estados de una página web.
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
165
Creando partículas controladas por audio en Three.js
👉 Con tecnología de Three.js y Web Audio API, ahora el sonido no solo se escucha,
¡se ve en tiempo real! 💻🎶
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
186
Looping words with GSAP
CodePen
Looping words with GSAP
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp
353
WordPress con React y Gutenberg
Crear una landing page con React y Gutenberg en WordPress es una combinación poderosa para lograr una experiencia de usuario moderna y un control total sobre el desarrollo.