Skip to content

Commit f68f8e5

Browse files
authored
Merge pull request #21 from Satvik-Singh192/chatbot-feature
feat: add chatbot functionality with widget and api integration
2 parents 0ed6246 + 8f7133b commit f68f8e5

16 files changed

Lines changed: 751 additions & 9 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
node_modules
1+
node_modules
2+
.env

CHATBOT_README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# 🤖 Chatbot Response Engine
2+
3+
## How It Works
4+
5+
The chatbot uses **OpenAI GPT-3.5-turbo** for intelligent responses to user queries. When OpenAI API is unavailable, it falls back to **predefined responses** for common questions.
6+
7+
### Response Flow:
8+
1. User sends a message
9+
2. System categorizes the message (greeting, pricing, support, features)
10+
3. Analyzes sentiment (positive, negative, neutral)
11+
4. Calls OpenAI API if available, otherwise uses predefined responses
12+
5. Saves conversation to database
13+
6. Returns response to user
14+
15+
### Message Categories:
16+
- **greeting**: hello, hi, hey
17+
- **pricing**: price, cost, pricing
18+
- **support**: help, support, issue, problem
19+
- **features**: feature, capability, what can
20+
- **default**: other queries
21+
22+
### Predefined Responses:
23+
When OpenAI is unavailable, the chatbot uses simple predefined responses:
24+
```javascript
25+
greeting: "Hello! How can I help you today?"
26+
pricing: "Our pricing plans start at $9.99/month..."
27+
support: "I'm here to help! Can you describe the issue?"
28+
features: "Our platform offers mass email sending..."
29+
```
30+
31+
## Setup
32+
33+
1. Add OpenAI API key to `backend/.env`:
34+
```env
35+
OPENAI_API_KEY=your_openai_api_key_here
36+
```
37+
38+
2. Install dependencies:
39+
```bash
40+
cd backend && npm install
41+
cd ../frontend && npm install
42+
```
43+
44+
3. Start servers:
45+
```bash
46+
# Backend
47+
cd backend && npm run dev
48+
49+
# Frontend
50+
cd frontend && npm run dev
51+
```
52+
53+
4. Visit `/chatbot` or use the chat widget
54+
55+
## API Endpoints
56+
57+
- `POST /api/chatbot/message` - Send message, get response
58+
- `GET /api/chatbot/history/:userId` - Get chat history
59+
- `POST /api/chatbot/test` - Test chatbot
60+
61+
## Files Created
62+
63+
**Backend:**
64+
- `services/chatbotService.js` - Core AI logic
65+
- `controllers/chatbotController.js` - API handlers
66+
- `routes/chatbotRoutes.js` - Routes
67+
- `models/Message.js` - Database schema
68+
69+
**Frontend:**
70+
- `pages/Chatbot.jsx` - Chat interface
71+
- `components/ChatbotWidget.jsx` - Embeddable widget

README.md

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,12 +143,44 @@ Then simply run:
143143

144144
npm start
145145

146-
## 🤖 Planned Features
146+
## 🤖 AI Chatbot Feature (COMPLETED!)
147+
148+
The AI Auto Responder chatbot has been successfully implemented! 🎉
149+
150+
### What's Included:
151+
- **OpenAI Integration**: Uses GPT-3.5-turbo for intelligent responses
152+
- **Smart Fallback**: Predefined responses when OpenAI is unavailable
153+
- **Message Categorization**: Automatically categorizes queries (greeting, pricing, support, features)
154+
- **Sentiment Analysis**: Analyzes user message sentiment
155+
- **Full Chat Interface**: Complete chat page at `/chatbot`
156+
- **Embeddable Widget**: Chat widget for any page
157+
- **Conversation History**: Stores and retrieves chat history
158+
- **Analytics**: Usage analytics and insights
159+
160+
### How to Use:
161+
1. **Set up OpenAI API key** in your `.env` file:
162+
```env
163+
OPENAI_API_KEY=your_openai_api_key_here
164+
```
165+
166+
2. **Access the chatbot**:
167+
- Visit `/chatbot` for the full chat interface
168+
- Use the chat widget on the home page
169+
- Navigate via the "AI Assistant" link in the navbar
170+
171+
3. **API Endpoints**:
172+
- `POST /api/chatbot/message` - Send messages
173+
- `GET /api/chatbot/history/:userId` - Get chat history
174+
- `GET /api/chatbot/analytics/:userId` - Get analytics
175+
176+
For detailed documentation, see [CHATBOT_README.md](./CHATBOT_README.md)
177+
178+
## 🚀 Planned Features
147179

148180
| Feature | Description | Status |
149181
|----------|-------------|--------|
150182
| 📧 Mass Email Sending | Send personalized bulk emails | ✅ Base setup |
151-
| 🧠 AI Auto Responder | AI chatbot replies to received emails | 🧩 Planned |
183+
| 🧠 AI Auto Responder | AI chatbot replies to received emails | **COMPLETED** |
152184
| 📅 Scheduler | Schedule campaigns for future dates | 🧩 Planned |
153185
| 📊 Dashboard | Track sent, opened, and clicked emails | 🧩 Planned |
154186
| 📂 Contact Management | Upload and manage email lists | 🧩 Planned |

