-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
617 lines (572 loc) Β· 19.7 KB
/
index.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//reffer wwebjs documentation and do changes as you want.
//also reffer docummentation https://beta.openai.com/docs/api-reference/completions
//and get api key from https://beta.openai.com/account/api-keys and save it into your system as OPENAI_API_KEY as a environment variable (windows only). in linux paste it directly here
const { Configuration, OpenAIApi } = require("openai");
const qrcode = require("qrcode-terminal");
const mime = require("mime-types");
const fs = require("fs");
const translate = require("google-translate-api-x");
const {
Client,
LocalAuth,
MessageMedia,
Buttons,
List,
} = require("whatsapp-web.js");
const client = new Client({
authStrategy: new LocalAuth(),
puppeteer: { args: ["--no-sandbox", "--disable-setuid-sandbox"] },
ffmpeg: "/usr/bin/ffmpeg", //This is linux default ffmpeg path || in winodws after extracting ffmpeg.exe to this path change this to ./ffmpeg
});
client.on("qr", (qr) => {
qrcode.generate(qr, { small: true });
});
client.on("loading_screen", (percent, message) => {
console.log("LOADING SCREEN", percent, message);
});
client.on("qr", (qr) => {
// NOTE: This event will not be fired if a session is specified.
console.log("QR RECEIVED", qr);
});
client.on("authenticated", () => {
console.log("AUTHENTICATED");
});
client.on("auth_failure", (msg) => {
// Fired if session restore was unsuccessful
console.error("AUTHENTICATION FAILURE", msg);
});
client.on("ready", () => {
console.log("READY");
});
client.initialize();
client.on("message", async (msg) => {
let chat = await msg.getChat();
chat.sendSeen();
//console.log("MESSAGE RECEIVED", msg);
//These two are for get openai responses with quoting previous message from bot. These two can do kinda continuous chat as they reads previous message from bot
//first one is for private chats and it gets sarcastic replies, using openai marv the sarcastic bot example
if (!chat.isGroup) {
if (msg.hasQuotedMsg) {
if (!msg.body.startsWith("!")) {
if (msg.type === "chat") {
const quotedMsg = await msg.getQuotedMessage();
if (quotedMsg.fromMe) {
msg.react("π¬");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
//use your bot name here in Botname
prompt:
`Botname is a chatbot that reluctantly answers questions with sarcastic responses: \nBotname: ${quotedMsg.body}\n\nYou:` +
msg.body +
`\nBotname:`,
temperature: 0.5, //you can change these values reffering api documentation and openai examples
max_tokens: 60,
top_p: 0.3,
frequency_penalty: 0.5,
presence_penalty: 0,
user: msg.author,
});
//console.log(completion.data.choices[0].text);
setTimeout(() => {
msg.react("β
");
msg.reply(completion.data.choices[0].text);
}, 300);
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
} else {
console.log(error.message);
}
}
}
}
}
}
}
//second one is for group chats and it gets helpful replies, using chat example
if (chat.isGroup) {
if (msg.hasQuotedMsg) {
if (!msg.body.startsWith("!")) {
if (msg.type === "chat") {
const quotedMsg = await msg.getQuotedMessage();
if (quotedMsg.fromMe) {
msg.react("π¬");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
//here also use your bot name
prompt:
`The following is a conversation with Botname. Botname is helpful, creative, clever, and very friendly.\nBotname: ${quotedMsg.body}\n\nHuman:` +
msg.body +
`\nBotname:`,
temperature: 0.9,
max_tokens: 250,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.6,
stop: [" Human:", " Botname:"],
user: msg.author,
});
//console.log(completion.data.choices[0].text);
setTimeout(() => {
msg.react("β
");
msg.reply(completion.data.choices[0].text);
}, 300);
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
} else {
console.log(error.message);
}
}
}
}
}
}
}
//check bot alive
if (msg.body === "!bot") {
msg.react("π");
msg.reply('I am here. Type & send "!help" to get all commands');
}
//check bot commands
else if (msg.body === "!help") {
let chat = await msg.getChat();
const media = MessageMedia.fromFilePath("/root/wabot/bibi.png"); //I have sent image with !help command
chat.sendMessage(media, {
caption: `π° *Hello I am Botname the Bot* π°
β¬οΈCommandsβ¬οΈ
_!tagall_
_!sticker_
_!groupinfo_
_!botinfo_
_!bot ..._ (start any message with !bot)
_!gen ..._ (Dall-E image generation)
_!code ..._ (Code check)
_!traen_ (Translate to English)
_!trasin_ (Translate to Sinhala)
_!chats_ (Chats that opened within bot)
_!id_ (Id of a group or chat)
_!sendowner ..._ (Send message to owner)
_Also send any message mentioning my previous message for like AI assistant in groups and Sarcastic replies in private chats_
`,
});
}
//reply to hi and also !bot, !code !gen commands who use without any text
else if (
msg.body === "Hi" ||
msg.body === "hi" ||
msg.body === "!bot" ||
msg.body === "!gen" ||
msg.body === "!code"
) {
setTimeout(() => {
msg.react("π");
msg.reply("Hi there. How can I help you?");
}, 400);
}
//get bot info
else if (msg.body === "!botinfo") {
let info = client.info;
msg.reply(
client.sendMessage(
msg.from,
`
*Bot info*
User name: ${info.pushname}
Platform: ${info.platform}
My number: ${info.wid.user}
_This bot is based on the WhatsApp-Web.js and can do many things. Type !help to get commands_
`
)
);
}
// Direct send a new message to owner only from private chats
else if (msg.body.startsWith("!sendowner ")) {
msg.react("ποΈ");
if (!chat.isGroup) {
const contact = await msg.getContact();
let message = msg.body.slice(11);
let number = `[email protected]`; //owners number
setTimeout(() => {
msg.react("β
");
msg.reply("Done. Sent to owner");
client.sendMessage(
number,
`${contact.pushname}
${contact.id.user}
${message}`
);
}, 800);
}
}
// Direct send a new message to specific id
// This is useful when someone use sendowner command and send owner a message
// Use number and message afer .sendton like .sendton 947xxxxxxxx hello
else if (msg.body.startsWith(".sendton ")) {
let number = msg.body.split(" ")[1];
let messageIndex = msg.body.indexOf(number) + number.length;
let message = msg.body.slice(messageIndex, msg.body.length);
number = number.includes("@c.us") ? number : `${number}@c.us`;
setTimeout(() => {
msg.react("β
");
client.sendMessage(
number,
`π° *Message from owner* π°
β¬οΈ
${message}`
);
}, 500);
}
// Get how many chats opened in bot
else if (msg.body === "!chats") {
const chats = await client.getChats();
setTimeout(() => {
msg.react("β
");
client.sendMessage(msg.from, `I have ${chats.length} chats open.`);
}, 400);
}
// Get id of a chat
else if (msg.body === "!id") {
let id = chat.id.user;
let number = `[email protected]`; //this is owners number and this will send owner the id
msg.react("β
");
client.sendMessage(number, id);
//console.log(id) // can get console also
}
//join or leave
else if (msg.body === "!leave") {
//Any admin can remove bot from group
// Leave the group
const authorId = msg.author;
let chat = await msg.getChat();
if (chat.isGroup) {
for (let participant of chat.participants) {
if (participant.id._serialized === authorId && participant.isAdmin) {
chat.leave();
}
}
} else {
msg.reply("This command can only be used in a group and admins.");
}
} else if (msg.body.startsWith("!joinlink ")) {
// Send .joinlink group link to join. but use any other as this can be used by anyone
const inviteLink = msg.body.split(" ")[1];
inviteCode = inviteLink.replace("https://chat.whatsapp.com/", "");
try {
await client.acceptInvite(inviteCode);
msg.react("β
");
msg.reply("Joined the group.");
} catch (e) {
msg.reply("That invite link seems to be invalid.");
}
}
//make whatsapp stickers
//ffmpeg required
else if (msg.body === "!sticker") {
const contact = await msg.getContact();
if (msg.hasMedia) {
msg.react("β
");
msg.downloadMedia().then((media) => {
if (media) {
const mediaPath = "./downloaded-media/";
if (!fs.existsSync(mediaPath)) {
fs.mkdirSync(mediaPath);
}
const extension = mime.extension(media.mimetype);
const filename = new Date().getTime();
const fullFilename = mediaPath + filename + "." + extension;
// Save to file
try {
fs.writeFileSync(fullFilename, media.data, {
encoding: "base64",
});
console.log("File downloaded successfully!", fullFilename);
console.log(fullFilename);
MessageMedia.fromFilePath((filePath = fullFilename));
client.sendMessage(
msg.from,
new MessageMedia(media.mimetype, media.data, filename),
{
sendMediaAsSticker: true,
stickerAuthor: `${contact.pushname}`,
stickerName: "Created by Botname Bot to",
}
);
fs.unlinkSync(fullFilename);
console.log(`File Deleted successfully!`);
} catch (err) {
console.log("Failed to save the file:", err);
console.log(`File Deleted successfully!`);
}
}
});
} else {
msg.react("π«");
msg.reply(`send image/video/gif with caption *!sticker* `);
}
}
//get group info
else if (msg.body === "!groupinfo") {
let chat = await msg.getChat();
if (chat.isGroup) {
msg.reply(`
*Group Details*
Name: ${chat.name}
Description: ${chat.description}
Created At: ${chat.createdAt.toString()}
Created By: ${chat.owner.user}
Participant count: ${chat.participants.length}
`);
} else {
msg.reply("This command can only be used in a group!");
}
}
//mentioning all group members
else if (msg.body === "!tagall") {
const authorId = msg.author;
let chat = await msg.getChat();
if (chat.isGroup) {
for (let participant of chat.participants) {
if (participant.id._serialized === authorId && participant.isAdmin) {
let mentions = [];
for (let participant of chat.participants) {
const contact = await client.getContactById(
participant.id._serialized
);
mentions.push(contact);
}
let quotedMsg = await msg.getQuotedMessage();
//send quoted msg with mentioning
if (quotedMsg) {
msg.react("π");
await chat.sendMessage(quotedMsg.body, { mentions });
break;
} else {
//send a msg with mentioning
msg.react("π·οΈ");
await chat.sendMessage("An admin mentioned all members", {
mentions,
});
break;
}
} else if (
participant.id._serialized === authorId &&
!participant.isAdmin
) {
if (msg.body === "!tagall") {
msg.react("π«");
msg.reply("The command can only be used by group admins.");
break;
}
}
}
}
}
//connected openai - chat
else if (msg.body.startsWith("!bot ")) {
if (
//had use this because sometimes hi hello gets weird replies
msg.body.startsWith("!bot Hi ") ||
msg.body.startsWith("!bot hi ") ||
msg.body.startsWith("!bot Hello ") ||
msg.body.startsWith("!bot hello ") ||
msg.body.startsWith("!bot Hey ") ||
msg.body.startsWith("!bot hey ") ||
msg.body === "!bot Hi" ||
msg.body === "!bot Hi " ||
msg.body === "!bot hi" ||
msg.body === "!bot hi " ||
msg.body === "!bot Hello" ||
msg.body === "!bot Hello " ||
msg.body === "!bot hello" ||
msg.body === "!bot hello " ||
msg.body === "!bot Hey" ||
msg.body === "!bot Hey " ||
msg.body === "!bot hey" ||
msg.body === "!bot hey "
) {
setTimeout(() => {
msg.react("π");
msg.reply("Hi there. How can I help you?");
}, 400);
} else {
msg.react("π¬");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: msg.body.slice(4),
temperature: 0.9,
max_tokens: 1000,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.6,
user: msg.author,
});
//console.log(completion.data.choices[0].text);
setTimeout(() => {
msg.react("β
");
msg.reply(completion.data.choices[0].text);
}, 300);
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
} else {
console.log(error.message);
}
}
}
}
//openai Dall e image gen
//reffer docummentation https://beta.openai.com/docs/api-reference/images/create and change values
else if (msg.body.startsWith("!gen ")) {
let chat = await msg.getChat();
msg.react("π¬");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
try {
const response = await openai.createImage({
prompt: msg.body.slice(5),
n: 1,
size: "1024x1024",
});
image_url = response.data.data[0].url;
const media = await MessageMedia.fromUrl(image_url);
msg.reply(media);
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
msg.reply(
"Your request was rejected as a result of our safety system. Your prompt may contain text that is not allowed by our safety system."
);
} else {
console.log(error.message);
}
}
}
//reffer documentation and change values
else if (msg.body.startsWith("!code ")) {
msg.react("π¬");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
try {
const completion = await openai.createCompletion({
model: "code-davinci-002",
prompt: msg.body.slice(6),
temperature: 0,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
user: msg.author,
});
//console.log(completion.data.choices[0].text);
setTimeout(() => {
msg.react("β
");
msg.reply(completion.data.choices[0].text);
}, 300);
} catch (error) {
if (error.response) {
console.log(error.response.status);
msg.reply("Invalid request or Limit reached. Try again later....");
console.log(error.response.data);
} else {
console.log(error.message);
}
}
}
//https://cloud.google.com/translate/docs/languages you can get language codes from here
//Translate any language to English
else if (msg.body.startsWith("!traen ")) {
msg.react("ποΈ");
prompt = msg.body.slice(7);
const res = await translate(`${prompt}`, { to: "en", autoCorrect: true });
setTimeout(() => {
msg.react("β
");
msg.reply(res.text);
}, 300);
}
//Translate any language to Sinhala
else if (msg.body.startsWith("!trasin ")) {
msg.react("ποΈ");
prompt = msg.body.slice(8);
const res = await translate(`${prompt}`, { to: "si", autoCorrect: true });
setTimeout(() => {
msg.react("β
");
msg.reply(res.text);
}, 300);
}
//These are for Used for exchanging papers in my group . But contains how to send media from URl , Buttons & Lists
else if (msg.body === "!deadlines") {
let chat = await msg.getChat();
const media = await MessageMedia.fromUrl("image or any file url link");
chat.sendMessage(media, {
caption: "Caption ",
});
}
// Buttons
else if (msg.body === "!papers") {
let button1 = new Buttons(
"Body",
[{ body: "button name" }],
"Header",
"Footer"
);
client.sendMessage(msg.from, button1);
}
//List
else if (msg.body === "button name") {
let sections = [
{
title: "List title",
rows: [
{ title: "1" },
{ title: "2" },
{ title: "3" },
{ title: "4" },
{ title: "5" },
],
},
];
let list1 = new List("List body", "Click Here", sections);
await client.sendMessage(msg.from, list1);
}
//sending local files
else if (msg.body === "1") {
const media = MessageMedia.fromFilePath("file path");
chat.sendMessage(media, { caption: "caption" });
} else if (msg.body === "2") {
const media = MessageMedia.fromFilePath("file path");
chat.sendMessage(media, { caption: "caption" });
} else if (msg.body === "3") {
const media = MessageMedia.fromFilePath("file path");
chat.sendMessage(media, { caption: "caption" });
} else if (msg.body === "4") {
const media = MessageMedia.fromFilePath("file path");
chat.sendMessage(media, { caption: "caption" });
} else if (msg.body === "5") {
const media = MessageMedia.fromFilePath("file path");
chat.sendMessage(media, { caption: "caption" });
}
});