Step-by-Step Guide: Integrating Chatbot into Your Website
Here's a beginner-friendly, step-by-step method to integrate the chatbot into your website:
🎯 Prerequisites
· Basic knowledge of HTML/CSS/JavaScript
· A code editor (VS Code, Sublime Text, etc.)
· Your website files
---
Step 1: Create the Chatbot Files
1.1 Create a new folder called chatbot in your website directory
```
your-website/
├── index.html
├── style.css
├── script.js
└── chatbot/ ← Create this folder
├── chatbot.html
├── chatbot.css
├── chatbot.js
└── app.py
```
---
Step 2: Create Chatbot HTML File
2.1 Create chatbot/chatbot.html
html
<!DOCTYPE html>
<html>
<head>
<title>Chatbot Widget</title>
<link rel="stylesheet" type="text/css" href="chatbot.css">
</head>
<body>
<!-- Chatbot Trigger Button -->
<button class="chatbot-trigger" onclick="toggleChatbot()">
💬
</button>
<!-- Chatbot Container -->
<div class="chatbot-container" id="chatbotContainer">
<div class="chatbot-header">
<h3>Customer Support</h3>
<button class="close-btn" onclick="toggleChatbot()">×</button>
</div>
<div class="chatbot-messages" id="chatMessages">
<div class="bot-message">
<p>Hello! How can I help you today?</p>
</div>
</div>
<div class="chatbot-input">
<input type="text" id="userInput" placeholder="Type your message..."
onkeypress="handleKeyPress(event)">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script src="chatbot.js"></script>
</body>
</html>
```
---
Step 3: Create Chatbot CSS File
3.1 Create chatbot/chatbot.css
```css
.chatbot-trigger {
position: fixed;
bottom: 20px;
right: 20px;
background: #007bff;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
cursor: pointer;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
z-index: 1000;
font-size: 24px;
color: white;
}
.chatbot-container {
position: fixed;
bottom: 90px;
right: 20px;
width: 350px;
height: 500px;
background: white;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
display: none;
flex-direction: column;
z-index: 1000;
}
.chatbot-header {
background: #007bff;
color: white;
padding: 15px;
border-radius: 10px 10px 0 0;
display: flex;
justify-content: space-between;
align-items: center;
}
.close-btn {
background: none;
border: none;
color: white;
font-size: 20px;
cursor: pointer;
}
.chatbot-messages {
flex: 1;
padding: 15px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.user-message, .bot-message {
max-width: 80%;
padding: 10px;
border-radius: 10px;
margin: 5px 0;
}
.user-message {
background: #007bff;
color: white;
align-self: flex-end;
}
.bot-message {
background: #f1f1f1;
color: #333;
align-self: flex-start;
}
.chatbot-input {
padding: 15px;
border-top: 1px solid #ddd;
display: flex;
gap: 10px;
}
.chatbot-input input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
.chatbot-input button {
background: #007bff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
}
.typing {
font-style: italic;
color: #666;
}
```
---
Step 4: Create Chatbot JavaScript File
4.1 Create chatbot/chatbot.js
```javascript
let isChatbotOpen = false;
function toggleChatbot() {
const container = document.getElementById('chatbotContainer');
isChatbotOpen = !isChatbotOpen;
container.style.display = isChatbotOpen ? 'flex' : 'none';
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
async function sendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();
if (!message) return;
// Add user message to chat
addMessage(message, 'user');
userInput.value = '';
// Show typing indicator
showTypingIndicator();
try {
// For now, use simple responses without backend
const response = getSimpleResponse(message);
// Simulate delay
setTimeout(() => {
removeTypingIndicator();
addMessage(response, 'bot');
}, 1000);
} catch (error) {
removeTypingIndicator();
addMessage('Sorry, I encountered an error. Please try again.', 'bot');
console.error('Error:', error);
}
}
function getSimpleResponse(message) {
const messageLower = message.toLowerCase();
// Simple response logic
if (messageLower.includes('hello') || messageLower.includes('hi')) {
return "Hello! How can I help you today?";
} else if (messageLower.includes('price') || messageLower.includes('cost')) {
return "Our pricing varies by product. Please visit our pricing page for details.";
} else if (messageLower.includes('contact') || messageLower.includes('email')) {
return "You can contact us at support@yourwebsite.com or call (555) 123-4567.";
} else if (messageLower.includes('hours')) {
return "We're available Monday to Friday, 9 AM to 6 PM.";
} else if (messageLower.includes('thank')) {
return "You're welcome! Is there anything else I can help with?";
} else if (messageLower.includes('bye') || messageLower.includes('goodbye')) {
return "Goodbye! Feel free to reach out if you have more questions.";
} else {
return "I understand you're asking about: " + message + ". For more detailed assistance, please contact our support team.";
}
}
function addMessage(text, sender) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `${sender}-message`;
const messageP = document.createElement('p');
messageP.textContent = text;
messageDiv.appendChild(messageP);
messagesContainer.appendChild(messageDiv);
scrollToBottom();
}
function showTypingIndicator() {
const messagesContainer = document.getElementById('chatMessages');
const typingDiv = document.createElement('div');
typingDiv.id = 'typing-indicator';
typingDiv.className = 'bot-message typing';
typingDiv.innerHTML = '<p>Typing...</p>';
messagesContainer.appendChild(typingDiv);
scrollToBottom();
}
function removeTypingIndicator() {
const typingIndicator = document.getElementById('typing-indicator');
if (typingIndicator) {
typingIndicator.remove();
}
}
function scrollToBottom() {
const messagesContainer = document.getElementById('chatMessages');
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Auto-open chatbot after 30 seconds
setTimeout(() => {
if (!isChatbotOpen) {
toggleChatbot();
}
}, 30000);
```
---
Step 5: Integrate Chatbot into Your Main Website
5.1 Add chatbot to your main HTML file
Add this code just before the closing </body> tag in your main HTML file:
html
<!-- Add this to your main website HTML file -->
<iframe src="chatbot/chatbot.html"
style="position: fixed; bottom: 0; right: 0; border: none; width: 100px; height: 100px; z-index: 999;">
</iframe>
OR (Better method) - Add directly to your main HTML:
html
<!-- Add this before closing </body> tag in your main HTML -->
<div id="chatbot-widget">
<!-- Chatbot Trigger Button -->
<button class="chatbot-trigger" onclick="toggleChatbot()">
💬
</button>
<!-- Chatbot Container -->
<div class="chatbot-container" id="chatbotContainer">
<div class="chatbot-header">
<h3>Customer Support</h3>
<button class="close-btn" onclick="toggleChatbot()">×</button>
</div>
<div class="chatbot-messages" id="chatMessages">
<div class="bot-message">
<p>Hello! How can I help you today?</p>
</div>
</div>
<div class="chatbot-input">
<input type="text" id="userInput" placeholder="Type your message..."
onkeypress="handleKeyPress(event)">
<button onclick="sendMessage()">Send</button>
</div>
</div>
</div>
<!-- Add chatbot CSS -->
<link rel="stylesheet" href="chatbot/chatbot.css">
<!-- Add chatbot JavaScript -->
<script src="chatbot/chatbot.js"></script>
---
Step 6: Test Your Chatbot
6.1 Open your website in a browser
· You should see a chat button in the bottom-right corner
· Click the button to open the chat interface
· Try sending messages like:
· "Hello"
· "What are your hours?"
· "How much does it cost?"
---
Step 7: Customize (Optional)
7.1 Change colors
In chatbot.css, change these colors:
css
/* Change main color from blue to green */
.chatbot-trigger { background: #28a745; }
.chatbot-header { background: #28a745; }
.user-message { background: #28a745; }
.chatbot-input button { background: #28a745; }
```
7.2 Add more responses
In chatbot.js, add to the getSimpleResponse function:
javascript
else if (messageLower.includes('shipping')) {
return "We offer free shipping on orders over $50!";
} else if (messageLower.includes('return')) {
return "We have a 30-day return policy. No questions asked!";
}
---
Step 8: Advanced - Add Backend (Optional)
8.1 Create Python backend (if you have Python installed)
Create chatbot/app.py:
python
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
def get_bot_response(user_message):
message_lower = user_message.lower()
if 'hello' in message_lower or 'hi' in message_lower:
return "Hello! How can I assist you today?"
elif 'price' in message_lower or 'cost' in message_lower:
return "Our pricing varies by product. Please visit our pricing page."
elif 'contact' in message_lower or 'email' in message_lower:
return "Contact us at support@yourwebsite.com"
else:
return "I understand you're asking about: " + user_message + ". How can I help?"
@app.route('/chat', methods=['POST'])
def chat():
data = request.get_json()
user_message = data.get('message', '')
bot_response = get_bot_response(user_message)
return jsonify({'response': bot_response})
if __name__ == '__main__':
app.run(debug=True)
8.2 Update JavaScript to use backend
In chatbot.js, replace the sendMessage function with:
javascript
async function sendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();
if (!message) return;
addMessage(message, 'user');
userInput.value = '';
showTypingIndicator();
try {
const response = await fetch('http://localhost:5000/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
const data = await response.json();
removeTypingIndicator();
addMessage(data.response, 'bot');
} catch (error) {
removeTypingIndicator();
// Fallback to simple responses if backend fails
const fallbackResponse = getSimpleResponse(message);
addMessage(fallbackResponse, 'bot');
}
}
---
Troubleshooting Tips
1. Chatbot not appearing?
· Check browser console for errors (F12 → Console)
· Verify file paths are correct
2. Styles not loading?
· Make sure CSS file path is correct
· Check if styles are being overridden by your main CSS
3. JavaScript not working?
· Check browser console for errors
· Ensure JavaScript is enabled in browser
4. Backend not working?
· Make sure Python and Flask are installed
· Check if port 5000 is available
---
Final Checklist
· Chatbot button appears on website
· Chat window opens when clicked
· You can type and send messages
· Bot responds to messages
· Styles look correct
· No errors in browser console
That's it! You now have a functional chatbot on your website. Start with the simple version and gradually add more features as you become comfortable.
