-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggrobot.vpp.js
3048 lines (2521 loc) · 124 KB
/
aggrobot.vpp.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
// ==VPPScript==
// @name AggroBot
// @version 1.2.0
// @script-filename aggrobot.vpp.js
// @update-url https://raw.githubusercontent.com/SimpleCreations/aggrobot/master/update.json
// @script-url https://raw.githubusercontent.com/SimpleCreations/aggrobot/master/aggrobot.vpp.js
// @database-url https://raw.githubusercontent.com/SimpleCreations/aggrobot/master/database.json
// ==/VPPScript==
const log = message => VPP.chats[0].log(`[AggroBot] ${message}`);
const compareVersions = (version1, version2) => {
version1 = version1.split(".");
version2 = version2.split(".");
for (let i = 0; i < version2.length; i++) {
if (!version1[i] || +version2[i] > +version1[i]) return 1;
else if (+version2[i] < +version1[i]) return -1;
}
return version2.length != version1.length ? -1 : 0;
};
log("Проверка обновлений...");
$.ajax({
url: VPPScript.meta["update-url"],
dataType: "json",
cache: false
}).pipe(response => response["script_version"] ? response : $.Deferred().reject()).done(response => {
if (compareVersions(response["script_version"], VPPScript.meta["version"]) < 0) {
return log(`Вы используете устаревший скрипт.<br>
Текущая версия: ${VPPScript.meta["version"]}<br>
Последняя версия: ${response["script_version"]}<br>
Введите "/aggrobot download", чтобы скачать последнюю версию.`);
}
log("Вы используете последнюю версию скрипта.");
if (!response["database_version"]) return log("Не удалось получить последнюю версию базы сообщений.");
const currentDatabaseVersion = VPPScript.storage.databaseVersion;
if (!currentDatabaseVersion || compareVersions(response["database_version"], currentDatabaseVersion) < 0) {
log(!currentDatabaseVersion ? "Идёт скачивание базы сообщений..." : "Идёт обновление базы сообщений...");
$.ajax({
url: VPPScript.meta["database-url"],
dataType: "json",
cache: false
}).done(database => {
VPPScript.storage.database = database;
VPPScript.storage.databaseVersion = response["database_version"];
VPPScript.storage.save();
log("База сообщений успешно " + (!currentDatabaseVersion ? "загружена." : "обновлена."));
enableScript();
}).fail(() => {
log("Не удалось скачать базу сообщений.");
if (currentDatabaseVersion) enableScript();
});
VPP.chats.forEach(chat =>
chat.addEventListener(VPP.Chat.Event.CONNECTED, "aggrobot", () =>
chat.log("[AggroBot] Скрипт начнёт работу только по завершении загрузки базы сообщений.")));
}
else enableScript();
}).fail(() => log("Не удалось получить данные об обновлении."));
const enableScript = () => {
let firstDatabase = null;
VPP.chats.forEach(chat => {
const aggroBot = new AggroBot();
chat.aggroBot = aggroBot;
const database = !firstDatabase ? (firstDatabase = AggroBot.Database.fromRaw(VPPScript.storage.database)) :
AggroBot.Database.fromAnother(firstDatabase);
aggroBot.setDatabase(database);
aggroBot.onTypingStart = () => chat.isChatStarted() && chat.setStartedTyping();
aggroBot.onTypingFinish = () => chat.isChatStarted() && chat.setFinishedTyping();
aggroBot.onMessageReady = message => chat.isChatStarted() && chat.sendMessage(message);
aggroBot.onConversationFinish = () => {
aggroBot.suspend();
chat.isChatStarted() && chat.close();
};
aggroBot.onReport = message => chat.log(message);
aggroBot.onImageReady = imageURL => {
if (!chat.isChatStarted()) return;
const chatId = chat.chatId;
const image = new VPP.Image(imageURL);
image.onLoad = () => {
image.onUpload = () => chat.chatId == chatId && chat.sendImage(image);
image.upload();
};
};
chat.removeEventListener("aggrobot");
chat.addEventListener(VPP.Chat.Event.CONNECTED, "aggrobot", () => {
// Генерируем новое состояние бота и готовим приветственное сообщение
chat.messageSent = false;
chat.aggrobotWasActive = false;
if (AggroBot.autoStart) {
aggroBot.reset();
chat.aggrobotWasActive = true;
}
// Обращаемся к деанонимайзеру
if (AggroBot.deanonEnabled && AggroBot.deanonURL) {
// Если включён деанонимайзер, то ожидаем ответа от него в течение некоторого времени перед тем, как запрашивать приветствие
const chatId = chat.chatId;
let responseRequested = false;
setTimeout(() =>
!responseRequested && (responseRequested = true) &&
chat.chatId == chatId && !aggroBot.messagesReceived && aggroBot.prepareResponse(), 1750);
VPP.ajax({
url: AggroBot.deanonURL,
data: {
guid: chat.guidOpp
},
cache: false,
success: function(response) {
if (chat.chatId != chatId) return;
response = JSON.parse(response);
if (Array.isArray(response["log"])) response["log"].forEach(row => console.log("%c" + row, "color: #AA0000;"));
if (!response["gender"] && !response["name"] && !response["vk"]) chat.log("Деанонимайзер не нашёл данных об этом пользователе");
else aggroBot.processDeanonResult((gender => {
return gender == "male" ? AggroBot.UserProfile.Gender.MALE :
gender == "female" ? AggroBot.UserProfile.Gender.FEMALE : undefined;
})(response["gender"]), response["name"], response["vk"]);
if (!responseRequested) {
responseRequested = true;
if (!aggroBot.messagesReceived) aggroBot.prepareResponse();
}
}
});
}
// Иначе просто готовим приветствие
else if (aggroBot.active) aggroBot.prepareResponse();
});
chat.addEventListener(VPP.Chat.Event.MESSAGE_RECEIVED, "aggrobot", (type, content) => {
if (!aggroBot.active) return;
let request;
switch (type) {
case VPP.Chat.MessageType.TEXT:
request = new AggroBot.Request(AggroBot.Request.Type.TEXT);
request.text = content;
break;
case VPP.Chat.MessageType.IMAGE:
request = new AggroBot.Request(AggroBot.Request.Type.PHOTO);
request.photoURL = content;
break;
case VPP.Chat.MessageType.STICKER:
request = new AggroBot.Request(AggroBot.Request.Type.STICKER);
const groupId = +content.match(/\/stickers\/(\d+)\//i)[1];
switch (groupId) {
case 4: request.stickerGroupName = "pony"; break;
case 6: request.stickerGroupName = "cat"; break;
case 8: request.stickerGroupName = "nichosi"; break;
case 9: request.stickerGroupName = "seagull"; break;
}
break;
}
aggroBot.receiveMessage(request);
aggroBot.prepareResponse(request, chat.messageSent);
});
chat.addEventListener(VPP.Chat.Event.MESSAGE_DELIVERED, "aggrobot", () => chat.messageSent = true);
chat.addEventListener(VPP.Chat.Event.USER_STARTED_TYPING, "aggrobot", () => {
if (!aggroBot.active) return;
// Если собеседник начал печатать во время ответа бота, бот на короткое время "отвлекается" от набора текста
aggroBot.waitForOpponent();
});
chat.addEventListener(VPP.Chat.Event.DISCONNECTED, "aggrobot", () => {
chat.setFinishedTyping();
if (aggroBot.active) aggroBot.suspend();
});
});
};
const AggroBot = class {
/**
* Генерирует новое состояние бота
*/
reset() {
this.suspend();
if (this._database) this._database.reset();
/**
* Работает ли бот
* @type {boolean}
*/
this.active = true;
/**
* ID таймеров различных откладываемых действий
* @type {number}
* @private
*/
this._readTimeout = null;
this._typeTimeout = null;
this._interruptedTimeout = null;
this._activityCheckTimeout = null;
/**
* Счётчик тиков неактивности собеседника
* @type {number}
* @private
*/
this._inactivityCounter = 0;
/**
* Timestamp, когда бот начал печать ответа.
* Вспомогательное свойство.
* @type {number}
* @private
*/
this._typingStartedTime = null;
/**
* Очередь ответов бота
* @type {Array<AggroBot.QueuedResponse>}
* @private
*/
this._responseQueue = [];
/**
* Было ли отправлено приветственное сообщение
* @type {boolean}
* @private
*/
this._greeted = false;
/**
* Установлено в true, если бот ещё не писал сообщение с момента получения последнего сообщения от собеседника
* @type {boolean}
* @private
*/
this._directResponse = false;
/**
* Намеревается ли бот покинуть чат после опустошения очереди
* @type {boolean}
* @private
*/
this._intendsToLeave = false;
/**
* Количество сообщений, отправленных ботом.
* Используется для оценки актуальности тех или иных сообщений от собеседника.
* @type {number}
*/
this.messagesReceived = 0;
/**
* Информация о пользователе
* @type {AggroBot.UserProfile}
* @private
*/
this._userProfile = new AggroBot.UserProfile();
/**
* Стиль письма бота
* @type {AggroBot.Style}
* @private
*/
this._style = new AggroBot.Style();
/**
* Переменные, подставляемые во фразы
* @type {object}
* @private
*/
this._variables = {};
/**
* Детектор флуда/спама
* @type {AggroBot.SpamDetector}
* @private
*/
this._spamDetector = new AggroBot.SpamDetector();
/**
* Последний запрос, который посчитался флудом/спамом
* @type {AggroBot.Request}
* @private
*/
this._spamRequest = null;
/**
* Флаг установлен, если бот игнорирует запросы о подготовке ответа
* @type {boolean}
* @private
*/
this._ignoringPrepareRequests = false;
/**
* Флаг установлен, если бот уже посылал своё фото
* @type {boolean}
* @private
*/
this._photoSent = false;
/**
* Сколько раз бот отвечал условным ответом
* @type {number}
* @private
*/
this._respondedByCondition = 0;
}
/**
* Устанавливает базу сообщений бота
* @param {AggroBot.Database} database
*/
setDatabase(database) {
this._database = database;
}
/**
* Приостанавливает работу бота
*/
suspend() {
this.active = false;
clearTimeout(this._readTimeout);
this._readTimeout = null;
clearTimeout(this._typeTimeout);
this._typeTimeout = null;
clearTimeout(this._interruptedTimeout);
this._interruptedTimeout = null;
clearTimeout(this._activityCheckTimeout);
this._activityCheckTimeout = null;
}
/**
* Возобновляет работу бота
*/
resume() {
this.active = true;
this._clearQueue();
}
/**
* Уведомляет бота о том, что ему отослали сообщение
* @param {AggroBot.Request} request Сообщение от собеседника
*/
receiveMessage(request) {
// Пытаемся определить пол
if (request.type === AggroBot.Request.Type.TEXT) this._determineGenderAndName(request.text);
// Полученное сообщение считается активностью, поэтому сбрасываем счётчик
this._inactivityCounter = 0;
this._intendsToLeave = false;
this.messagesReceived++;
this._directResponse = true;
// Смотрим, есть ли в очереди ответы, которые должны быть удалены из очереди во время получения сообщения
let queueUpdated = false;
if (this._responseQueue[0] && this._responseQueue[0].discardOnMessage) {
this._removeNextQueuedResponse();
queueUpdated = true;
}
this._responseQueue = this._responseQueue.filter(queued => !queued.discardOnMessage);
if (queueUpdated) this._setQueueUpdated();
// Если бот получил сообщение, пока писал своё, он отвлекается на его прочтение
const nextQueued = this._responseQueue[0];
if (nextQueued) {
if (nextQueued.interruptOnMessage) this._interrupt(AggroBot.getTimeToRead(request));
}
// Проверяем на спам/флуд
const alreadyResponding = this._responseQueue.some(queued => queued.isSpamResponse);
const {result, variables} = this._spamDetector.analyzeNext(request, alreadyResponding);
if (result) {
this._spamRequest = request;
if (!alreadyResponding) {
Object.assign(this._variables, variables);
this._processAndAddToQueue(this._getMessage(result), {
readDelay: AggroBot.getTimeToRead(request),
isSpamResponse: true
});
}
}
else {
this._spamRequest = null;
this._ignoringPrepareRequests = this._spamDetector.state === AggroBot.SpamDetector.State.IGNORING;
if (!this._ignoringPrepareRequests && this._responseQueue[0] && this._responseQueue[0].isSpamResponse) {
while(this._responseQueue[0] && this._responseQueue[0].isSpamResponse) this._removeNextQueuedResponse();
this._setQueueUpdated();
}
}
if (!this._responseQueue[0]) this._resetInactiveTimeout();
}
/**
* Готовит и откладывает ответ собеседнику
* @param {AggroBot.Request} request Сообщение от собеседника
* @param {boolean} withoutGreeting Нужно ли пропустить приветствие
*/
prepareResponse(request = null, withoutGreeting = false) {
if (this._ignoringPrepareRequests || request != null && this._spamRequest == request) return;
// Отправляем приветствие
if (!this._greeted) {
this._greeted = true;
if (!withoutGreeting) {
this._processAndAddToQueue(this._getMessage("greetings"), {
discardOnMessage: true
});
return;
}
}
// Проверяем, занят ли бот
const ready = !this._responseQueue[0] || this._responseQueue.every(queued => !queued.blockQueue);
const defaultOptions = {readDelay: AggroBot.getTimeToRead(request)};
let added = false;
let allowSecondary = true;
// Пытаемся найти ответ по регулярному выражению или на особые типы контента
if (request != null) switch (request.type) {
case AggroBot.Request.Type.TEXT:
// Ответ на запрос фото
if (!this._photoSent &&
/(фот|селфи)[а-яё]* (себя |сво[еёию] )?(с?кин(ь|еш)|кида(й|еш)|го(?![а-я])|давай|сдела(й|еш)|(при|вы|ото)шл(и|еш)|отправ(ь|иш))|(кин|кида|([^а-яё]|^)го|дава|сдела|(при|вы|ото)шл|отправ)(и|й|еш|иш)?ь? (себя |сво[еёию] )?(фот|селфи)|сфот(к?а|огр[ао]фиру)й(ся| себя)/i.test(request.text) &&
!this._responseQueue.some(queued => queued.pattern == "photo_sending")) {
this._processAndAddToQueue(this._getMessage("photo_sending"), Object.assign({
pattern: "photo_sending"
}, defaultOptions));
const queued = new AggroBot.QueuedResponse(AggroBot.selfieURL, AggroBot.QueuedResponse.ContentType.IMAGE);
queued.readDelay = AggroBot.TIME_TO_MAKE_PHOTO;
queued.pattern = "photo_sending";
queued.interruptOnTyping = false;
queued.interruptOnMessage = false;
this._enqueueResponse(queued);
this._photoSent = true;
added = true;
allowSecondary = false;
break;
}
// Ответ на запрос ВКонтакте; установка флага, если собеседник пишет, что у него нет ВКонтакте; обработка ссылки на страницу
if (AggroBot.vkEnabled) {
let matches;
if (/(кинь|скажи|напиши|пришли|дай|давай|([^а-яё]|^)го|отправь|черкани|сыл(ку|ь)( на)?|линк(ани)?|записан|может|страницу)([ \-]?ка)?( тогда)?( сво[йю])?( ты| в| мне)?( тогда)?( сво[йю])? (вк|vk|id|ай ?[дп]и|одноклас+ники|фб|fb|фейсбук|facebook|телег|в(ай|и)бер|в[оа](тс|ц)ап)|(вк[оа][а-я]+|vk|id|ай ?[дп]и|одноклас+ники|фб|fb|фейсбук|facebook|телег(у|рам+)|в(ай|и)бер|в[оа](тс|ц)ап+)( ты| мне)?( свой)? (с?кинь|скажи|напиши|пришли|дай|давай|го|отправь|черкани|с+ыл(ку|ь)|линк)/i.test(request.text) ||
/(кинь|скажи|напиши|пришли|дай|давай|([^а-яё]|^)го|отправь|черкани|лучше)([\- ]?ка)? ([ст]во[еёйю]|ты|сам|с+ыл(ку|ь))|([ст]во[еёйю]|ты|сам|сыл(ку|ь)) (с?кинь|скажи|напиши|пришли|дай|давай|го|отправь|черкани|лучше|первы[йм])/i.test(request.text) && this._userProfile.vk.requestedAt !== undefined && this.messagesReceived - this._userProfile.vk.requestedAt <= 6) {
this._processAndAddToQueue(this._getMessage(!this._userProfile.vk.sent ? "vk_response" : "vk_already_sent"), defaultOptions);
added = true;
} else if (/(у )?меня (нет )?(в |на )?(вк|стра)|^нету? (вк|страницы)|^(а )?вк нет/i.test(request.text) || /(у меня (его )?|меня там )нет|не зарег|^нету$|не сижу/i.test(request.text) && this.messagesReceived - this._userProfile.vk.requestedAt <= 6) {
console.log("User does not have VK profile");
this._userProfile.vk.userDoesNotHave = true;
} else if (this.messagesReceived - this._userProfile.vk.requestedAt <= 10 && (matches = request.text.match(/(?:(?:https?:\/\/)?(?:m\.)?vk\.com)?(\/?id\d+|\/[a-z][\w.]{4,})/i))) {
const vk = matches[1].replace("/", "");
this._userProfile.vk.receive(vk).then(() => {
this._processAndAddToQueue(this._getMessage("vk_acknowledged"), defaultOptions);
added = true;
return this._userProfile.vk.process();
}).then(({name, gender, avatarContents, avatarDescription}) => {
if (gender !== undefined) {
this._userProfile.gender = gender;
this.onReport("Пол ВКонтакте: " + (gender === AggroBot.UserProfile.Gender.MALE ? "мужской" : "женский"));
}
if (!this._userProfile.name || !(this._userProfile.nameConfirmed || this._userProfile.name == name)) {
this._userProfile.name = name;
this.onReport(`Имя ВКонтакте: ${name}`);
}
switch (avatarContents) {
case AggroBot.VK.AvatarContents.PERSON:
this._processAndAddToQueue(this._getMessage("vk_avatar_person"), defaultOptions);
console.log(`Assuming a person`);
break;
case AggroBot.VK.AvatarContents.OBJECT:
let gender = 0;
if (/[ая]$/.test(avatarDescription)) gender = 1;
else if (/[ое]$/.test(avatarDescription)) gender = 2;
this._variables["vkavatarobjectgender"] = (...args) => args[gender];
const accusative = avatarDescription.replace(/[ая]я?(?![а-яё])/g, match => {
return match.replace(/а/g, "у").replace(/я/g, "ю");
});
this._variables["vkavatarobject"] = wordsCase => wordsCase == "accusative" ? accusative : avatarDescription;
this._processAndAddToQueue(this._getMessage("vk_avatar_object"), defaultOptions);
console.log(`Assuming an object`);
break;
case AggroBot.VK.AvatarContents.NONE:
this._processAndAddToQueue(this._getMessage("vk_no_avatar"), defaultOptions);
console.log("Profile does not have an avatar");
}
}).catch(error => {
let databaseKey;
switch (error) {
case AggroBot.VK.Error.ANOTHER_PROFILE: databaseKey = "vk_another_profile"; break;
case AggroBot.VK.Error.BOT_PROFILE: databaseKey = "vk_myself"; break;
case AggroBot.VK.Error.ID_0: databaseKey = "vk_id0"; break;
case AggroBot.VK.Error.PROFILE_DOES_NOT_EXIST: databaseKey = "vk_does_not_exist"; break;
case AggroBot.VK.Error.URL_INVALID: databaseKey = "vk_invalid"; break;
case AggroBot.VK.Error.BANNED: databaseKey = "vk_banned"; break;
default: console.log(error);
}
if (databaseKey) {
added = true;
this._processAndAddToQueue(this._getMessage(databaseKey), defaultOptions);
}
});
}
}
// Ответы на реакцию на запрос подтверждения имени
if (this._userProfile.nameConfirmationRequestedAt !== undefined && this.messagesReceived - this._userProfile.nameConfirmationRequestedAt <= 8) {
if (/(как|откуда)( ты)?( меня| это)? (узнал|знаеш|угадал)|^как\??$|меня помниш/i.test(request.text)) {
this._processAndAddToQueue(this._getMessage("name_source"), defaultOptions);
this._userProfile.nameConfirmed = true;
added = true;
console.log("Name confirmed");
break;
} else if (/^(а+|э+м+|ну)?[^а-я]*да+([^а-яё]|$)|[^н]. угадал|^(угадал|почти|ага)|(^конечно|именно|верно|почти|допустим|прикинь|предположим|возможно|^это? я|^а ч(то|[её])|^(ну )?и( что| ч[её])?)[^а-я]*(так |да )?([^а-я ]|$)|^(\+|ну|д[ыэя]|й?ес)$/i.test(request.text)) {
this._userProfile.nameConfirmed = true;
console.log("Name confirmed");
break;
} else if (/^не+([та\-]| верно| угадал|$)|^(мен)?я не |^мимо[^а-я]*$|^-$/i.test(request.text) && !this._userProfile.nameConfirmed) {
this._processAndAddToQueue(this._getMessage("name_incorrect"), defaultOptions);
this._userProfile.name = undefined;
this._userProfile.nameConfirmationRequestedAt = undefined;
this._userProfile.nameConfirmed = false;
this._userProfile.nameAskedAt = this.messagesReceived;
added = true;
console.log("Name rejected");
break;
}
}
// Ответы по регулярному выражению
const {message, pattern} = this._getAnswer(request.text);
if (message != null) this._processAndAddToQueue(message, Object.assign({
pattern: pattern
}, defaultOptions)) && (added = true);
break;
case AggroBot.Request.Type.PHOTO:
if (!this._responseQueue.some(queued => queued.pattern == "photo")) this._processAndAddToQueue(this._getMessage("photo"), Object.assign({
pattern: "photo"
}, defaultOptions)) && (added = true);
break;
case AggroBot.Request.Type.STICKER:
const databaseKey = `sticker_${request.stickerGroupName}`;
if (this._database.has(databaseKey) && !this._responseQueue.some(queued => queued.pattern == "sticker")) {
const message = this._getMessage(databaseKey);
if (message) this._processAndAddToQueue(message, Object.assign({
pattern: "sticker"
}, defaultOptions)) && (added = true);
}
break;
}
// Добавляем в очередь уточнение имени собеседника, а также рифму к имени
if (!added && ready && this._userProfile.name && !this._userProfile.nameConfirmed &&
Math.random() < AggroBot.getNameConfirmationProbability(this._userProfile.nameConfirmationRequests)) {
console.log("Reporting name...");
this._userProfile.nameConfirmationRequests++;
this._processAndAddToQueue(this._getMessage("name_confirmation"), defaultOptions);
this._userProfile.nameConfirmationRequestedAt = this._userProfile.nameAskedAt = this.messagesReceived;
added = true;
}
if (!added && ready && this._userProfile.nameConfirmed && !this._userProfile.nameRhymed &&
Math.random() < AggroBot.PROBABILITY_NAME_RHYME) {
const rhyme = !AggroBot.nameVariations.split(",").includes(this._userProfile.name) ?
this._getNameRhyme() : this._getMessage("name_same");
if (rhyme) {
console.log("Got a rhyme to the name...");
this._processAndAddToQueue(rhyme, defaultOptions);
added = true;
allowSecondary = false;
}
else console.log("No rhymes to this name");
this._userProfile.nameRhymed = true;
}
// Добавляем в очереди запрос ВКонтакте
if (AggroBot.vkEnabled && AggroBot.vkToken && !added && ready && !this._userProfile.vk.url && !this._userProfile.vk.userDoesNotHave &&
Math.random() < AggroBot.getVKRequestProbability(this._userProfile.vk.requests)) {
this._userProfile.vk.requests++;
this._processAndAddToQueue(this._getMessage("vk_request"), defaultOptions);
this._userProfile.vk.requestedAt = this.messagesReceived;
added = true;
}
// Добавялем в очередь условный ответ
if (!added && ready && Math.random() < AggroBot.getConditionalResponseProbability(this._respondedByCondition)) {
console.log("picking conditional response...");
const possibleSets = Object.keys(AggroBot.satisfiesCondition).filter(key =>
this._database.conditional.has(key) && AggroBot.satisfiesCondition[key]()).map(key =>
this._database.conditional.get(key));
let response = null;
while (!response && possibleSets.length) {
const index = Math.floor(Math.random() * possibleSets.length);
response = possibleSets[index].getRandom();
if (!response) possibleSets.splice(index, 1);
}
if (response) {
const message = this._processMessage(response.string);
if (message) {
this._processAndAddToQueue(message, defaultOptions);
this._respondedByCondition++;
added = true;
}
}
}
// Добавляем в очередь новый первичный ответ, если бот не занят
if (!added && ready) {
this._processAndAddToQueue(this._getMessage("primary"), defaultOptions);
added = true;
}
// Добавляем вторичные ответы
if (added && allowSecondary) while (Math.random() < AggroBot.PROBABILITY_SECONDARY) {
this._processAndAddToQueue(this._getMessage("secondary"), {
readDelay: AggroBot.TIME_ADDITIONAL_READ_DELAY,
interruptOnTyping: false,
discardOnMessage: true
});
}
}
/**
* Задерживает ответ
*/
waitForOpponent() {
if (this._responseQueue[0]) {
if (this._responseQueue[0].interruptOnTyping) this._interrupt(AggroBot.TIME_WAIT);
}
else this._resetInactiveTimeout();
}
/**
* Вызывается, когда нужно начать посылать уведомление о наборе сообщения
*/
onTypingStart() {}
/**
* Вызывается, когда нужно закончить посылать уведомление о наборе сообщения
*/
onTypingFinish() {}
/**
* Вызывается, когда нужно отправить ответ от бота
*/
onMessageReady() {}
/**
* Вызывается, когда нужно отправить изображение от бота
*/
onImageReady() {}
/**
* Вызывается, когда бот инициирует завершение чата
*/
onConversationFinish() {}
/**
* Вызывается, когда бот посылает отчётную информацию
*/
onReport() {}
/**
* Форсирует проверку очереди сообщений
* @private
*/
_setQueueUpdated() {
// Ничего не делаем, если бот уже читает запрос или пишет ответ
if (this._readTimeout || this._typeTimeout || this._interruptedTimeout) return;
// Если очередь не пустая, запускаем таймер чтения последнего сообщения.
// Иначе запускаем таймер неактивности собеседника.
const queued = this._responseQueue[0];
if (queued) this._readTimeout = setTimeout(this._setReadingFinished.bind(this), queued.readDelay);
else if (this._intendsToLeave) setTimeout(this.onConversationFinish.bind(this), 100);
else this._resetInactiveTimeout();
}
/**
* Вспомогательный метод, вызываемый, когда чтение (задержка перед набором) текущего сообщения должно быть закончено
* @private
*/
_setReadingFinished() {
this._readTimeout = null;
this._typingStartedTime = Date.now();
const typeDelay = this._responseQueue[0].typeDelay;
if (typeDelay) this.onTypingStart();
this._typeTimeout = setTimeout(this._setTypingFinished.bind(this), typeDelay);
}
/**
* Вспомогательный метод, вызываемый, когда набор текущего сообщения должен быть закончен
* @private
*/
_setTypingFinished() {
this._typeTimeout = null;
this.onTypingFinish();
const queued = this._responseQueue.shift();
switch (queued.contentType) {
case AggroBot.QueuedResponse.ContentType.TEXT:
this.onMessageReady(queued.message);
this._spamDetector.storeOutput(queued.message);
break;
case AggroBot.QueuedResponse.ContentType.IMAGE:
this.onImageReady(queued.imageURL);
break;
}
this._directResponse = false;
this._setQueueUpdated();
}
/**
* Запускает таймер, который, если во время его активности собеседник не был активен, увеличивает счётчик тиков
* неактивности по его истечении.
* При каждом прибавлении бот выполняет действия, направленные на привлечение внимания собеседника.
* Если собеседник неактивен несколько тиков подряд, соединение разрывается.
* @private
*/
_resetInactiveTimeout() {
clearTimeout(this._activityCheckTimeout);
if (!this._intendsToLeave) this._activityCheckTimeout = setTimeout(() => {
this._activityCheckTimeout = null;
if (this._ignoringPrepareRequests) return this._resetInactiveTimeout();
switch (++this._inactivityCounter) {
case 1:
this.prepareResponse();
break;
case 2:
case 3:
this._processAndAddToQueue(this._getMessage("inactivity_response"), {
discardOnMessage: true
});
break;
case 4:
this._intendsToLeave = true;
this._processAndAddToQueue(this._getMessage("before_leaving"), {
discardOnMessage: true
});
break;
}
}, AggroBot.TIME_INCREMENT_INACTIVE_COUNTER);
}
/**
* Добавляет ответ в очередь
* @param {AggroBot.QueuedResponse} queued
* @private
*/
_enqueueResponse(queued) {
this._responseQueue.push(queued);
this._setQueueUpdated();
}
/**
* Отменяет подготовку к отправке следующего ответа в очереди
* @private
*/
_removeNextQueuedResponse() {
this._responseQueue.shift();
clearTimeout(this._readTimeout);
clearTimeout(this._typeTimeout);
clearTimeout(this._interruptedTimeout);
this._readTimeout = null;
this._typeTimeout = null;
this._interruptedTimeout = null;
this._resetInactiveTimeout();
}
/**
* Очищает очередь
* @private
*/
_clearQueue() {
clearTimeout(this._readTimeout);
this._readTimeout = null;
clearTimeout(this._typeTimeout);
this._typeTimeout = null;
clearTimeout(this._interruptedTimeout);
this._interruptedTimeout = null;
this._responseQueue.length = 0;
this._setQueueUpdated();
}
/**
* Задерживает/прерывает/отвлекает бота от чтения/печати на время
* @param {number} time Время, мс
* @private
*/
_interrupt(time) {
if (!this._readTimeout && !this._typeTimeout) return;
// Если в данный момент активно чтение, то чтение будет закончено по истечение переданного времени
if (this._readTimeout) {
clearTimeout(this._readTimeout);
this._readTimeout = setTimeout(this._setReadingFinished.bind(this), time);
}
// Если же активна печать, то статус печати перестаёт отправляться на переданное время
else if (this._typeTimeout) {
clearTimeout(this._typeTimeout);
this._typeTimeout = null;
this.onTypingFinish();
const delayLeft = this._responseQueue[0].typeDelay - (Date.now() - this._typingStartedTime);
this._interruptedTimeout = setTimeout(() => {
this._interruptedTimeout = null;
this._responseQueue[0].typeDelay = delayLeft;
this.onTypingStart();
this._typeTimeout = setTimeout(this._setTypingFinished.bind(this), delayLeft);
}, time);
}
}
/**
* Возвращает случайное необработанное сообщение из базы сообщений по ключу
* @param {string} databaseKey
* @returns {string}
* @private
*/
_getRawMessage(databaseKey) {
const response = this._database.getRandom(databaseKey);
return response && response.string;
}
/**
* Обрабатывает функции и флаги внутри строки
* @param {string} message
* @param {Array<string>} matches Массив совпадений для %m
* @returns {string | null}
* @private
*/
_processMessage(message, matches = []) {
if (message == null) return null;
let invalid = false;
message = message.replace(/%(\w+)(?:\(([^,)]*(?:,[^,)]*)*)\))?/g, (_, name, args) => {
args = args ? args.split(",") : [];
switch (name) {
case "g":
case "gender":
if (!args.length) {
const genderName = this._userProfile.gender === AggroBot.UserProfile.Gender.MALE ?
["мужик", "пацан", "парень"] : ["баба", "телка", "девушка"];
return genderName[Math.floor(Math.random() * genderName.length)];
}
return (this._userProfile.gender === AggroBot.UserProfile.Gender.MALE ? args[0] : args[1]) || "";
case "userprofilename":
return this._userProfile.name || "";
case "d":
case "direct":
if (!this._directResponse) invalid = true;
break;
case "nd":
case "nondirect":
if (this._directResponse) invalid = true;
break;
case "firstname":
return AggroBot.firstName.toLowerCase();
case "lastname":
return AggroBot.lastName.toLowerCase();
case "shortname":
return AggroBot.shortName.toLowerCase();
case "vk":
return "https://vk.com/" + (AggroBot.vkUseIdURL ? AggroBot.vkIdURL : AggroBot.vkCustomURL);
case "m":
case "match":
return (matches[+(args[0] || 0)] || "").toLowerCase();
case "ifm":
case "ifmatch":
invalid = !matches[+args[0]];
break;
case "ifnm":
case "ifnomatch":
invalid = !!matches[+args[0]];
break;
case "timeschedule": {
const to12HourFormat = hours => hours % 12 || 12;
const toFullHourFormat = hours => {
const hours12 = to12HourFormat(hours);
return hours12 == 1 ? "час" : `${hours12} час${hours12 < 5 ? "а" : "ов"}`;
};
const now = new Date();
const minutes = now.getMinutes();
const hours = now.getHours();
if (minutes <= 15) return toFullHourFormat(hours);
if (minutes < 45) return `${minutes <= 25 ? "почти" : ""} пол ${to12HourFormat(hours + 1)}`;
return "почти " + toFullHourFormat(hours + 1);
}
case "timehour": {
const now = new Date();
return (now.getHours() + (now.getMinutes() > 25)) % 12 || 12;
}
case "timeofday": {
const now = new Date();
const hours = now.getHours() + now.getMinutes() / 100;
if (hours < 5.30 || hours > 23.30) return "посреди ночи";
if (hours < 12) return "с утра";
if (hours < 18) return "посреди дня";
return "весь вечер";
}
case "timedayofweek":
return ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"][new Date().getDay()];
case "asksname":
this._userProfile.nameAskedAt = this.messagesReceived;
break;
default:
if (typeof this._variables[name] === "string") return this._variables[name];
else if (typeof this._variables[name] === "function") return this._variables[name].apply(this, args);
}