-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1522 lines (1322 loc) · 56.2 KB
/
app.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
// MODULES
var Botkit = require('botkit');
var request = require('request');
var Pokedex = require('pokedex-promise-v2');
// POKEDEX CONSTRUCTOR
var P = new Pokedex();
// CONFIG
var controller = Botkit.facebookbot({
access_token: process.env.page_access_token,
verify_token: process.env.verify_token,
});
// BOT SPAWN
var bot = controller.spawn({
});
// SERVER
controller.setupWebserver(process.env.PORT, function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
// MONITORING MIDDLEWARE
controller.middleware.receive.use(function(bot, message, next) {
console.log(userCurrentGame, 'userCurrentGame')
console.log(userPokedex, 'userPokedex')
next();
})
var pokemonList = null;
// POKEMON LIST
request('https://pokeapi.co/api/v2/pokemon', function (err, result) {
if (!err) {
var data = JSON.parse(result.body);
var url = 'https://pokeapi.co/api/v2/pokemon/?limit=' + data.count;
request(url, function (err, result) {
if (!err) {
data = JSON.parse(result.body);
pokemonList = data.results;
} else {
console.log('there was an error: ' + err); // verify
}
});
} else {
console.log('there was an error: ' + err); // verify
}
});
// MENUS
var mainMenu = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': 'What can I help you with?',
'buttons': [
{
'type':'postback',
'title':'Search for a Pokémon',
'payload':'search'
},
{
'type':'postback',
'title':'Search for a type',
'payload':'search-type'
},
{
'type':'postback',
'title':'More options',
'payload':'moreoptions-button'
}
]
}
]
}
};
var mainMenuNext = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': 'What can I help you with?',
'buttons': [
{
'type':'postback',
'title':'Set my Pokédex',
'payload':'pokedexmenu'
},
{
'type':'postback',
'title':'Help section',
'payload':'help'
},
{
'type':'postback',
'title':'That\'s all for now',
'payload':'thatsall-button'
}
]
}
]
}
};
var pokedexMenu = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': 'What would you like to do?',
'buttons': [
{
'type':'postback',
'title':'Use National Pokédex',
'payload':'default'
},
{
'type':'postback',
'title':'Use game Pokédex',
'payload':'set-pokedex'
},
{
'type':'postback',
'title':'Keep current Pokédex',
'payload':'keep-pokedex'
}
]
}
]
}
};
var newSearchMenu = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': 'Would you like to do another search?',
'buttons': [
{
'type':'postback',
'title':'Search for a Pokémon',
'payload':'search'
},
{
'type':'postback',
'title':'See main menu',
'payload':'mainmenu-button'
},
{
'type':'postback',
'title':'That\'s all for now',
'payload':'thatsall-button'
}
]
}
]
}
};
// MENUS HANDLER
controller.on('facebook_postback', function(bot, message) {
var currentGameName;
if (userCurrentGame[message.user]) {
currentGameName = userCurrentGame[message.user].name.split('-').join(' ');
}
var messageSplit = message.payload.split('*');
var onButtonPress = messageSplit[0];
if (messageSplit.length === 4) {
var pokemonName = messageSplit[1];
var pokemonChainUrl = messageSplit[2];
var displayName = messageSplit[3];
} else if (messageSplit.length === 3) {
var chosenPokedexUrl = messageSplit[1];
var chosenPokedexName = messageSplit[2];
}
if (onButtonPress === 'evolution-button') {
bot.reply(message, 'No problem, hold on a second!');
getEvolutionChain(bot, message, pokemonName, pokemonChainUrl, displayName);
}
else if (onButtonPress === 'search') {
searchPokemon(bot, message);
}
else if (onButtonPress === 'thatsall-button') {
bot.reply(message, 'Ok, tell me if you need my help again!');
return;
}
else if (onButtonPress === 'mainmenu-button') {
bot.reply(message, {attachment: mainMenu});
}
else if (onButtonPress === 'moreoptions-button') {
bot.reply(message, {attachment: mainMenuNext});
}
else if (onButtonPress === 'search-type') {
getType(bot, message);
}
else if (onButtonPress === 'pokedexmenu') {
bot.startConversation(message, function(err, convo) {
if (!err) {
stateCurrentPokedex(bot, message, convo);
convo.say({attachment: pokedexMenu});
} else {
console.log('there was an error: ' + err); // verify
return;
}
});
}
else if (onButtonPress === 'set-pokedex') {
findGame(bot, message);
}
else if (onButtonPress === 'keep-pokedex') {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('No problem!');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
else if (onButtonPress === 'default') {
if (userPokedex[message.user]) {
delete userPokedex[message.user];
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Alright, you are now using the National Pokédex.');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('You are already using the National Pokédex!');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
}
else if (onButtonPress === 'help') {
sendHelp(bot, message);
}
else if (onButtonPress === 'pokedexchoice') {
userPokedex[message.user] = [ { url: chosenPokedexUrl, name: chosenPokedexName } ];
console.log(userPokedex[message.user])
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Pokédex now set to ' + capitalizeFirst(splitJoin(chosenPokedexName)) + '.');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
});
// SAY CURRENT POKEDEX
function stateCurrentPokedex(bot, message, convo) {
var currentGameName = null;
if (userCurrentGame[message.user]) {
currentGameName = userCurrentGame[message.user].name.split('-').join(' ');
}
if (userPokedex[message.user]) {
var name = userPokedex[message.user][0].name;
convo.say('You are currently using the Pokédex for Pokémon ' + displayGameName(currentGameName) + ': ' + capitalizeFirst(splitJoin(name)) + '.');
} else {
convo.say('You are currently using the National Pokédex.');
}
}
// HELLO FUNCTION
var userFirstRun = {};
controller.hears(['^hello$', '^hi$', '^yo$', '^hey$', 'what\'s up'], 'message_received', function(bot, message) { // NOTE: Change dialog, add user nickname question linked with database
if (!userFirstRun[message.user]) {
userFirstRun[message.user] = 'done';
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Hey there, Pokémon trainer. :) Nice to meet you! I am your assistant Pokédex. Feel free to browse through my menus, or say "help" if you want to know more!');
stateCurrentPokedex(bot, message, convo);
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Hello, nice to see you again! :)');
stateCurrentPokedex(bot, message, convo);
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
});
// HELP SECTION
controller.hears('^help$', 'message_received', sendHelp);
function sendHelp(bot, message) {
var convoArray = ['I heard that you want to know more about me? :) \nI am a bot made to assist Pokémon trainers like you, on a quest to catch \'em all! ☺', 'I can find any Pokémon through any Pokédex of a given game, and tell you about its evolution trigger and conditions. When prompted for a Pokémon, try to say "Squirtle" or "Pikachu" ❤️, for example. Or any number between 1 and 721!', 'I can also tell you what type is good against another. Try searching for types like "fire", "psychic" or "electric"! ⚡ \n\nKeep in mind that I understand only the English version of the Pokémon names and types.', 'All my functions are available through my main menu. Though you can also call them by saying things like "pokemon" or "type". \n\nGreeting me will bring up the main menu as well. ☎ If you need a reminder, don\'t hesitate to say "help"! ☺', {attachment: mainMenu}]
bot.reply(message, convoArray[0]);
setTimeout(function() {
bot.reply(message, convoArray[1]);
}, 4000)
setTimeout(function() {
bot.reply(message, convoArray[2]);
}, 12000)
setTimeout(function() {
bot.reply(message, convoArray[3]);
}, 19000)
setTimeout(function() {
bot.reply(message, convoArray[4]);
}, 25000)
}
// WHICH GAME: Finding which game the user is playing for pokedex entry numbers
var userCurrentGame = {};
var userPokedex = {};
controller.hears(['game', '^pokedex$', '^pokédex$'], 'message_received', findGame);
function findGame(bot, message) {
bot.startConversation(message, function(err, convo) {
if (!err) {
if (!userCurrentGame[message.user]) {
convo.ask('Which game are you currently playing?', function(response, convo) {
var userAnswer = response.text.toLowerCase();
// if 'pokemon' is in the answer, remove it
if (userAnswer.indexOf('pokemon') !== -1) {
userAnswer = userAnswer.split('pokemon ')[1];
} else if (userAnswer.indexOf('pokémon') !== -1) {
userAnswer = userAnswer.split('pokémon ')[1];
}
// REGEXP (to avoid having another game/multiple games as a result ('black' instead of 'black 2', etc.))
if (userAnswer === 'y') {
userAnswer = /\sy$/;
} else if (userAnswer === 'x') {
userAnswer = /^x\s/;
} else if (userAnswer === 'ruby') {
userAnswer = /^ruby\s/;
} else if (userAnswer === 'red') {
userAnswer = /^red\s/;
} else if (userAnswer === 'gold') {
userAnswer = /^gold\s/;
} else if (userAnswer === 'silver') {
userAnswer = /\ssilver$/;
} else if (userAnswer === 'white') {
userAnswer = /\swhite$/;
} else if (userAnswer === 'sapphire') {
userAnswer = /^ruby sapphire$/;
} else if (userAnswer === 'black') {
userAnswer = /^black white$/;
}
// Fetching game info
request('https://pokeapi.co/api/v2/version-group/', function (err, result) {
if (!err) {
var resultObject = JSON.parse(result.body);
var versionGroup = resultObject.results;
var gameFound = false;
var counter = versionGroup.length;
// loop over each available game
versionGroup.forEach(function(version) {
var currentGameName = version.name.split('-').join(' ');
counter--;
console.log(currentGameName);
// compare user answer to available games. if found, save infos for that game
if (currentGameName.search(userAnswer) !== -1 && currentGameName !== 'colosseum' && currentGameName !== 'xd') { // ignoring Colosseum and XD
console.log('found! here is the url: ' + version.url);
gameFound = true;
userCurrentGame[message.user] = version;
}
});
// if game infos saved
if (userCurrentGame[message.user]) {
getPokedex(bot, message); // call next function
} else if (gameFound === false && counter === 0) {
bot.reply(message, 'Sorry, I couldn\'t find the game that you requested.');
bot.reply(message, {attachment: mainMenu});
}
} else {
bot.reply(message, 'server error'); // verify
return;
}
});
convo.stop();
});
} else {
delete userCurrentGame[message.user];
convo.stop();
findGame(bot, message);
}
} else {
bot.reply(message, 'error'); // verify, use convo.stop(); instead of return??
return;
}
});
}
// GET POKEDEX for the current game
function getPokedex(bot, message) {
var currentGameName = userCurrentGame[message.user].name.split('-').join(' ');
// requesting game version
request(userCurrentGame[message.user].url, function(err, result) {
if (!err) {
var resultObject = JSON.parse(result.body);
var pokedexes = resultObject.pokedexes;
console.log(pokedexes, 'pokedexes')
// if only 1 pokedex available for that game
if (pokedexes.length === 1) {
userPokedex[message.user] = pokedexes; // assign pokedex to user
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('You are currently playing Pokémon ' + displayGameName(currentGameName) + '. Pokédex now set to ' + capitalizeFirst(splitJoin(pokedexes[0].name)) + '.');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
// if multiple pokedexes available for one game
else if (pokedexes.length > 1) {
var pokedexButtons = [];
pokedexes.forEach(function(pokedex) {
var pokedexName = capitalizeFirst(splitJoin(pokedex.name));
var button = {
type:'postback',
title: pokedexName,
payload:'pokedexchoice*' + pokedex.url + '*' + pokedex.name
};
pokedexButtons.push(button);
});
var pokedexChoice = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': 'Which Pokédex should I use?',
'buttons': pokedexButtons
}
]
}
};
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('You are currently playing Pokémon ' + displayGameName(currentGameName) + '.');
convo.say('I have found multiple available Pokédex for this game.');
convo.say({attachment: pokedexChoice});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
// WHICH POKEMON ?
controller.hears(['^pokemon$', '^pokémon$', '^search$'], 'message_received', searchPokemon);
function searchPokemon(bot, message) {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.ask('Which Pokémon would you like to know more about? Say its name or Pokédex entry number.', function(response, convo) {
bot.reply(message, 'Alright, please wait while I look through my files.');
var chosenPokemon = response.text;
// note to future self: make up for people entering things like '#025', 'number 25', 'pokemon no. 25', etc.
var chosenPokemonId;
var chosenPokemonName;
// checking if a name or an ID number was entered
if (chosenPokemon.match(/^[^0-9]+$/)) {
if (chosenPokemon.toLowerCase().indexOf('mega') !== -1) {
var splitChosenPokemon = chosenPokemon.toLowerCase().split(' ');
chosenPokemonName = megaPokemonName(splitChosenPokemon);
} else if (chosenPokemon.toLowerCase().indexOf('primal') !== -1) {
splitChosenPokemon = chosenPokemon.toLowerCase().split(' ');
chosenPokemonName = megaPokemonName(splitChosenPokemon);
} else {
chosenPokemonName = reverseSplitJoin(chosenPokemon.toLowerCase());
}
} else if (chosenPokemon.match(/^[0-9]+$/)) {
chosenPokemonId = Number(chosenPokemon);
} else {
bot.reply(message, 'Sorry, I didn\'t understand... Please say a number OR a name.');
// add menu ?
}
// FINDING THE POKEMON ENTRY BASED ON SET POKEDEX
if (chosenPokemonId || chosenPokemonName) {
var pokedex;
if (!userPokedex[message.user]) {
pokedex = 'https://pokeapi.co/api/v2/pokedex/1/';
} else {
pokedex = userPokedex[message.user][0].url;
}
console.log(pokedex, 'pokedex');
request(pokedex, function (err, result) {
if (!err) {
var resultObject = JSON.parse(result.body);
var pokemon_entries = resultObject.pokemon_entries;
var foundPokemon = null;
// if it's an ID...
if (chosenPokemonId) {
pokemon_entries.forEach(function(index) {
var entry_number = index.entry_number;
var pokemonName = index.pokemon_species.name;
if (entry_number === chosenPokemonId) {
foundPokemon = index.pokemon_species.url;
displayFoundPokemon(bot, message, foundPokemon, pokemonName, entry_number);
}
});
}
else if (chosenPokemonName) { // if it's a name
pokemon_entries.forEach(function(index) {
var entry_number = index.entry_number;
var pokemonName = index.pokemon_species.name;
if (pokemonName.indexOf(chosenPokemonName) !== -1) {
foundPokemon = index.pokemon_species.url;
displayFoundPokemon(bot, message, foundPokemon, pokemonName, entry_number);
}
});
if (foundPokemon === null && chosenPokemonName.indexOf('mega') !== -1 || chosenPokemonName.indexOf('primal') !== -1) {
pokemonList.forEach(function(listedPokemon) {
if (listedPokemon.name.indexOf(chosenPokemonName) !== -1) {
foundPokemon = listedPokemon.url;
var pokemonName = listedPokemon.name;
displayFoundPokemon(bot, message, foundPokemon, pokemonName, null);
}
});
}
}
if (foundPokemon === null) {
bot.startConversation(message, function(err, convo) {
if (!err) {
var exists = false;
pokemonList.forEach(function(pokemon) {
if (pokemon.name.indexOf(chosenPokemonName) !== -1) {
exists = true;
}
})
console.log(chosenPokemonName)
if (exists === true) {
convo.say('The Pokémon that you requested exists but cannot be found in your current game version / Pokédex. Try searching in the National Pokédex instead!');
convo.say({attachment: mainMenu});
} else {
console.log('woo')
convo.say('Sorry, I couldn\'t find the Pokémon that you requested.');
convo.say({attachment: mainMenu});
}
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
console.log(chosenPokemonId)
console.log(chosenPokemonName)
console.log(foundPokemon)
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
convo.stop();
});
}
});
}
// DISPLAY POKEMON WITH MENU
function displayFoundPokemon(bot, message, foundPokemon, pokemonName, entry_number) {
// search requested pokemon using the URL that was passed
request(foundPokemon, function (err, result) {
if (!err) {
var resultObject = JSON.parse(result.body);
var nationalDexNo = null;
var currentPokedexEntryNo = '';
var pokemonChainUrl = null;
var isSpecial = false;
var displayName = null;
if (foundPokemon.indexOf('/pokemon/') !== -1) { // if the pokemon was found in the pokemon list (instead of pokemon species) and has a different url
nationalDexNo = resultObject.id;
isSpecial = true;
console.log(pokemonName, 'pokemonName')
displayName = capitalizeFirst(splitJoin(megaPokemonName(pokemonName.split('-'))));
var pokemonNameSplit = pokemonName.split('-');
P.getPokemonSpeciesByName(pokemonNameSplit[0])
.then(function(response) {
pokemonChainUrl = response.evolution_chain.url;
console.log(pokemonChainUrl, 'pokemonChainUrl')
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
} else {
nationalDexNo = resultObject.pokedex_numbers[(resultObject.pokedex_numbers.length -1)].entry_number;
currentPokedexEntryNo = 'No. ' + entry_number + ', ';
pokemonChainUrl = resultObject.evolution_chain.url;
displayName = resultObject.names[0].name;
}
if (nationalDexNo) {
request('https://pokeapi.co/api/v2/pokemon/' + nationalDexNo, function(err, result) { // need to change the no. display according to chosen pokedex
if (!err) {
var isBaby = '';
var displaySpecial = '';
if (resultObject.is_baby === true) {
isBaby = ' [baby]';
}
else if (isSpecial === true) {
displaySpecial = ' [\u2606special\u2606]';
}
var pokemonInfo = JSON.parse(result.body);
var pokemonTypes = [];
pokemonInfo.types.forEach(function(type) {
pokemonTypes.push(type.type.name);
});
var attachment = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title': currentPokedexEntryNo + displayName + isBaby + displaySpecial,
'image_url': pokemonInfo.sprites.front_default,
'subtitle': 'Type(s) : ' + beautifyWordsArrays(pokemonTypes),
'buttons': [
{
'type':'postback',
'title':'See evolution chain',
'payload':'evolution-button*' + pokemonName + '*' + pokemonChainUrl + '*' + displayName
},
{
'type':'postback',
'title':'Search for a Pokémon',
'payload':'search'
},
{
'type':'postback',
'title':'That\'s all for now',
'payload':'thatsall-button'
}
]
}
]
}
};
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('I have found:');
convo.say({attachment: attachment});
}
});
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Sorry, I couldn\'t find the Pokémon that you requested.'); // verify -> server error?
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
});
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('Sorry, I couldn\'t find the Pokémon that you requested.');
convo.say({attachment: mainMenu});
} else {
bot.reply(message, 'error'); // verify
return;
}
});
}
}
});
}
// GET EVOLUTION CHAIN
function getEvolutionChain(bot, message, pokemonName, pokemonChainUrl, displayName) {
request(pokemonChainUrl, function (err, result) {
if (!err) {
var evolutionInfos = JSON.parse(result.body);
sortEvolutionLevels(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos);
} else {
console.log('The was an error: ' + err) // verify
return;
}
});
}
// SORT EVOLUTION LEVELS
function sortEvolutionLevels(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos) {
var first = evolutionInfos.chain.species.name;
var evoLevelTwoArray = [];
var evoLevelThreeArray = [];
var totalPokemonsInChain = [];
var counter = 1;
var secondLevel = [];
var thirdLevel = [];
if (evolutionInfos.chain.evolves_to.length > 0) { // if at least 2 stages evolution
evoLevelTwoArray = evolutionInfos.chain.evolves_to;
evoLevelTwoArray.forEach(function(evolution) { // loop over second-stage pokemon
console.log(evolution, 'evolution')
secondLevel.push(evolution.species.name);
totalPokemonsInChain.push(evolution.species.name);
counter++;
if (evolution.evolves_to.length > 0) { // if there is at least 1 level three stage for this level 2 pokemon
evolution.evolves_to.forEach(function(evolution2) { // loop over
evoLevelThreeArray.push(evolution2); // push level 3 pokemons
thirdLevel.push(evolution2.species.name);
totalPokemonsInChain.push(evolution2.species.name);
counter++;
});
}
});
totalPokemonsInChain.push(first);
} else {
totalPokemonsInChain.push(first);
}
console.log(totalPokemonsInChain, 'totalPokemonsInChain')
console.log(counter, 'counter')
if (totalPokemonsInChain.length === counter) {
sortMegaPrimal(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos, totalPokemonsInChain, first, secondLevel, thirdLevel, evoLevelTwoArray, evoLevelThreeArray);
}
}
// SORT MEGA / PRIMAL
function sortMegaPrimal(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos, totalPokemonsInChain, first, secondLevel, thirdLevel, evoLevelTwoArray, evoLevelThreeArray) {
var relatedSpecialPokemons = {};
var mega = [];
var primal = [];
totalPokemonsInChain.forEach(function(pokemonInChain) {
if (pokemonList) {
pokemonList.forEach(function(pokemonInList) {
if (pokemonInList.name.indexOf(pokemonInChain) !== -1 && pokemonInList.name !== pokemonInChain) { // if there are many pokemon with the same name in the full list (Charizard, Mega Charizard X, etc.)
if (!relatedSpecialPokemons[pokemonInChain]) {
relatedSpecialPokemons[pokemonInChain] = [];
}
relatedSpecialPokemons[pokemonInChain].push(pokemonInList.name);
}
});
} else {
return;
}
});
console.log(relatedSpecialPokemons, 'relatedSpecialPokemons')
for (var key in relatedSpecialPokemons) {
var list = relatedSpecialPokemons[key];
list.forEach(function(listedPokemon){
if (listedPokemon.indexOf('-mega') !== -1) { // if a mega pokemon is found in the special pokemon versions
var megaPokemonSplit = listedPokemon.split('-'); // split because 'mega' is displayed after the pokemon name in the API
var megaPokemon = megaPokemonName(megaPokemonSplit);
mega.push(megaPokemon);
}
else if (listedPokemon.indexOf('-primal') !== -1) {
var primalPokemonSplit = listedPokemon.split('-');
var pokemon = primalPokemonSplit.shift();
var primalPokemon = primalPokemonSplit + '-' + pokemon;
primal.push(primalPokemon);
}
});
}
console.log(mega, 'mega')
console.log(primal, 'primal')
locationFinder(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos, first, secondLevel, thirdLevel, evoLevelTwoArray, evoLevelThreeArray, mega, primal);
}
// FIND AVAILABLE EVOLUTION TRIGGER LOCATIONS
function locationFinder(bot, message, pokemonName, pokemonChainUrl, displayName, evolutionInfos, first, secondLevel, thirdLevel, evoLevelTwoArray, evoLevelThreeArray, mega, primal) {
var availableLocationsArray = [];
// pre-sorting pokemon levels and checking if they have a specified location for evolution trigger.
// if yes, save the region and displayName in the same location object and push that object into an array that will be passed to further functions
if (evoLevelTwoArray.length > 0) { // if at least 2 stages evolution
var count = evoLevelTwoArray.length;
var count2 = null;
var locationFound = null;
var locationCounter = 0;
console.log(count, 'count beginning')
evoLevelTwoArray.forEach(function(evolution) { // loop over second-stage pokemon
var evolutionDetails = evolution.evolution_details;
if (evoLevelThreeArray.length > 0) { // if 3rd-stage evolution level exists
var location2Found = null;
count2 = evoLevelThreeArray.length;
evoLevelThreeArray.forEach(function(evolution) { // loop over 3rd stage pokemon
var evolutionDetails2 = evolution.evolution_details;
count2--;
evolutionDetails2.forEach(function(detail) { // for each evolution trigger details per pokemon
var locationInfos2 = detail.location;
if (locationInfos2 !== null) { // if there is a location
location2Found = true;
locationCounter++;
P.getLocationByName(locationInfos2.name) // get infos about that location with found name
.then(function(response) {
locationInfos2.region = response.region.name; // save corresponding region in found location object
response.names.forEach(function(name) { // loop over display names available
if (name.language.name === 'en') { // if name is in English
locationInfos2.displayName = name.name; // save corresponding name in found location object
}
});
availableLocationsArray.push(locationInfos2); // push location object with added region and displayName in an array
if (count2 === 0 && location2Found === true && locationCounter === availableLocationsArray.length) { // if
console.log(availableLocationsArray, 'availableLocationsArray');
console.log('possibility 1')
botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal);
}
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
} else if (count2 === 0 && location2Found === null) { // 3 evolution levels, without locations
console.log('possibility 2')
botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal);
}
});
});
} else { // two-stage evolution pokemon
count--;
console.log(count, 'count')
evolutionDetails.forEach(function(detail) {
var locationInfos = detail.location;
console.log(locationInfos, ', locationInfos')
if (locationInfos !== null) {
locationFound = true;
locationCounter++;
P.getLocationByName(locationInfos.name)
.then(function(response) {
console.log(response.region.name, 'response.region.name')
locationInfos.region = response.region.name;
response.names.forEach(function(name) {
if (name.language.name === 'en') {
locationInfos.displayName = name.name;
}
});
console.log(locationInfos, 'locationInfos')
availableLocationsArray.push(locationInfos);
if (count2 === null && count === 0 && locationFound === true && locationCounter === availableLocationsArray.length) {
console.log(availableLocationsArray, 'availableLocationsArray');
console.log('possibility 3')
botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal);
}
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
} else if (count === 0 && locationFound === null && evolution.evolves_to.length === 0) { // 2 evolution levels, without locations
console.log('possibility 4')
botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal);
}
});
}
});
console.log(locationCounter, 'locationCounter')
} else { // one level only pokemon
console.log('possibility 5')
botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal);
}
}
// BOT SAY EVOLUTION
function botSayEvolution(bot, message, displayName, evolutionInfos, evoLevelTwoArray, evoLevelThreeArray, first, secondLevel, thirdLevel, pokemonName, availableLocationsArray, mega, primal) {
bot.startConversation(message, function(err, convo) {
if (!err) {
var megaDisplay = '';
var megaChain = '';
var primalChain = '';
var primalDisplay = '';
if (mega.length > 0) {