-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lol-rankify.js
647 lines (584 loc) · 25 KB
/
lol-rankify.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
registerPlugin({
name: 'League Of Legends Rankify',
version: '1.4.2',
backends: ['ts3'],
description: 'Adds the corresponding League Of Legends Rank, Level, Role & InGame status for each user',
author: 'Erin McGowan <sinusbot_lolrankify@protected.calmarsolutions.ch>',
requiredModules: ['http', 'store'],
vars: [
{
name: 'LeagueOfLegendsApiKey',
title: 'Official RIOT API Key needed',
type: 'string',
placeholder: 'Looks like this: RGAPI-3ffb7016-687d-414a-aff4-0d5f18069a78'
},
{
name: 'LeagueRegion',
title: 'Select Riot Games Region',
type: 'select',
options: ['br1', 'eun1', 'euw1', 'jp1', 'kr', 'la1', 'la2', 'na1', 'oc1', 'tr1', 'ru']
},
{
name: 'RankQueueType',
title: 'Select the Rank-queue/s you want to show. DEFAULT = highest of both ranks',
type: 'select',
options: ['highest of both ranks', 'solo/duo rank', 'flex rank']
},
{
name: 'NameForSummonerSearch',
title: 'Select if you want to use "TS3 User Nicknames" INSTEAD of the "TS3 User Description" in this script. DEFAULT = description',
type: 'checkbox',
options: ['useNickname']
},
{
name: 'summonerLevelGroupIDs',
title: 'Add Summoner Level groups for lvl "0-30, 30+, 50+, 75+, 100+, 150+, 200+, 250+, 500+" in this order. (USE ENTER KEY)',
type: 'strings',
},
{
name: 'summonerLaneGroupIDs',
title: 'Add Summoner Lane groups for "TOP_LANE, MID_LANE, BOT_LANE, JUNGLE, SUPPORT" in this order. (USE ENTER KEY)',
type: 'strings',
},
{
name: 'gameHistoryCountToConsider',
title: 'The ammount of lol games (history) to consider when calculation the role (blank = default 60)',
type: 'select',
placeholder: '60',
options: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100']
},
{
name: 'inGameGroupId',
title: 'Empty/blank = disabled. Add the group ID that gets added if the user is ingame.',
type: 'number',
},
{
name: 'inGameFunctionInterval',
title: 'How often to check if user is ingame. Default = 60. Use seconds, not milliseconds!',
placeholder: '60',
type: 'number',
},
{
name: 'PermUserSetDescr',
title: 'Allow users to set their own description with !lolsetname <string>',
type: 'select',
options: ['no', 'yes'],
placeholder: 'Default = no'
},
{ //-- Ranks
name: 'GroupUndefined',
title: 'Input Group if Unranked (Group ID). (NOT REQUIRED!)',
type: 'number'
},
{
name: 'GroupIron',
title: 'Input Group For Iron (Group ID)',
type: 'number'
},
{
name: 'GroupBronze',
title: 'Input Group For Bronze (Group ID)',
type: 'number'
},
{
name: 'GroupSilver',
title: 'Input Group For Silver (Group ID)',
type: 'number'
},
{
name: 'GroupGold',
title: 'Input Group For Gold (Group ID)',
type: 'number'
},
{
name: 'GroupPlatinum',
title: 'Input Group For Platinum (Group ID)',
type: 'number'
},
{
name: 'GroupDiamond',
title: 'Input Group For Diamond (Group ID)',
type: 'number'
},
{
name: 'GroupMaster',
title: 'Input Group For Master (Group ID)',
type: 'number'
},
{
name: 'GroupGrandmaster',
title: 'Input Group For Grandmaster (Group ID)',
type: 'number'
},
{
name: 'GroupChallenger',
title: 'Input Group For Challenger (Group ID)',
type: 'number'
}, //-- END Ranks
{
name: 'messageUnranked',
title: 'Input your message incase the client is unranked',
type: 'string',
placeholder: 'Sorry. You are unranked.',
},
{
name: 'messageRankReload',
title: 'Input your message for when the client reloads the rank manually',
type: 'string',
placeholder: 'Your rank was reloaded.',
},
],
}, function(sinusbot, config) {
// Variables
const engine = require('engine')
const backend = require('backend')
const event = require('event')
const http = require('http')
const store = require('store')
const apiKey = config.LeagueOfLegendsApiKey
const protocol = 'https://'
const groupUndefined = config.GroupUndefined
const leagueRankGroupIDs = [config.GroupIron, config.GroupBronze, config.GroupSilver, config.GroupGold, config.GroupPlatinum, config.GroupDiamond, config.GroupMaster, config.GroupGrandmaster, config.GroupChallenger]
const officialRankNamesArray = ['IRON', 'BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND', 'MASTER', 'GRANDMASTER', 'CHALLENGER']
const officialLaneNamesArray = ['TOP', 'MID', 'BOTTOM', 'JUNGLE', 'SUPPORT', 'NONE']
const gameHistoryNumbers = ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100']
const permUserSetDescr = config.PermUserSetDescr || 'no'
const summonerLevelGroupIDsArray = config.summonerLevelGroupIDs
const summonerLaneGroupIDsArray = config.summonerLaneGroupIDs
const inGameGroupId = config.inGameGroupId
const nameForSummonerSearch = config.NameForSummonerSearch
//--
// Derived Variables
let clients // setting them in mainEvent now
let clientName
let leagueRegionShort = ['br1', 'eun1', 'euw1', 'jp1', 'kr', 'la1', 'la2', 'na1', 'oc1', 'tr1', 'ru']
let apiUrlSummonerV4Name
let apiUrlLeagueV4Summoner
let requestArray = []
let gameHistoryCount = gameHistoryNumbers[config.gameHistoryCountToConsider]
if (!gameHistoryCount) {
gameHistoryCount = 60
}
let inGameFunctionInterval = config.inGameFunctionInterval
if (!inGameFunctionInterval) {
inGameFunctionInterval = 60
}
let rankQueueTypeSelection = config.RankQueueType
if (!rankQueueTypeSelection) {
rankQueueTypeSelection = 0
}
let summonerTier
//--
// Objects
//--
// Var Messages
let message = {
rankReload: config.messageRankReload,
unranked: config.messageUnranked,
newDescription: config.messageNewDescription,
}
if (!message.rankReload) { message.rankReload = 'Your rank was reloaded.' }
if (!message.unranked) { message.unranked = 'Sorry. You are unranked.' }
if (!message.newDescription) { message.newDescription = 'Your description is now: ' }
//--
event.on('clientVisible', function (ev) {
backendClientsReload()
if (nameForSummonerSearch) {
clientName = ev.client.nick()
} else {
clientName = ev.client.description()
}
mainEvent(client = ev.client, clientName)
})
event.on('chat', function(ev) {
backendClientsReload()
if (nameForSummonerSearch) {
clientName = ev.client.nick()
} else {
clientName = ev.client.description()
}
if (ev.text === '!lolreload') {
console.log('Reloaded Rank of: ' + ev.client.name() )
mainEvent(client = ev.client, clientName)
ev.client.chat(message.rankReload)
}
if (ev.text === '!lolreload all') {
ev.client.chat('...reloading')
let chain = Promise.resolve()
for (let client of clients) {
if (nameForSummonerSearch) {
chain = chain.then(resolve => mainEvent(client, client.nick()))
} else {
chain = chain.then(resolve => mainEvent(client, client.description())).then(delay(300))
}
ev.client.chat('--> Reloaded rank of ' + client.name() + '.')
}
ev.client.chat('ALL ranks reloaded.')
}
if (ev.text.startsWith('!lolsetname') && permUserSetDescr === '1') { // user can set description by himself
let newDescription = ev.text.replace(/!lolsetname /, '')
ev.client.setDescription(newDescription)
ev.client.chat(message.newDescription + newDescription)
mainEvent(client = ev.client, clientName)
ev.client.chat(message.rankReload)
}
if (ev.text === '!lolignoreme') {
lolIgnore()
function lolIgnore () {
let clientUID = ev.client.uid()
let status = store.get(clientUID + '_ignoreme')
if (status !== false) {
store.set(clientUID + '_ignoreme', false)
ev.client.chat('Your InGame status is now INVISIBLE/HIDDEN.')
simpleServerGroupRemove(ev.client, inGameGroupId)
} else {
store.unset(clientUID + '_ignoreme')
ev.client.chat('Your InGame status is now VISIBLE.')
}
}
}
})
let delay = (time) => (result) => new Promise(resolve => setTimeout(() => resolve(result), time));
function backendClientsReload() {
clients = backend.getClients() // get list of all current clients
}
function mainEvent(client, userName) {
return new Promise(function (resolve) {
if (userName.length > 2) {
apiUrlSummonerV4Name = protocol + leagueRegionShort[config.LeagueRegion] + '.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + userName.replace(/ /g, '%20') + '?api_key=' + apiKey;
if (client.getServerGroups().length > 0) {
makeRequest(apiUrlSummonerV4Name)
.then(result => makeRequest(protocol + leagueRegionShort[config.LeagueRegion] + '.api.riotgames.com/lol/league/v4/entries/by-summoner/' + result.id + '?api_key=' + apiKey))
.catch(error => engine.log('Error: ' + error))
.then(result => {
return new Promise(function (resolve) {
if (result[0] && result[0].tier) {
rankQueueTypeSwitch(result)
.then(result => {
compareLocalGroups(result, client.getServerGroups(), leagueRankGroupIDs, officialRankNamesArray, summonerTier, client)
}).then(result => {
resolve(result)
})
} else if (groupUndefined) {
addServerGroupRanked(client, groupUndefined)
resolve(result)
} else {
resolve(result)
}
})
})
.catch(error => engine.log('Error: ' + error))
.then(result => makeRequest(protocol + leagueRegionShort[config.LeagueRegion] + '.api.riotgames.com/lol/match/v4/matchlists/by-account/' + requestArray[0].accountId + '?api_key=' + apiKey + '&endIndex=' + gameHistoryCount))
.catch(error => engine.log('Error: ' + error))
.then(result => checkLaneStats(result, client))
.catch(error => engine.log('Error: ' + error))
.then(result => checkSummonerLevel(summonerLevelGroupIDsArray, requestArray[0].summonerLevel, client, result))
.catch(error => engine.log('Error: ' + error))
.then(result => {
requestArray = []
resolve(result)
})
.catch(error => engine.log('Error: ' + error));
}
} else {
resolve(client.name() + ' has no valid description.')
}
})
}
// -------- CHECK IF CLIENT / SUMMONER IS INGAME
function interval() {
backendClientsReload()
let statusChain = Promise.resolve()
for (let client of clients) {
statusChain = statusChain.then(result => checkInGameStatus(client))
}
}
if (inGameGroupId && inGameFunctionInterval) { // disable in-game status if no input in backend
// runs every 60 sec and runs on init.
interval();
setInterval(interval, inGameFunctionInterval * 1000)
}
function summonerNotInGame(client) {
return new Promise(function (resolve) {
simpleServerGroupRemove(client, inGameGroupId)
resolve()
})
}
function summonerInGame(client) {
return new Promise(function (resolve) {
addServerGroupRanked(client, inGameGroupId)
resolve()
})
}
function checkResult(client, result) { // used instead of .catch()
return new Promise(function (resolve) {
if (result !== undefined) {
summonerInGame(client, result)
} else {
summonerNotInGame(client, result)
}
resolve()
})
}
function checkInGameStatus(client) {
return new Promise(function (resolve) {
let userName
if (nameForSummonerSearch) {
userName = client.nick();
} else {
userName = client.description();
}
if (userName.length > 2 && store.get(client.uid() + '_ignoreme') !== false) {
apiUrlSummonerV4Name = protocol + leagueRegionShort[config.LeagueRegion] + '.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + userName.replace(/ /g, '%20') + '?api_key=' + apiKey;
makeRequest(apiUrlSummonerV4Name, '', '', '', true)
.then(result => makeRequest(protocol + leagueRegionShort[config.LeagueRegion] + '.api.riotgames.com/lol/spectator/v4/active-games/by-summoner/' + result.id + '?api_key=' + apiKey, '', '', '', true))
.catch(result => console.log('Failed. "' + client.name() + '" is not InGame: ' + result))
.then(result => checkResult(client, result))
.catch(result => console.log('Unexpected Error: ' + result))
.then(result => resolve('Success. "' + client.name() + '" is InGame.'))
} else {
resolve('No Summoner Name found for ' + client.name() + '.')
}
})
}
// -------- END CHECK IF CLIENT / SUMMONER IS INGAME
function rankQueueTypeSwitch(result) {
return new Promise(function (resolve) {
summonerTier = ''
let compareTiers = []
for (let item of result) {
if (rankQueueTypeSelection === '0') { // both
compareTiers.push(item.tier)
} else if (rankQueueTypeSelection === '1') { // solo
if (item.queueType === 'RANKED_SOLO_5x5') {
summonerTier = item.tier
}
} else if (rankQueueTypeSelection === '2') { // flex
if (item.queueType === 'RANKED_FLEX_SR') {
summonerTier = item.tier
}
}
}
if (rankQueueTypeSelection === '0' && compareTiers.length > 0) {
compareStringToIndex(compareTiers[0], compareTiers[1])
} else {
resolve(result)
}
function compareStringToIndex(tierOne, tierTwo) {
// compare name to index, get the value and use the highest defined value
let indexOne = officialRankNamesArray.indexOf(tierOne)
let indexTwo = officialRankNamesArray.indexOf(tierTwo)
if (tierOne && tierTwo) {
if (indexOne >= indexTwo) {
summonerTier = tierOne
} else if (indexTwo > indexOne) {
summonerTier = tierTwo
}
} else if (tierOne) {
summonerTier = tierOne
} else if (tierTwo) {
summonerTier = tierTwo
}
resolve(result)
}
})
}
function compareServerGroups(serverGroupList, groupIDsArray, currentGroup, client) {
for (let clientGroup of serverGroupList) { // client groups
for (let group of groupIDsArray) {
if (group === clientGroup.id()) { // array of groups
if (group !== currentGroup) // if not equal to group that should be added
removeServerGroupRanked(group, client)
}
}
}
}
function checkLaneStats(parsed, client) {
return new Promise(function (resolve) {
if (summonerLaneGroupIDsArray.length > 4 && parsed && parsed.matches) {
let map = new Map()
map.set('TOP', 0)
map.set('MID', 0)
map.set('BOTTOM', 0)
map.set('JUNGLE', 0)
map.set('NONE', 0)
let map_role = new Map()
map_role.set('SOLO', 0)
map_role.set('DUO', 0)
map_role.set('NONE', 0)
map_role.set('DUO_CARRY', 0)
map_role.set('DUO_SUPPORT', 0)
for (let item of parsed.matches) {
let number = map.get(item.lane)
map.set(item.lane, number + 1)
number = map_role.get(item.role)
map_role.set(item.role, number + 1)
}
let mostUsedLane = [...map.entries()].reduce((a, e) => e[1] > a[1] ? e : a) // get the map with the highest value
let mostUsedLaneName = mostUsedLane[0]
let mostUsedRole = [...map_role.entries()].reduce((a, e) => e[1] > a[1] ? e : a) // get the map with the highest value
let mostUsedRoleName = mostUsedRole[0]
if (mostUsedLaneName === 'BOTTOM') {
if (mostUsedRoleName === 'DUO_SUPPORT') {
mostUsedLaneName = 'SUPPORT'
}
}
if (mostUsedLaneName === 'NONE') { // role is unclear
client.chat('Lane Preference Unclear.')
resolve(parsed)
return
}
compareLocalGroups(parsed, client.getServerGroups(), summonerLaneGroupIDsArray, officialLaneNamesArray, mostUsedLaneName, client)
resolve(parsed)
} else {
resolve(parsed)
}
})
}
function checkSummonerLevel(groupIDsArray, level, client, request) {
return new Promise(function (resolve, reject) {
if (summonerLevelGroupIDsArray) {
if (groupIDsArray !== undefined) {
function execute(number) {
compareServerGroups(client.getServerGroups(), groupIDsArray, groupIDsArray[number], client)
addServerGroupRanked(client, groupIDsArray[number])
}
if (level < 30) { //-25
execute(0)
} else if (level < 50) { //25
execute(1)
} else if (level < 75) { //50
execute(2)
} else if (level < 100) { //75
execute(3)
} else if (level < 150) { //100
execute(4)
} else if (level < 200) { //150
execute(5)
} else if (level < 250) { //200
execute(6)
} else if (level < 500) { //250
execute(7)
} else if (level > 500) { //500+
execute(8)
} else {
reject('An Unknown Error Occurred. var level is not a number.')
}
resolve(request) // continue to forward the request
} else {
reject('Can\'t work with Array. Array empty.')
}
} else {
resolve(request)
}
})
}
function compareLocalGroups(parsed, currentGroups, groupArrayIDs, groupNamesArray, newGroupName, client) {
return new Promise(function (resolve) {
let count = 0
let countMax = currentGroups.length * groupArrayIDs.length
let compareSwitch = false
for (let currentGroup of currentGroups) {
for (let groupID of groupArrayIDs) { // check if one of the Rank Groups match the added groups
if (currentGroup.id() == groupID) {
count++
compareSwitch = true
compareGroup(parsed, currentGroup.id(), groupArrayIDs, groupNamesArray, newGroupName, client)
resolve(parsed)
} else {
count++
if (count === countMax && compareSwitch === false) {
compareGroup(parsed, undefined, groupArrayIDs, groupNamesArray, newGroupName, client)
resolve(parsed)
}
}
}
}
simpleServerGroupRemove(client, groupUndefined) // remove rank undefined group if client has it
if (!newGroupName) {
resolve()
}
})
}
function compareGroup(parsed, currentGroup, theNewGroupIdArray, theNewGroupNameArray, newGroupName, client) { // beware that currentGroup will be removed!
return new Promise(function (resolve) {
if (parsed) {
let newGroup = theNewGroupNameArray.indexOf(newGroupName) // get the index by string
newGroup = theNewGroupIdArray[newGroup] // insert index to get correct group
if (currentGroup == newGroup) {
resolve()
} else if (currentGroup != newGroup) {
if (currentGroup !== undefined) {
removeServerGroupRanked(currentGroup, client)
}
addServerGroupRanked(client, newGroup)
resolve()
}
} else {
client.chat(message.unranked)
}
})
}
function addServerGroupRanked(client, group) {
return new Promise(function (resolve) {
let count = 0
let max = client.getServerGroups().length
for (let groupId of client.getServerGroups()) {
if (groupId.id() == group) {
resolve('Group exists. None added to: ' + client.name())
return
}
count++
if (count === max) {
client.addToServerGroup(group)
resolve('Rank added for ' + client.name())
}
}
})
}
function removeServerGroupRanked(group, client) {
return new Promise(function (resolve) {
client.removeFromServerGroup(group)
resolve()
})
}
function simpleServerGroupRemove(client, groupToRemove) {
return new Promise(function (resolve) {
for (let group of client.getServerGroups()) {
if (group.id() == groupToRemove) {
client.removeFromServerGroup(groupToRemove)
resolve()
}
}
})
}
function makeRequest(url, method, datatype, timeout, prevent_push_array) {
return new Promise(function (resolve, reject) {
http.simpleRequest({
'method': method || 'GET',
'url': url,
'dataType': datatype || 'json',
'timeout': timeout || 6000,
}, function (error, response) {
if (error) {
reject(error)
}
if (response.statusCode == 403) {
console.log('YOUR API KEY WAS REJECTED.')
reject(response.status)
}
if (response.statusCode == 404) {
reject(response.status)
}
if (response.statusCode != 200) {
reject(response.status)
}
let parsed = JSON.parse(response.data)
if (!prevent_push_array) { // stops the array push if true
requestArray.push(parsed)
}
resolve(parsed);
});
})
}
});