backend/package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@
1313
"jsonwebtoken": "^9.0.2",
1414
"mongoose": "^6.9.1",
1515
"nodemailer": "^6.9.4",
16-
"winston": "^3.8.2"
16+
"winston": "^3.8.2",
17+
"openai": "^4.20.1",
18+
"dotenv": "^16.3.1",
19+
"cors": "^2.8.5"
1720
},
1821
"devDependencies": {
1922
"nodemon": "^2.0.22"
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
const { askBot } = require('../services/chatbotService');
2+
const Message = require('../models/Message');
3+
const logger = require('../utils/logger');
4+
5+
// Send message to chatbot and get response
6+
exports.sendMessage = async (req, res) => {
7+
try {
8+
const { message, userId } = req.body;
9+
10+
if (!message || message.trim().length === 0) {
11+
return res.status(400).json({
12+
success: false,
13+
error: 'Message is required and cannot be empty'
14+
});
15+
}
16+
17+
// Get chatbot response
18+
const botResponse = await askBot(message, userId);
19+
20+
res.status(200).json({
21+
success: true,
22+
data: {
23+
message: message,
24+
response: botResponse.reply,
25+
category: botResponse.category,
26+
sentiment: botResponse.sentiment,
27+
timestamp: botResponse.timestamp
28+
}
29+
});
30+
31+
} catch (error) {
32+
logger.error('Error in sendMessage controller:', error);
33+
res.status(500).json({
34+
success: false,
35+
error: 'Internal server error. Please try again later.'
36+
});
37+
}
38+
};
39+
40+
41+
// Test chatbot endpoint (for development/testing)
42+
exports.testChatbot = async (req, res) => {
43+
try {
44+
const { message } = req.body;
45+
46+
if (!message) {
47+
return res.status(400).json({
48+
success: false,
49+
error: 'Test message is required'
50+
});
51+
}
52+
53+
const botResponse = await askBot(message);
54+
55+
res.status(200).json({
56+
success: true,
57+
data: {
58+
input: message,
59+
output: botResponse.reply,
60+
category: botResponse.category,
61+
sentiment: botResponse.sentiment,
62+
timestamp: botResponse.timestamp
63+
}
64+
});
65+
66+
} catch (error) {
67+
logger.error('Error in testChatbot controller:', error);
68+
res.status(500).json({
69+
success: false,
70+
error: 'Chatbot test failed'
71+
});
72+
}
73+
};

backend/src/models/Message.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const mongoose = require('mongoose');
2+
3+
const MessageSchema = new mongoose.Schema({
4+
user: {
5+
type: mongoose.Schema.Types.ObjectId,
6+
ref: 'User',
7+
required: true
8+
},
9+
message: {
10+
type: String,
11+
required: true,
12+
trim: true
13+
},
14+
response: {
15+
type: String,
16+
required: true,
17+
trim: true
18+
},
19+
timestamp: {
20+
type: Date,
21+
default: Date.now
22+
},
23+
category: {
24+
type: String,
25+
enum: ['general', 'support', 'sales', 'technical', 'other'],
26+
default: 'general'
27+
},
28+
sentiment: {
29+
type: String,
30+
enum: ['positive', 'negative', 'neutral'],
31+
default: 'neutral'
32+
},
33+
isAutoReply: {
34+
type: Boolean,
35+
default: true
36+
}
37+
}, { timestamps: true });
38+
39+
// Index for better query performance
40+
MessageSchema.index({ user: 1, timestamp: -1 });
41+
MessageSchema.index({ category: 1 });
42+
MessageSchema.index({ sentiment: 1 });
43+
44+
module.exports = mongoose.model('Message', MessageSchema);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
const {
4+
sendMessage,
5+
testChatbot
6+
} = require('../controllers/chatbotController');
7+
8+
// POST /api/chatbot/message - Send a message to the chatbot
9+
router.post('/message', sendMessage);
10+
11+
// POST /api/chatbot/test - Test chatbot functionality (development endpoint)
12+
router.post('/test', testChatbot);
13+
14+
module.exports = router;

backend/src/server.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
require('dotenv').config();
22

33
const express = require('express');
4+
const cors = require('cors');
45
const connectDB = require('./config/db');
56
const userRoutes = require('./routes/userRoutes');
7+
const chatbotRoutes = require('./routes/chatbotRoutes');
68

79
const app = express();
10+
app.use(cors());
811
app.use(express.json());
912

13+
app.use('/api/users', userRoutes);
14+
app.use('/api/chatbot', chatbotRoutes);
1015
app.use('/api/auth', userRoutes);
1116

1217
const PORT = process.env.PORT || 5000;

0 commit comments

Comments
 (0)