-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbasic-usage.js
More file actions
259 lines (225 loc) Β· 8.38 KB
/
basic-usage.js
File metadata and controls
259 lines (225 loc) Β· 8.38 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// Basic usage example for WuzAPI client
// This example shows how to set up and use the WuzAPI client
// with both traditional (global token) and flexible (per-request token) approaches
import WuzapiClient from "wuzapi";
// Method 1: Traditional usage with global token
const adminClient = new WuzapiClient({
apiUrl: "http://localhost:8080", // Your WuzAPI server URL
token: "your-user-token-here", // Your user authentication token
});
// Method 2: Flexible usage - no global token (or admin token as default)
const userClient = new WuzapiClient({
apiUrl: "http://localhost:8080", // Your WuzAPI server URL
// token is optional - can be provided per request
});
// For this example, we'll use the traditional approach
const client = adminClient;
async function basicExample() {
try {
console.log("π Connecting to WuzAPI...");
// Test connectivity
const isConnected = await client.ping();
if (!isConnected) {
console.error("β Cannot connect to WuzAPI server");
return;
}
console.log("β
Connected to WuzAPI server");
// Optional: Configure proxy before connecting (uncomment if needed)
/*
console.log("π§ Configuring proxy...");
try {
await client.session.setProxy("socks5://username:password@proxy-server:1080", true);
console.log("β
Proxy configured");
} catch (proxyError) {
console.log("β οΈ Proxy configuration failed:", proxyError.message);
}
*/
// Connect to WhatsApp
console.log("π Connecting to WhatsApp...");
await client.session.connect({
Subscribe: ["Message", "ReadReceipt"],
Immediate: false,
});
// Check connection status
const status = await client.session.getStatus();
console.log("π± WhatsApp Status:", {
connected: status.Connected,
loggedIn: status.LoggedIn,
});
// If not logged in, offer options: QR code or phone pairing
if (status.Connected && !status.LoggedIn) {
console.log("π± Not logged in. Choose login method:");
// Option 1: QR Code (traditional)
console.log("π· Option 1: QR Code login");
const qr = await client.session.getQRCode();
console.log("π· Scan this QR code with WhatsApp:", qr.QRCode);
console.log("β³ Waiting for QR code scan...");
// Option 2: Phone pairing (alternative)
console.log("\nπ Option 2: Phone pairing");
console.log("π‘ To use phone pairing instead:");
console.log(" 1. Uncomment the pairPhone example below");
console.log(" 2. Replace with your phone number");
console.log(" 3. You'll receive an SMS/call with verification code");
/*
// Phone pairing example - uncomment and modify:
try {
const phoneNumber = "5491155554444"; // Your phone number with country code
console.log(`π± Requesting pairing code for ${phoneNumber}...`);
// This will generate a pairing code that will be sent via SMS/call
const pairResult = await client.session.pairPhone(phoneNumber);
console.log("β
Pairing result:", pairResult.Details);
console.log("π± Check your phone for verification code and enter it in WhatsApp");
} catch (pairError) {
console.error("β Phone pairing failed:", pairError.message);
}
*/
}
// Example: Send a text message (uncomment when ready)
/*
if (status.LoggedIn) {
console.log('π€ Sending test message...');
const response = await client.chat.sendText({
Phone: '5491155554444', // Replace with actual phone number
Body: 'Hello from WuzAPI! π'
});
console.log('β
Message sent:', response.Id);
}
*/
// Example: Get user contacts
if (status.LoggedIn) {
console.log("π Getting contacts...");
const contacts = await client.user.getContacts();
console.log(`π Found ${Object.keys(contacts).length} contacts`);
}
// Example: List groups
if (status.LoggedIn) {
console.log("π₯ Getting groups...");
const groups = await client.group.list();
console.log(`π₯ Found ${groups.Groups.length} groups`);
}
// Example: Request message history sync (useful after login)
if (status.LoggedIn) {
console.log("π Requesting message history sync...");
try {
await client.session.requestHistory();
console.log("β
History sync requested");
} catch (error) {
console.log("β οΈ History sync failed:", error.message);
}
}
// Advanced examples (uncomment to test)
if (status.LoggedIn) {
console.log("\nπ Advanced features available:");
console.log("π Uncomment below to test new message types:");
/*
// Interactive buttons example
await client.chat.sendButtons({
Phone: '5491155554444',
Body: 'Choose an option:',
Footer: 'WuzAPI Bot',
Buttons: [
{ ButtonId: 'btn1', ButtonText: { DisplayText: 'Option 1' }, Type: 1 },
{ ButtonId: 'btn2', ButtonText: { DisplayText: 'Option 2' }, Type: 1 }
]
});
// List message example
await client.chat.sendList(
'5491155554444', // Phone
'View Options', // Button text
'Select from menu:', // Description
'Menu', // Top text/title
[{ // Sections
Title: 'Options',
Rows: [
{ Title: 'Option A', Desc: 'First option', RowId: 'opt_a' },
{ Title: 'Option B', Desc: 'Second option', RowId: 'opt_b' }
]
}]
);
// Poll example (for groups only)
await client.chat.sendPoll(
'120362023605733675@g.us', // Group JID (replace with actual group)
'Favorite color?', // Header
['Red', 'Blue', 'Green'] // Options array
);
*/
}
} catch (error) {
console.error("β Error:", error.message);
if (error.code) {
console.error("π Error code:", error.code);
}
if (error.details) {
console.error("π Error details:", error.details);
}
}
}
// Example with flexible token usage
async function flexibleTokenExample() {
try {
console.log("\nπ§ Flexible Token Usage Example");
console.log("=================================");
// Use the flexible client
const userToken = "user-specific-token-here";
const adminToken = "admin-token-here";
// Test connectivity with user token
const isConnected = await userClient.ping({ token: userToken });
if (!isConnected) {
console.error("β Cannot connect to WuzAPI server");
return;
}
console.log("β
Connected to WuzAPI server with user token");
// Connect to WhatsApp with user token
console.log("π Connecting to WhatsApp with user token...");
await userClient.session.connect(
{
Subscribe: ["Message", "ReadReceipt"],
Immediate: false,
},
{ token: userToken }
);
// Check status with user token
const status = await userClient.session.getStatus({ token: userToken });
console.log("π± WhatsApp Status:", {
connected: status.Connected,
loggedIn: status.LoggedIn,
});
// Send message with user token
if (status.LoggedIn) {
console.log("π€ Sending message with user token...");
// Uncomment and update phone number when ready
/*
const response = await userClient.chat.sendText(
{
Phone: '5491155554444',
Body: 'Hello from flexible token usage! π'
},
{ token: userToken }
);
console.log('β
Message sent:', response.Id);
*/
}
// Admin operations with admin token
console.log("π¨βπΌ Performing admin operations with admin token...");
try {
const users = await userClient.admin.listUsers({ token: adminToken });
console.log(`π₯ Found ${users.length} users in system`);
} catch (error) {
console.log("β οΈ Admin operations require valid admin token");
}
console.log("β
Flexible token example completed");
} catch (error) {
console.error("β Error in flexible token example:", error.message);
if (error.code === 401) {
console.error("π Authentication error - check your tokens");
}
}
}
// Run the examples
console.log("Running WuzAPI Basic Usage Examples");
console.log("==================================\n");
// Uncomment the example you want to run:
// Traditional usage
basicExample();
// Flexible token usage
// flexibleTokenExample();