Un chatbot JavaScript en 100 lignes
Dans ce tutoriel, vous construisez un chatbot qui fonctionne directement dans le navigateur. Il reconnaît des mots-clés dans les messages de l’utilisateur et répond de manière contextuelle. Ensuite, on le connecte à l’API ChatGPT pour des réponses intelligentes. Tout en HTML, CSS et JavaScript.
L’interface du chat
<div class="chatbot">
<div class="chat-header">
<span class="status-dot"></span>
<h3>Assistant ITSkillsCenter</h3>
</div>
<div class="chat-messages" id="messages"></div>
<form class="chat-input" id="chatForm">
<input type="text" id="userInput" placeholder="Tapez votre message..." autocomplete="off">
<button type="submit">Envoyer</button>
</form>
</div>
.chatbot {
width: 380px;
height: 500px;
border-radius: 16px;
box-shadow: 0 8px 32px rgba(0,0,0,0.15);
display: flex;
flex-direction: column;
overflow: hidden;
font-family: -apple-system, sans-serif;
}
.chat-header {
background: #4a90d9;
color: white;
padding: 16px;
display: flex;
align-items: center;
gap: 10px;
}
.status-dot {
width: 10px; height: 10px;
background: #4caf50;
border-radius: 50%;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
background: #f8f9fa;
}
.message {
max-width: 80%;
padding: 10px 14px;
border-radius: 16px;
font-size: 14px;
line-height: 1.5;
}
.message.bot {
background: white;
align-self: flex-start;
border-bottom-left-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,0.08);
}
.message.user {
background: #4a90d9;
color: white;
align-self: flex-end;
border-bottom-right-radius: 4px;
}
.typing-indicator {
display: flex;
gap: 4px;
padding: 10px 14px;
}
.typing-indicator span {
width: 8px; height: 8px;
background: #ccc;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
}
.typing-indicator span:nth-child(2) { animation-delay: 0.16s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.32s; }
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
.chat-input {
display: flex;
padding: 12px;
gap: 8px;
background: white;
border-top: 1px solid #eee;
}
.chat-input input {
flex: 1;
padding: 10px 14px;
border: 1px solid #ddd;
border-radius: 20px;
font-size: 14px;
outline: none;
}
.chat-input button {
padding: 10px 20px;
background: #4a90d9;
color: white;
border: none;
border-radius: 20px;
cursor: pointer;
}
Version 1 : chatbot à règles (sans IA)
const messages = document.getElementById('messages');
const chatForm = document.getElementById('chatForm');
const userInput = document.getElementById('userInput');
// Base de connaissances du bot
const responses = [
{ keywords: ['bonjour', 'salut', 'hello', 'bonsoir'],
reply: 'Bonjour ! 👋 Comment puis-je vous aider ?' },
{ keywords: ['prix', 'tarif', 'combien', 'coût'],
reply: 'Nos tarifs commencent à 150 000 FCFA pour un site vitrine. Souhaitez-vous un devis personnalisé ?' },
{ keywords: ['formation', 'cours', 'apprendre'],
reply: 'Nous proposons des formations en développement web, marketing digital et IA. Quelle thématique vous intéresse ?' },
{ keywords: ['contact', 'joindre', 'appeler', 'téléphone'],
reply: 'Vous pouvez nous contacter au +221 XX XXX XX XX ou par email à contact@itskillscenter.io' },
{ keywords: ['wordpress', 'site', 'web'],
reply: 'Nous créons des sites WordPress sur mesure. Vitrine, e-commerce, blog — selon vos besoins. Quel type de site recherchez-vous ?' },
{ keywords: ['merci', 'thanks'],
reply: 'Avec plaisir ! N\'hésitez pas si vous avez d\'autres questions. 😊' },
{ keywords: ['au revoir', 'bye', 'bonne journée'],
reply: 'Au revoir ! Bonne journée et à bientôt sur ITSkillsCenter ! 👋' }
];
const defaultReply = 'Je ne suis pas sûr de comprendre. Pouvez-vous reformuler ? Vous pouvez me demander nos tarifs, formations ou comment nous contacter.';
function findResponse(input) {
const lower = input.toLowerCase();
const match = responses.find(r =>
r.keywords.some(kw => lower.includes(kw))
);
return match ? match.reply : defaultReply;
}
function addMessage(text, sender) {
const div = document.createElement('div');
div.className = 'message ' + sender;
div.textContent = text;
messages.appendChild(div);
messages.scrollTop = messages.scrollHeight;
}
function showTyping() {
const typing = document.createElement('div');
typing.className = 'message bot typing-indicator';
typing.id = 'typing';
typing.innerHTML = '<span></span><span></span><span></span>';
messages.appendChild(typing);
messages.scrollTop = messages.scrollHeight;
}
function hideTyping() {
const typing = document.getElementById('typing');
if (typing) typing.remove();
}
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = userInput.value.trim();
if (!text) return;
addMessage(text, 'user');
userInput.value = '';
showTyping();
// Simuler un délai de réponse
setTimeout(() => {
hideTyping();
addMessage(findResponse(text), 'bot');
}, 800 + Math.random() * 700);
});
// Message de bienvenue
addMessage('Bonjour ! Je suis l\'assistant ITSkillsCenter. Comment puis-je vous aider ?', 'bot');
Version 2 : connecter à l’API ChatGPT
// Remplacer findResponse par un appel API
async function getAIResponse(userMessage) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer VOTRE_CLE_API' // ⚠️ Ne jamais mettre en front-end !
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'Tu es l\'assistant d\'ITSkillsCenter, un centre de formation IT à Dakar. Réponds en français, de manière concise et amicale.' },
{ role: 'user', content: userMessage }
],
max_tokens: 150
})
});
const data = await response.json();
return data.choices[0].message.content;
}
⚠️ Important : ne mettez JAMAIS votre clé API dans le code front-end — elle serait visible par tous. Créez un petit backend (Node.js, PHP, ou une fonction serverless) qui fait l’appel API côté serveur.
Exercice
- Ajoutez des boutons de réponse rapide (« Tarifs », « Formations », « Contact ») sous les messages du bot
- Ajoutez un indicateur « En ligne » / « Hors ligne » basé sur l’heure
- Sauvegardez l’historique de conversation dans localStorage
- Ajoutez un bouton flottant en bas à droite pour ouvrir/fermer le chat