-
Notifications
You must be signed in to change notification settings - Fork 12
/
WABOT.js
1294 lines (1202 loc) · 49.3 KB
/
WABOT.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const EventEmitter = require('events');
const Merge = require('merge-anything');
const fs = require('fs');
const path = require('path');
var scrape = require('html-metadata');
const _WABOT = require('../lib/browser');
const ConvertBase64 = require('../lib/convertBase64');
const Stickers = require('../lib/stickers');
const Vcards = require('../lib/vcards');
const TYPES = require('../types/validTypes');
const types = new TYPES();
const convert64 = new ConvertBase64();
const vcard = new Vcards();
const puppeteerDefault = require('../types/puppeteer.config.json');
const intentsDefault = require('../types/intents.json');
THUMB_DEFAULT_URL = 'https://icon-library.com/images/url-icon-png/url-icon-png-20.jpg'
const Params = require('./params');
const getRandomItem = (array) => {
return array[Math.floor(Math.random()*array.length)]
}
const randomUUI = (a,b) => {for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'');return b}
const escapeRegExp = (string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const replaceAll = (str, term, replacement) => {
return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);
}
/**
*WABOT class for interact whit whatsapp web
*
* @class WABOT
* @extends {EventEmitter}
* @param {object} opts - Wabot options
* @param {object} opts.puppeteerConfig - Puppeteer launch options
* @param {string} opts.puppeteerConfig.WAUrl - Whatsapp Web Url
* @param {string} opts.puppeteerConfig.sessionPath - Path to save the session info for restore this in the future
* @param {boolean} opts.puppeteerConfig.viewBrowser - Show browser (headless)
* @param {boolean} opts.puppeteerConfig.opendevtools - Show devtools (console)
* @param {string} opts.puppeteerConfig.userAgent - User Agent for web browser
* @param {number} opts.puppeteerConfig.width - Width for web browser
* @param {number} opts.puppeteerConfig.heigth - Height for web browser
* @param {boolean} opts.puppeteerConfig.dowloadChromeVersion - Download chromium browser or use local google chome
* @param {number} opts.puppeteerConfig.chromeVersion - Version of chromium to download
* @param {string} opts.puppeteerConfig.localChromePath - Google chrome executable path
* @param {string} opts.puppeteerConfig.getInitScreenshot - Allows you to take a screenshot when you start WhatsApp in order to detect problems when running in headless mode
* @param {string} opts.puppeteerConfig.localChromePath - File name to save the screenshot
* @param {string} opts.puppeteerConfig.args - Args to open the web browser
* @param {object} opts.intentConfig - Execution and internal options
* @param {boolean} opts.intentConfig.showContent - Display chats in browser
* @param {string} opts.intentConfig.debug - Debug mode for view console logs
* @param {string[]} opts.intentConfig.removeBgApis - Api keys for https://www.remove.bg
* @param {object} opts.intentConfig.plugins - Options for plugins config
* @param {string} opts.intentConfig.plugins.folder - Folder containing the plugins
* @param {string[]} opts.intentConfig.plugins.plugins - Array containing the plugin names to use
* @param {object} opts.intentConfig.plugins.setup - Configuration of each plugin
* @param {object} opts.intentConfig.executions - Options for control chats
* @param {boolean} opts.intentConfig.executions.reponseUsers - Control response to users
* @param {boolean} opts.intentConfig.executions.simulateTyping - Simulate typing in chat
* @param {number} opts.intentConfig.executions.timeSimulate - Time in ms for simulate typing
* @param {boolean} opts.intentConfig.executions.contorlExecutions - Control chats to enqueue messages
* @param {number} opts.intentConfig.executions.maxExecutions - Max messages to process in the same time
* @param {number} opts.intentConfig.executions.timeInterval - Time in seconds to queue messages
* @param {number} opts.intentConfig.executions.timePending - Time in minutes to search for pending messages
* @param {boolean} opts.intentConfig.executions.sendSeen - Send seen ticket
* @param {boolean} opts.intentConfig.executions.sendSeenFull - Send seen ticket to all pending messages on login
* @param {number} opts.intentConfig.executions.intervalSendSeen - Time in minutes for search pending messages to send seen
* @param {object} opts.intentConfig.bann - Bann options
* @param {boolean} opts.intentConfig.bann.active - Control bann users
* @param {number} opts.intentConfig.bann.timeInterval - Time in seconds to validate spam messages
* @param {number} opts.intentConfig.bann.maxBann - Maximum number of messages allowed in the indicated amount of time
* @param {number} opts.intentConfig.bann.timeBann - Time in minutes for temporary ban
* @param {number} opts.intentConfig.bann.timeInactive - Time in minutes to release banned users who are inactive for the specified time
* @param {string[]} opts.intentConfig.bann.whiteList - List of users who will not be banned
* @param {object} opts.intentConfig.messages - Message settings
* @param {string} opts.intentConfig.messages.userBanned - Message to display when a user is banned
* @param {string} opts.intentConfig.messages.groupBanned - Message to display when a group is banned
* @param {string} opts.intentConfig.messages.privileges - Message to display when you do not have privileges to use the bot
* @param {string[]} opts.intentConfig.blocked - List of users who cannot use the bot
* @param {string[]} opts.intentConfig.whiteList - List of users who can use the bot
* @param {object[]} opts.intentConfig.commands - List of commands to evaluate in user messages
* @param {string} opts.intentConfig.commands.name - Name of the command
* @param {string[]} opts.intentConfig.commands.contains - Contains word on message
* @param {string[]} opts.intentConfig.commands.exact - Message is the same as what is contained here
* @param {object[]} opts.intentConfig.commands.params - Parameters to require
* @param {string} opts.intentConfig.commands.params.name - Name of the param
* @param {boolean} opts.intentConfig.commands.params.isNumber - Is a number param
* @param {string[]} opts.intentConfig.commands.params.request - Questions to request the parameter
* @param {string[]} opts.intentConfig.commands.params.values - Allowed values. If any is allowed, "any" must be indicated
* @param {string[]} opts.intentConfig.commands.params.badResponse - Messages to send in case of illegal values
* @param {object} opts.session - Object containing session information. Can be used to restore the session.
* @param {string} opts.session.WABrowserId
* @param {string} opts.session.WASecretBundle
* @param {string} opts.session.WAToken1
* @param {string} opts.session.WAToken2
*
* @fires WABOT#ready
* @fires WABOT#onStateChanged
* @fires WABOT#onMessageFromBloqued
* @fires WABOT#onMessageFromNoPrivileges
* @fires WABOT#waitNewAcknowledgements
* @fires WABOT#onBattery
* @fires WABOT#onPlugged
* @fires WABOT#onRemovedFromGroup
* @fires WABOT#onParticipantsChanged
* @fires WABOT#onMessageMediaUploadedEvent
* @fires WABOT#vcard
* @fires WABOT#message
* @fires WABOT#command
*/
class WABOT extends EventEmitter {
constructor(opts = {}){
super();
// Messages callbacks history
this.callbacks = [];
this.isLogged = false;
if(opts !== undefined && typeof opts === 'object'){
this.puppeterConfig = opts.puppeteerConfig || {};
this.intentConfig = opts.intentsConfig || {};
}else {
this.puppeterConfig = puppeteerDefault;
this.intentConfig = intentsDefault;
}
this.puppeteerConfig = this.mergeOpts(puppeteerDefault, this.puppeterConfig);
this.intentConfig = this.mergeOpts(intentsDefault, this.intentConfig);
this.sticker = new Stickers(this.intentConfig.removeBgApis);
// Add plugins
if (this.intentConfig.plugins.plugins.length > 0) {
this.addPlugins(this.intentConfig.plugins);
}
this._wabot = new _WABOT({
puppeteerConfig: this.puppeteerConfig,
intentConfig: this.intentConfig,
session: opts.session
});
this._wabot.on('message', (arg) => {
try {
this.getNewMessages(arg);
} catch (err) {
console.error('Error on new message', err);
}
});
this._wabot.on('onStateChanged', (arg) => {
/**
* Emitted when the connection state changes
* @event WABOT#onStateChanged
* @param {object} arg - State info
*/
this.emit('onStateChanged', arg);
});
this._wabot.on('onMessageFromBloqued', (arg) => {
/**
* Emitted when a message is received from a bloqued user
* @event WABOT#onMessageFromBloqued
* @param {object} arg - Message info
*/
this.emit('onMessageFromBloqued', arg);
});
this._wabot.on('onMessageFromNoPrivileges', (arg) => {
/**
* Emitted when a message is received from a non-privileged user
* @event WABOT#onMessageFromNoPrivileges
* @param {object} arg - Message info
*/
this.emit('onMessageFromNoPrivileges', arg);
});
this._wabot.on('waitNewAcknowledgements', (arg) => {
/**
* Emitted when a the acknowledgement state of a message changes.
* @event WABOT#waitNewAcknowledgements
* @param {object} arg
*/
this.emit('waitNewAcknowledgements', arg);
});
this._wabot.on('onBattery', (arg) => {
/**
* Emitted when the battery percentage for the attached device changes
* @event WABOT#onBattery
* @param {number} arg - The current battery percentage
*/
this.emit('onBattery', arg);
});
this._wabot.on('onPlugged', (arg) => {
/**
* Emitted when add a participant of the group
* @event WABOT#onPlugged
* @param {boolean} arg - True or False
*/
this.emit('onPlugged', arg);
});
this._wabot.on('onAddedToGroup', (arg) => {
/**
* Emitted when add a participant of the group
* @event WABOT#onAddedToGroup
* @param {object} arg
*/
this.emit('onAddedToGroup', arg);
});
this._wabot.on('onRemovedFromGroup', (arg) => {
/**
* Emitted when remove a participant of the group
* @event WABOT#onRemovedFromGroup
* @param {object} arg
*/
this.emit('onRemovedFromGroup', arg);
});
this._wabot.on('onParticipantsChanged', (arg) => {
/**
* Emitted when a participant of the group change
* @event WABOT#onParticipantsChanged
* @param {object} arg
* @param {string} arg.by
* @param {string} arg.action - Promote or Demote
* @param {string} arg.who - Id of the user
*/
this.emit('onParticipantsChanged', arg);
});
this._wabot.on('onMessageMediaUploadedEvent', (arg) => {
/**
* Emitted when media has been uploaded for a message sent by the client.
* @event WABOT#onMessageMediaUploadedEvent
* @param {object} message - The message with media that was uploaded
*/
this.emit('onMessageMediaUploadedEvent', arg);
});
this._wabot.on('ready', (session) => {
this.isLogged = true;
/**
* Emitted when WABOT is ready to work
* @event WABOT#ready
* @param {object} session Object containing session information. Can be used to restore the session.
* @param {string} session.WABrowserId
* @param {string} session.WASecretBundle
* @param {string} session.WAToken1
* @param {string} session.WAToken2
*/
this.emit('ready', session);
})
process.on('SIGINT', async () => {
console.log('Unexpected closure, we will close the browser for greater security!');
await this._wabot.destroy();
});
process.on('SIGQUIT', async () => {
console.log('Unexpected closure, we will close the browser for greater security!');
this._wabot.destroy();
});
}
mergeOpts (defaultOpts, customOpts) {
return Merge.merge(defaultOpts, customOpts);
}
emitMessage (type, arg){
switch (type) {
case 'message':
/**
* Emitted when an uncontrolled message is received
* @event WABOT#message
* @param {object} arg - Message Info
*/
this.emit('message', arg);
break;
case 'vcard':
/**
* Emitted when a vcard pis received
* @event WABOT#vcard
* @param {object} arg - Message Info
*/
this.emit('message', arg);
break;
default:
/**
* Emitted when a command is detected
* @event WABOT#command
* @param {object} arg - Message Info
*/
this.emit(type, arg);
break;
}
}
async getNewMessages(arg) {
let _this = this;
if (this.intentConfig.commands.length === 0) {
switch (arg.data.type) {
case "vcard":
vcard.extractVcard(arg.data.content)
.then(res => {
arg.data.vcard = res;
_this.emitMessage('vcard', arg);
});
break;
case "document": case "sticker": case "video": case "gif":
_this.emitMessage('message', arg);
break;
default:
_this.emitMessage('message', arg);
break;
}
} else {
switch (arg.data.type) {
case "vcard":
vcard.extractVcard(arg.data.content)
.then(res => {
arg.data.vcard = res;
_this.emitMessage('vcard', arg);
});
break;
case "sticker": case "video": case "gif":
_this.emitMessage('message', arg);
break;
case "document":
if (!await _this.validCallbackResponse({
idChat: arg.data.from,
message: arg
})){
_this.emitMessage('message', arg);
}
break;
default:
let exactMatch, PartialMatch, _match, _find;
let response = arg;
_find = false;
let _message;
if (arg.data.type === 'chat'){
_message = arg.data.body;
}else {
_message = arg.data.caption;
}
if (_message === undefined) _message = '';
exactMatch = this.intentConfig.commands.find(obj => obj.exact.find(ex => ex.toLowerCase() == _message.toLowerCase()));
if (exactMatch !== undefined) {
response.params = Params.getParams(exactMatch, '');
_match = exactMatch;
_find = true;
}else{
let exactMatch = this.intentConfig.commands.find(obj => obj.exact.find(ex => _message.toLowerCase().trim().indexOf(ex.toLowerCase().trim()) === 0));
if (exactMatch != undefined && exactMatch.params) {
let initCommand = exactMatch.exact.find(ex => _message.toLowerCase().trim().indexOf(ex.toLowerCase().trim()) === 0);
let _arguments = _message.toLowerCase().replace(initCommand.toLowerCase(), "").trim();
response.params = Params.getParams(exactMatch, _arguments);
if (typeof exactMatch.params !== 'undefined' && exactMatch.params.length > 0){
_match = exactMatch;
_find = true;
}
}else{
PartialMatch = this.intentConfig.commands.find(obj => obj.contains !== undefined && obj.contains.find(ex => _message.toLowerCase().search(ex.toLowerCase()) > -1));
if (PartialMatch != undefined) {
if (PartialMatch.isFile) PartialMatch['values'] = "any";
_match = PartialMatch;
_find = true;
}
}
}
if (!_find) {
if (!await _this.validCallbackResponse({
idChat: arg.data.from,
message: arg
})) {
_this.emitMessage('message', arg);
}
} else {
_this.releaseCallback(arg.data.from);
// Request first param else emit intent
if (_match.params && Array.isArray(_match.params) && _match.params.length > 0){
let index = Params.getNextPendingValue(_match, response.params);
if (index === 'no_data') {
_this.emitMessage(_match.name, response);
} else {
if (typeof _match.params[index] === 'object'){
_this.executeCallback({
idChat: arg.data.from,
message: arg.data,
intent: _match,
idParam: index,
values: response.params
});
} else {
_this.emitMessage(_match.name, response);
}
}
} else {
_this.emitMessage(_match.name, response);
}
}
break;
}
}
}
validCallback(args){
if (typeof this.callbacks[args.idChat] !== 'undefined'){
if (this.callbacks[args.idChat].isFinished) {
this.releaseCallback(args.idChat);
return false;
} else {
return true;
}
} else {
return false;
}
}
async validCallbackResponse(args){
if (this.validCallback({idChat: args.idChat})){
let caption = "";
if (args.message.data.type === 'chat'){
caption = args.message.data.body;
} else {
caption = args.message.data.caption;
}
caption = caption.trim().toLowerCase();
const _possibleValues = this.callbacks[args.idChat].possibleValues;
let currentParam = this.callbacks[args.idChat].currentParam;
const requireFile = this.callbacks[args.idChat].requireFile;
let response;
if (requireFile) {
if (args.message.data.type === 'document') {
const file = await this.downloadFile(args.message.data.id);
const pathFile = path.join(this.intentConfig.downloadPath, `${randomUUI()}${path.extname(args.message.data.filename)}`);
fs.writeFileSync(pathFile, file.split(';base64,').pop(), {encoding: 'base64'});
response = pathFile;
}
} else if (typeof _possibleValues === 'object'){
response = Object.keys(_possibleValues).find(key => _possibleValues[key].find(obj => obj.toLowerCase() == caption));
} else {
if ( _possibleValues === 'any' ) {
if (this.callbacks[args.idChat].intent.params[currentParam].isNumber){
try {
response = isNaN(parseInt(caption)) ? '' : parseInt(caption);
} catch (e) {
response = '';
}
} else {
response = caption;
}
}
}
if (response !== undefined && response !== '') {
let param = this.callbacks[args.idChat].intent.params[currentParam].name;
let value;
if (requireFile) value = response;
else if (typeof _possibleValues === 'object'){
if (this.callbacks[args.idChat].customValues.length > 0) {
value = this.callbacks[args.idChat].customValues[response].value;
} else {
if (typeof this.callbacks[args.idChat].intent.params[currentParam].values[response] === 'object') {
value = this.callbacks[args.idChat].intent.params[currentParam].values[response].value;
} else {
value = this.callbacks[args.idChat].intent.params[currentParam].values[response];
}
}
} else {
value = response;
}
this.callbacks[args.idChat].values[param] = value;
currentParam = Params.getNextPendingValue(this.callbacks[args.idChat].intent, this.callbacks[args.idChat].values);
if (currentParam === 'no_data') {
this.callbacks[args.idChat].isFinished = true;
let _message = args.message;
_message.params = this.callbacks[args.idChat].values;
this.emitMessage(this.callbacks[args.idChat].intent.name, _message);
} else {
this.callbacks[args.idChat].currentParam = currentParam;
this.executeCallback({
idChat: args.idChat,
message: args.message,
intent: this.callbacks[args.idChat].intent,
idParam: currentParam,
values: this.callbacks[args.idChat].values
});
}
} else {
let text = getRandomItem(this.callbacks[args.idChat].intent.params[currentParam].badResponse);
this.sendMessage({
"idChat": args.idChat,
"message": text
});
}
return true;
} else {
return false;
}
}
releaseCallback(idChat){
if (typeof this.callbacks[idChat] !== 'undefined'){
delete this.callbacks[idChat];
}
}
executeCallback(args){
let index = args.idParam;
let _values = {};
let _possibleValues = {};
let _customValues = [];
let cont = 0;
if (this.validCallback({idChat: args.idChat})){
_values = this.callbacks[args.idChat].values;
} else {
_values = args.values;
}
let isFile = false;
if (args.intent.params[index].isFile) {
isFile = args.intent.params[index].isFile;
} else if (Array.isArray(args.intent.params[index].values)){
// If custom values are configured
let valuesToDisplay = [];
if (args.intent.params[index].customValues && args.intent.params[index].customValues.length > 0) {
args.intent.params[index].customValues.forEach(customValue => {
if (_values[customValue.param] !== undefined
&& _values[customValue.param] === customValue.paramValue
) {
_customValues.push(customValue);
valuesToDisplay.push(customValue);
}
})
}
if (valuesToDisplay.length === 0) {
valuesToDisplay = args.intent.params[index].values;
}
valuesToDisplay.forEach((value) => {
if (typeof value === 'object'){
_possibleValues[cont] = [(cont+1).toString(), value.display, value.value];
} else {
_possibleValues[cont] = [(cont+1).toString(), value];
}
++cont;
});
} else {
if (args.intent.params[index].values === 'any'){
_possibleValues = "any";
}
}
this.callbacks[args.idChat] = {
message: args.message,
intent: args.intent,
currentParam: index,
isFinished: false,
requireFile: isFile,
possibleValues: _possibleValues,
values: _values,
customValues: _customValues
}
let text = getRandomItem(args.intent.params[index].request) + String.fromCharCode(10);
for (var i=0; i<cont; i++){
let options = [];
options.push(_possibleValues[(i).toString()][0]);
options.push(_possibleValues[(i).toString()][1]);
//text += _possibleValues[(i).toString()].join('.- ') + String.fromCharCode(10);
text += options.join('.- ') + String.fromCharCode(10);
}
this.sendMessage({
"idChat": args.idChat,
"message": text
});
}
addPlugins (plugins) {
if (Array.isArray(plugins.plugins)) {
// Read plugins folder
const pathPlugins = path.join(__dirname, plugins.folder || '../plugins/');
fs.readdir(pathPlugins, (err, files) => {
if (err) {
console.error('Error reading plugins directory');
} else {
let pluginsFiles = [];
files.forEach(file => {
if (file.indexOf('.js') !== -1){
const {id, setup, plugin, init} = require(path.join(pathPlugins, file));
const metadata = {
id: id,
setup: setup,
init: init,
plugin: plugin
};
pluginsFiles.push(metadata);
}
});
plugins.plugins.forEach(plugin => {
const pluginFile = pluginsFiles.find(el => el.id === plugin);
if (pluginFile !== undefined) {
Object.assign(this, {
[pluginFile.id]: pluginFile.plugin
});
if (typeof pluginFile.init !== 'undefined') {
pluginFile.init();
}
if (typeof plugins.setup[plugin] !== 'undefined') {
pluginFile.setup(plugins.setup[plugin]);
}
}
})
}
});
}
}
/**
* Send list of commands
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.prefix - Prefix message
* @param {string} args.postfix - Postfix message
*/
sendCommands(args) {
if (this.intentConfig.commands && this.intentConfig.commands.length > 0) {
let helpText = `${args.prefix || ''} \n `;
this.intentConfig.commands.forEach(command => {
if (command.description && command.description !== '') {
if (command.exact && command.exact.length > 0) {
helpText += `- *${command.exact[0]}* - ${command.description} \n `;
} else {
helpText += `- ${command.description} \n `;
}
}
});
helpText += `${args.postfix || ''}`;
if (helpText !== '') {
this.sendMessage({
"idChat": args.idChat,
"message": helpText
});
}
}
}
addCommand (command) {
this.intentConfig.commands.push(command);
}
deleteCommand (commandName) {
this.intentConfig.commands = this.intentConfig.commands.filter(el => el.name !== commandName);
}
/**
* Send text as image
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.message - Message to send
*/
sendMessage(args){
let data = types.valid('text', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
}
/**
* Download file from message received from others users
* @param {string} idMessage - Message id containing the file to download
*
* @returns {Promise<string>} file in base64 or error message
*/
async downloadFile(idMessage){
return new Promise(async (resolve, reject) => {
this._wabot.downloadFile(idMessage)
.then((file) => {
resolve(file);
})
.catch((err) => {
reject(err);
});
});
}
/**
* Send text as image
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.message - Message to convert into image
*/
sendText2Image(args){
let data = types.valid('text2image', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
}
/**
* Send a image file
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.file - Url, base64 or path to the file
*/
sendImage(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
convert64.convert(args.file)
.then(res => {
args.file = res;
let data = types.valid('image', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error converting to base64.`, err);
})
}
}
/**
* Send a file
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.file - Url, base64 or path to the file
*/
sendFile(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
convert64.convert(args.file)
.then(res => {
args.file = res;
let data = types.valid('document', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error converting to base64.`, err);
})
}
}
/**
* Send a video file
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.file - Url, base64 or path to the file
*/
sendVideo(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
convert64.convert(args.file)
.then(res => {
args.file = res;
let data = types.valid('video', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error converting to base64.`, err);
})
}
}
/**
* Send a gif file
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.file - Url, base64 or path to the file
*/
sendGif(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
convert64.convert(args.file)
.then(res => {
args.file = res;
let data = types.valid('gif', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error converting to base64.`, err);
})
}
}
/**
* Send a music file
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.file - Url, base64 or path to the file
*/
sendMusic(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
convert64.convert(args.file)
.then(res => {
args.file = res;
args.fileType = 'music';
let data = types.valid('music', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error converting to base64.`, err);
})
}
}
/**
* Send a link
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.caption - Caption to display in the message
* @param {string} args.link - Url to send
*/
sendLink(args){
let data = types.valid('link', args);
if (data.isValid){
if (args.thumb && args.thumb !== '') {
this._wabot.sendMessage(data.data);
} else {
const _this = this;
scrape(args.link, function(error, metadata){
if(!error){
if(typeof metadata.openGraph != 'undefined' && metadata.openGraph != undefined){
const title = metadata.openGraph.title || "News";
const description = metadata.openGraph.description || "";
const urlNews = metadata.openGraph.url || args.link;
let urlImage;
if(typeof metadata.openGraph.image.url != "undefined" && metadata.openGraph.image.url != undefined && metadata.openGraph.image.url != ""){
urlImage = metadata.openGraph.image.url;
}else{
urlImage = THUMB_DEFAULT_URL;
}
const info = data.data;
info.description = description;
info.title = title;
info.link = urlNews;
convert64.convert(urlImage)
.then(res => {
info.thumb = res;
_this._wabot.sendMessage(info);
})
.catch(err => {
info.thumb = '';
_this._wabot.sendMessage(info);
})
}
} else {
console.error(data.messageInvalid);
}
});
}
}else {
console.error(data.messageInvalid);
}
}
/**
* Send a sticker
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.file - Url, base64 or Path of the image (with or without background)
*/
sendSticker(args){
if (typeof args.file !== 'undefined' && args.file !== ''){
this.sticker.makeSticker(args.file)
.then(res => {
args.file = res.file;
let data = types.valid('sticker', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
})
.catch(err => {
console.error(`Error creating sticker.`, err);
})
}
}
/**
* Send a location
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.lat - Latitude of the location
* @param {string} args.lng - Location of the location
* @param {string} args.title - Title to display
*/
sendLocation(args){
let data = types.valid('location', args);
if (data.isValid){
this._wabot.sendMessage(data.data);
}else {
console.error(data.messageInvalid);
}
}
/**
* Send a contact as vcard
* @param {object} args - The message info
* @param {string} args.idChat - Id Chat
* @param {string} args.idMessage - Id of message to reply
* @param {string} args.contactName - Contact Name to display
* @param {object} args.vcard - Contact info
* @param {string} args.vcard.firstName - First Name
* @param {string} args.vcard.middleName - Middle Name
* @param {string} args.vcard.lastName - Last Name
* @param {string} args.vcard.organization - Organization
* @param {string} args.vcard.birthday - Dirthday date
* @param {string} args.vcard.title - Title to display
* @param {string} args.vcard.url - Url
* @param {string} args.vcard.note - Note
* @param {string} args.vcard.nickname - Nickname
* @param {string} args.vcard.namePrefix - Name Prefix
* @param {string} args.vcard.nameSuffix - Name Suffix
* @param {string} args.vcard.gender - Gender
* @param {string} args.vcard.role - Role
* @param {string} args.vcard.homePhone - Home Phone
* @param {string} args.vcard.workPhone - Work Phone
* @param {string} args.vcard.cellPhone - Cell Phone
* @param {string} args.vcard.pagerPhone - Pager Phone
* @param {string} args.vcard.homeFax - Home Fax
* @param {string} args.vcard.workFax - Work Fax
* @param {string} args.vcard.email - Email
* @param {string} args.vcard.workEmail - Work Email
* @param {string} args.vcard.socialUrlsFacebook - Social Urls Facebook
* @param {string} args.vcard.socialUrlsLinkedin - Social Urls Linkedin
* @param {string} args.vcard.socialUrlsTwitter - Social Urls Twitter
* @param {string} args.vcard.socialUrlsFlickr - Social Urls Flickr
* @param {string} args.vcard.socialUrlsCustom - Social Urls Custom
* @param {string} args.vcard.homeAddressLabel - Home Address Label
* @param {string} args.vcard.homeAddressStreet - Home Address Street
* @param {string} args.vcard.homeAddressCity - Home Address City
* @param {string} args.vcard.homeAddressStateProvince - Home Address State Province
* @param {string} args.vcard.homeAddressPostalCode - Home Address Postal Code
* @param {string} args.vcard.homeAddressCountryRegion - Home Address Country Region
* @param {string} args.vcard.workAddressLabel - Work Address Label
* @param {string} args.vcard.workAddressStreet - Work Address Street
* @param {string} args.vcard.workAddressCity - Work Address City
* @param {string} args.vcard.workAddressStateProvince - Work Address State Province
* @param {string} args.vcard.workAddressPostalCode - Work Address Postal Code
* @param {string} args.vcard.workAddressCountryRegion - Work Address Country Region
* @param {string} args.vcard.photo - Photo (url or path)
*/
sendVcard(args){
let data = types.valid('vcard', args);
if (data.isValid){
let _vcard = vcard.createVcard(data.data.vcard);
data.data.vcard = _vcard;
this._wabot.sendMessage(data.data);
}else {