-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathchatbot-example.js
More file actions
230 lines (203 loc) Β· 6.68 KB
/
chatbot-example.js
File metadata and controls
230 lines (203 loc) Β· 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Advanced chatbot example using WuzAPI
// This example shows how to create a simple chatbot with webhooks
// Demonstrates both traditional (global token) and flexible (per-request token) usage
import WuzapiClient from "wuzapi";
import express from "express";
const app = express();
app.use(express.json());
// Configuration
const CONFIG = {
apiUrl: "http://localhost:8080",
userToken: "your-user-token-here",
adminToken: "your-admin-token-here", // Optional: for admin operations
useFlexibleTokens: false, // Set to true to use flexible token approach
};
// Initialize the client based on chosen approach
const client = CONFIG.useFlexibleTokens
? new WuzapiClient({
apiUrl: CONFIG.apiUrl,
// No token here - will be provided per request
})
: new WuzapiClient({
apiUrl: CONFIG.apiUrl,
token: CONFIG.userToken, // Traditional global token
});
// Helper function to get request options for flexible token usage
const getRequestOptions = () => {
return CONFIG.useFlexibleTokens ? { token: CONFIG.userToken } : undefined;
};
// Simple command handlers
const commands = {
"/help": () => `π€ Available commands:
/help - Show this help
/status - Check bot status
/groups - List my groups
/contacts - Count contacts
/ping - Test connectivity`,
"/status": async () => {
const status = await client.session.getStatus(getRequestOptions());
return `π± Bot Status:
Connected: ${status.Connected ? "β
" : "β"}
Logged In: ${status.LoggedIn ? "β
" : "β"}
Token Mode: ${CONFIG.useFlexibleTokens ? "Flexible" : "Global"}`;
},
"/groups": async () => {
const groups = await client.group.list(getRequestOptions());
const groupList = groups.Groups.map(
(g) => `β’ ${g.Name} (${g.Participants.length} members)`
)
.slice(0, 5) // Show only first 5
.join("\n");
return `π₯ Your Groups (showing first 5):
${groupList}
${
groups.Groups.length > 5 ? `\n... and ${groups.Groups.length - 5} more` : ""
}`;
},
"/contacts": async () => {
const contacts = await client.user.getContacts(getRequestOptions());
return `π You have ${Object.keys(contacts).length} contacts`;
},
"/ping": () => "π Pong! Bot is working.",
};
// Handle incoming webhook messages
app.post("/webhook", async (req, res) => {
try {
const { event } = req.body;
// Only handle text messages
if (event?.Message?.conversation) {
const message = event.Message.conversation;
const from = event.Info.RemoteJid.replace("@s.whatsapp.net", "");
const isGroup = event.Info.RemoteJid.includes("@g.us");
console.log(`π¨ Message from ${from}: ${message}`);
// Handle commands
if (message.startsWith("/")) {
const command = message.split(" ")[0].toLowerCase();
if (commands[command]) {
try {
const response = await commands[command]();
await client.chat.sendText(
{
Phone: from,
Body: response,
},
getRequestOptions()
);
} catch (error) {
await client.chat.sendText(
{
Phone: from,
Body: `β Error executing command: ${error.message}`,
},
getRequestOptions()
);
}
} else {
await client.chat.sendText(
{
Phone: from,
Body: `β Unknown command. Type /help for available commands.`,
},
getRequestOptions()
);
}
}
// Auto-reply to specific messages
else if (message.toLowerCase().includes("hello")) {
await client.chat.sendText(
{
Phone: from,
Body: `π Hello! I'm a WuzAPI bot. Type /help to see what I can do.`,
},
getRequestOptions()
);
}
// Group mention handling
else if (isGroup && message.includes("@bot")) {
await client.chat.sendText(
{
Phone: from,
Body: `π€ You mentioned me! Type /help to see available commands.`,
},
getRequestOptions()
);
}
}
res.status(200).json({ success: true });
} catch (error) {
console.error("β Webhook error:", error);
res.status(500).json({ error: error.message });
}
});
// Initialize the bot
async function initializeBot() {
try {
console.log("π€ Starting WuzAPI bot...");
console.log(
`π§ Token mode: ${CONFIG.useFlexibleTokens ? "Flexible" : "Global"}`
);
// Test connection
const isConnected = await client.ping(getRequestOptions());
if (!isConnected) {
throw new Error("Cannot connect to WuzAPI server");
}
console.log("β
Connected to WuzAPI");
// Connect to WhatsApp
await client.session.connect(
{
Subscribe: ["Message", "ReadReceipt"],
Immediate: false,
},
getRequestOptions()
);
// Check status
const status = await client.session.getStatus(getRequestOptions());
console.log("π± WhatsApp Status:", status);
if (!status.LoggedIn) {
console.log("π± Not logged in. Getting QR code...");
const qr = await client.session.getQRCode(getRequestOptions());
console.log("π· Scan this QR code:", qr.QRCode);
// Wait for login
let attempts = 0;
while (attempts < 30) {
// Wait up to 5 minutes
await new Promise((resolve) => setTimeout(resolve, 10000)); // Wait 10 seconds
const newStatus = await client.session.getStatus(getRequestOptions());
if (newStatus.LoggedIn) {
console.log("β
Successfully logged in!");
break;
}
attempts++;
}
}
// Set webhook
const webhookUrl = "http://localhost:3000/webhook"; // Update with your webhook URL
await client.webhook.setWebhook(webhookUrl, ["All"], getRequestOptions());
console.log(`π Webhook set to: ${webhookUrl}`);
// Start Express server
app.listen(3000, () => {
console.log("π Bot server running on http://localhost:3000");
console.log("π€ Bot is ready to receive messages!");
console.log(
"π Available commands: /help, /status, /groups, /contacts, /ping"
);
});
} catch (error) {
console.error("β Bot initialization failed:", error);
process.exit(1);
}
}
// Handle graceful shutdown
process.on("SIGINT", async () => {
console.log("\nπ Shutting down bot...");
try {
await client.session.disconnect(getRequestOptions());
console.log("β
Disconnected from WhatsApp");
} catch (error) {
console.error("β Error during shutdown:", error);
}
process.exit(0);
});
// Start the bot
initializeBot();
export { app, client };