-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbotCommands.py
663 lines (539 loc) · 26.4 KB
/
botCommands.py
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
import discord
import humanfriendly
import json
import requests
import time
from datetime import datetime, date, timedelta
from conversions import metersToMiles, metersToFeet, getMinPerKm, getMinPerMile
from discord.ext import commands
import botGlobals
import cmdImpl
import help
import userData
import distanceLeader
# Commands for the bot...just make sure to append to the commandList to register the command
commandList = []
@commands.command()
async def debug(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
admin = await botGlobals.checkAdmin(ctx=ctx)
if admin:
dmChannel = user.dm_channel
if dmChannel is None:
dmChannel = await user.create_dm()
embed = discord.Embed()
embed = discord.Embed(color=0x00ff00)
embed.title = f"**DEBUG:**\n"
embed.description = botGlobals.debugInit
monthCollection = await userData.getDataCollection(botGlobals.monthlyMileageData)
currentMileage = await userData.getMontlyMileage(monthyear=botGlobals.currentMonthYear)
await dmChannel.send('Test working...')
currentTime = datetime.now()
currentMonth = currentTime.month
currentMonthYear = currentTime.strftime(botGlobals.monthFormat)
leaderboardJSON = await botGlobals.loadLastLeaderboard()
if leaderboardJSON is not None:
await dmChannel.send('Crown last weeks...')
# Monthly data is format
# {"6.2021" : {'stravaId': {meters,
# 'stravaId2': meters}}
# dataValues = {}
# for i, rankedUser in enumerate(leaderboardJSON['data']):
# athleteId = rankedUser['athlete_id']
# meters = rankedUser['distance']
# dataValues[str(athleteId)] = rankedUser['distance']
#
# await userData.setMontlyMileage(monthyear=currentMonthYear, data=dataValues)
await distanceLeader.crownDistanceLeadersImpl(channel=dmChannel)
commandList.append(debug)
@commands.command(name='fulllb', aliases=('fullleaderboard','fullboard'))
async def _fullleaderboard(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
await cmdImpl.leaderboardImpl(channel=currChannel, bot=ctx.bot, registeredOnly=False)
commandList.append(_fullleaderboard)
@commands.command(name='fullvert', aliases=('fullvertlb','fullvlb'))
async def _fullvert(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
await cmdImpl.vertleaderboardImpl(channel=currChannel, bot=ctx.bot)
commandList.append(_fullvert)
@commands.command(name='distanceleader', aliases=('dlb','dleader'))
async def _distanceLeader(ctx, *args):
# Update the Mongo DB data for avatar_url and display_name
# ADMIN ONLY
user = ctx.message.author
dmChannel = user.dm_channel
if dmChannel is None:
dmChannel = await user.create_dm()
admin = await botGlobals.checkAdmin(ctx=ctx)
if admin:
try:
await dmChannel.send('Starting assignment...')
leaderboardJSON = await botGlobals.loadLastLeaderboard()
if leaderboardJSON is not None:
distanceWinnerMale = None
distanceWinnerFemale = None
for i, rankedUser in enumerate(leaderboardJSON['data']):
athleteId = rankedUser['athlete_id']
meters = rankedUser['distance']
aUser = await userData.retrieveNickname(athleteId)
if aUser is not None:
# Retrieve the gender
gender = await userData.retrieveGender(athleteId)
if gender == 'male':
if distanceWinnerMale is None:
distanceWinnerMale = await userData.retrieveDiscordID(athleteId)
elif gender == 'female':
if distanceWinnerFemale is None:
distanceWinnerFemale = await userData.retrieveDiscordID(athleteId)
currentMale, currentFemale = await userData.getDistanceLeader()
maleWinner = None
femaleWinner = None
if distanceWinnerMale is not None:
# Put into database
await userData.setDistanceLeader(gender='male', id=distanceWinnerMale)
for m in botGlobals.bot.get_all_members():
if m.id == distanceWinnerMale:
maleWinner = m
break
#maleWinner = await cmdImpl.assignLeader(role=botGlobals.distanceMaleRole, id=distanceWinnerMale,
#currentLeader=currentMale['male'])
if distanceWinnerFemale is not None:
# Put into database
await userData.setDistanceLeader(gender='female', id=distanceWinnerFemale)
for m in botGlobals.bot.get_all_members():
if m.id == distanceWinnerFemale:
femaleWinner = m
break
#femaleWinner = await cmdImpl.assignLeader(role=botGlobals.distanceFemaleRole, id=distanceWinnerFemale,
#currentLeader=currentFemale['female'])
announceChannel = None
for c in botGlobals.bot.get_all_channels():
if c.name == botGlobals.announceChannel:
announceChannel = c
await dmChannel.send('Announce channel '+str(announceChannel))
if announceChannel is not None:
doAnnounce = False
mesg = 'Last week leaderboard results:\n'
if maleWinner is not None:
doAnnounce = True
mesg += maleWinner.mention + ': Distance King.\n'
if femaleWinner is not None:
doAnnounce = True
mesg += femaleWinner.mention + ': Distance Queen.\n'
if doAnnounce:
try:
await cmdImpl.leaderboardImpl(channel=announceChannel, bot=botGlobals.bot,registeredOnly=True,
entries=None, leaderboardJSON=leaderboardJSON)
except Exception as e:
print(e)
await announceChannel.send(mesg)
except Exception as e:
await dmChannel.send(e)
else:
dmChannel.send('!distanceleader is an admin only command.')
pass
commandList.append(_distanceLeader)
@commands.command(name='lastmonth', aliases=('last', 'lmonth'))
async def _lastmonth(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
# Monthly data is format
# {"6_2021" : {'stravaId': meters,
# 'stravaId2': meters}}
dataValues = {}
currentTime = datetime.now()
currentMonth = currentTime.month
lastMonth = currentTime.replace(month=currentMonth-1).strftime(botGlobals.monthFormat)
#lastMonth = botGlobals.currentMonthYear-1
currentMileage = await userData.getMontlyMileage(monthyear=lastMonth)
# Add the mileage together
metersPerAthlete = currentMileage[lastMonth]
for strava,m in metersPerAthlete.items():
dataValues[strava] = m
# Display the new information
dataValues = dict(sorted(dataValues.items(), key=lambda x: x[1], reverse=True))
linesPerEmbed = 20
embedMesg = []
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
embed.title = f"**{botGlobals.STRAVACLUB_PRETTYNAME} {lastMonth} Monthly Distance Leaderboard:**\n"
embedMesg.append(embed)
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
i = 0
leaderboardMsg = ""
for strava,m in dataValues.items():
# Don't display until the athlete overcame the left-over mileage at the beginning of month
if m <= 0:
continue
boldstr = ""
if i < 10:
boldstr = "**"
aUser = await userData.retrieveNickname(int(strava))
if aUser is not None:
leaderboardMsg += boldstr + str(i+1) + '. '
leaderboardMsg += aUser
leaderboardMsg += ' - ' + \
"{:,}".format(round(m/1000, 2)) + \
' km (' + \
metersToMiles(m) + \
')' + boldstr + '\n'
# Printing everything so use lines per embed
if linesPerEmbed <= 0:
# Store current
embed.description = leaderboardMsg
embedMesg.append(embed)
# Start a new embed message
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
linesPerEmbed = 20
leaderboardMsg = ''
else:
linesPerEmbed -= 1
i += 1
if leaderboardMsg:
embed.description = leaderboardMsg
embedMesg.append(embed)
# Add info text at hte bottom
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
infoMesg = 'Shows and tracks registered users only. Type !register for details on how to register.'
embed.description = infoMesg
embedMesg.append(embed)
for e in embedMesg:
await currChannel.send(embed=e)
commandList.append(_lastmonth)
@commands.command(name='leaderboard', aliases=('lb','leader'))
async def _leaderboard(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
await cmdImpl.leaderboardImpl(channel=currChannel, bot=ctx.bot, entries=30)
commandList.append(_leaderboard)
@commands.command(name='monthleaderboard', aliases=('monthlb', 'month'))
async def _monthleaderboard(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
# Load the current leaderboard and add up everything then sort
leaderboardJSON = await botGlobals.loadLeaderboard()
if leaderboardJSON is not None:
# Monthly data is format
# {"6_2021" : {'stravaId': meters,
# 'stravaId2': meters}}
dataValues = {}
for i, rankedUser in enumerate(leaderboardJSON['data']):
athleteId = rankedUser['athlete_id']
meters = rankedUser['distance']
aUser = await userData.retrieveNickname(athleteId)
if aUser is not None:
dataValues[str(athleteId)] = rankedUser['distance']
currentMileage = await userData.getMontlyMileage(monthyear=botGlobals.currentMonthYear)
# Add the mileage together
metersPerAthlete = currentMileage[botGlobals.currentMonthYear]
for strava,m in metersPerAthlete.items():
if strava in dataValues:
dataValues[strava] = dataValues[strava] + m
else:
# This athelete wasn't found in the current leaderboard add their data
dataValues[strava] = m
# Display the new information
dataValues = dict(sorted(dataValues.items(), key=lambda x: x[1], reverse=True))
linesPerEmbed = 20
embedMesg = []
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
embed.title = f"**{botGlobals.STRAVACLUB_PRETTYNAME} {botGlobals.currentMonthYear} Monthly Distance Leaderboard:**\n"
embedMesg.append(embed)
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
i = 0
leaderboardMsg = ""
for strava,m in dataValues.items():
# Don't display until the athlete overcame the left-over mileage at the beginning of month
if m <= 0:
continue
boldstr = ""
if i < 10:
boldstr = "**"
aUser = await userData.retrieveNickname(int(strava))
if aUser is not None:
leaderboardMsg += boldstr + str(i+1) + '. '
leaderboardMsg += aUser
leaderboardMsg += ' - ' + \
"{:,}".format(round(m/1000, 2)) + \
' km (' + \
metersToMiles(m) + \
')' + boldstr + '\n'
# Printing everything so use lines per embed
if linesPerEmbed <= 0:
# Store current
embed.description = leaderboardMsg
embedMesg.append(embed)
# Start a new embed message
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
linesPerEmbed = 20
leaderboardMsg = ''
else:
linesPerEmbed -= 1
i += 1
if leaderboardMsg:
embed.description = leaderboardMsg
embedMesg.append(embed)
# Add info text at hte bottom
embed = discord.Embed()
embed = discord.Embed(color=0x0000ff)
infoMesg = 'Shows and tracks registered users only. Type !register for details on how to register.'
embed.description = infoMesg
embedMesg.append(embed)
for e in embedMesg:
await currChannel.send(embed=e)
commandList.append(_monthleaderboard)
@commands.command(name='register')
async def _register(ctx, *args):
# Interact with the user to connect their strava athlete id w/ discord id
# using the current leaderboard rank
# !register - sends DM describing command flow and leaderboard in a DM w/ leaderboard first
# !register <number of leaderboard> <gender> - Assigns the current strava athlete at that position to
# the discord user and prints out confirmation
# !register erase - Removes the current discord id from any strava id connection
# !register erase <number of lb> - Admin only command that removes that discord id from that strava athlete id
user = ctx.message.author
currChannel = ctx.message.channel
dmChannel = user.dm_channel
if dmChannel is None:
dmChannel = await user.create_dm()
# Test to see if the channel was created
try:
await dmChannel.send('Starting the registration process..')
except Exception as e:
print(e)
# Tell the user to turn on direct messages
mesg = user.mention + ' please turn on direct messages to start the registration process.'
await currChannel.send(mesg)
if (len(args) == 0):
# Open DM channel and display leaderboard w/ help on !register <rank>
await cmdImpl.registerCacheImpl(channel=dmChannel, bot=ctx.bot, discordId=ctx.message.author.id)
elif (len(args) == 1):
if args[0] == 'erase':
# Erase my entry in the database for discord id
deleteWorked = await userData.deleteDiscordID(discordId=ctx.message.author.id)
mesg = ''
if deleteWorked is not None:
mesg = 'Successfully removed registration. Type !register to restart the process if needed.'
else:
mesg = 'Registration not found for you.'
await dmChannel.send(mesg)
elif args[0].isdigit():
rankPos = int(args[0])
# Check the cache to see if its valid
checkCache = await userData.checkLeaderBoardCache(discordId=ctx.message.author.id)
if checkCache is not None:
# Set the strava ID
stravaId = None
wrongRank = True
# Use the cached leaderboard
leaderboardJSON = checkCache
if leaderboardJSON is not None:
for rank, rankedUser in enumerate(leaderboardJSON['data']):
if rank == (rankPos - 1):
# This is our athlete
stravaId = rankedUser['athlete_id']
wrongRank = False
break
if stravaId is not None:
# Delete any potential current registration
result = await userData.deleteDiscordID(discordId=ctx.message.author.id)
nickName = None
for m in botGlobals.bot.get_all_members():
if m.id == ctx.message.author.id:
nickName = m.nick
break
dataSet = await userData.setRegistration(discordId=ctx.message.author.id, stravaId=stravaId,
displayName=ctx.message.author.display_name,
#avatarURL=ctx.message.author.avatar_url,
nickname=nickName)
if dataSet:
# Display leaderboard for last check
await cmdImpl.leaderboardImpl(channel=dmChannel, bot=ctx.bot, registeredOnly=False)
# Remove cache and cache expiration
mesg = 'Please check above leaderboard to see if its accurate. If not type:\n'
mesg += ' !register erase then !register to restart registration process.'
await dmChannel.send(mesg)
else:
await dmChannel.send('Failed to set registration for strava ID: '+str(stravaId))
else:
if wrongRank:
await dmChannel.send('The rank you entered does not exist.')
else:
# Failed to load leaderboard
print('# ALS - failed to load')
await dmChannel.send('Failed to load leaderboard try again later.')
else:
# Cache is invalid display leaderboard and re-cache
await cmdImpl.registerCacheImpl(channel=dmChannel, bot=ctx.bot, discordId=ctx.message.author.id)
await dmChannel.send('```Please try again as the leaderboard may have changed and type !register <rank>.```')
elif (len(args) == 2):
admin = await botGlobals.checkAdmin(ctx=ctx)
if args[0] == 'erase':
if admin:
if args[1].isdigit():
deletePos = int(args[1])
stravaId = None
leaderboardJSON = await botGlobals.loadLeaderboard()
if leaderboardJSON is not None:
for rank, rankedUser in enumerate(leaderboardJSON['data']):
if rank == (deletePos - 1):
# This is our athlete
stravaId = rankedUser['athlete_id']
break
if stravaId is not None:
discordId = await userData.retrieveDiscordID(stravaId=stravaId)
deleteWorked = await userData.deleteDiscordID(discordId=discordId)
if deleteWorked:
await dmChannel.send('{ADMIN} : Deletion success.')
else:
print('# ALS - failed to load(3)')
await dmChannel.send('Failed to load the leaderboard.')
pass
elif args[0].isdigit():
rankPos = int(args[0])
gender = 'male'
if args[1] == 'female' or args[1] == 'f':
gender = 'female'
# Check the cache to see if its valid
checkCache = await userData.checkLeaderBoardCache(discordId=ctx.message.author.id)
if checkCache is not None:
# Set the strava ID
stravaId = None
wrongRank = True
# Use the cached leaderboard
leaderboardJSON = checkCache
if leaderboardJSON is not None:
for rank, rankedUser in enumerate(leaderboardJSON['data']):
if rank == (rankPos - 1):
# This is our athlete
stravaId = rankedUser['athlete_id']
wrongRank = False
break
if stravaId is not None:
# Delete any potential current registration
result = await userData.deleteDiscordID(discordId=ctx.message.author.id)
nickName = None
for m in botGlobals.bot.get_all_members():
if m.id == ctx.message.author.id:
nickName = m.nick
break
dataSet = await userData.setRegistration(discordId=ctx.message.author.id, stravaId=stravaId,
displayName=ctx.message.author.display_name,
#avatarURL=ctx.message.author.avatar_url,
nickname=nickName, gender=gender)
if dataSet:
# Display leaderboard for last check
await cmdImpl.leaderboardImpl(channel=dmChannel, bot=ctx.bot, registeredOnly=False)
# Remove cache and cache expiration
mesg = 'Please check above leaderboard to see if its accurate. If not type:\n'
mesg += ' !register erase then !register to restart registration process.'
await dmChannel.send(mesg)
else:
await dmChannel.send('Failed to set registration for strava ID: '+str(stravaId))
else:
if wrongRank:
await dmChannel.send('The rank you entered does not exist.')
else:
# Failed to load leaderboard
print('# ALS - failed to load')
await dmChannel.send('Failed to load leaderboard try again later.')
else:
# Cache is invalid display leaderboard and re-cache
await cmdImpl.registerCacheImpl(channel=dmChannel, bot=ctx.bot, discordId=ctx.message.author.id)
await dmChannel.send('```Please try again as the leaderboard may have changed and type !register <rank>.```')
# Clear our local registration cache
botGlobals.registrationCache = None
commandList.append(_register)
@commands.command()
async def shutdown(ctx, *args):
admin = await botGlobals.checkAdmin(ctx=ctx)
if admin:
await ctx.bot.close()
commandList.append(shutdown)
@commands.command()
async def stats(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
access_token = botGlobals.getToken()
if access_token is not None:
stravaAuthHeader = {'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(access_token)}
embed = discord.Embed()
embed = discord.Embed(color=0x00ff00)
embed.title = f"**{botGlobals.STRAVACLUB_PRETTYNAME} Weekly Statistics:**\n"
stravaResult = requests.get('https://www.strava.com/api/v3/clubs/' +
botGlobals.STRAVACLUB+'/activities',
headers=stravaAuthHeader)
if stravaResult.status_code == 200:
totalDistance = 0
totalElevationGain = 0
totalMovingTime = 0
totalActivitiesRecorded = len(stravaResult.json())
for activity in stravaResult.json():
totalDistance += activity['distance']
totalElevationGain += activity['total_elevation_gain']
totalMovingTime += activity['moving_time']
humanMovingTime = humanfriendly.format_timespan(totalMovingTime)
statisticsMsg = 'Together we have run: ' + \
"{:,}".format(round(totalDistance/1000, 2)) + \
' km (' + \
metersToMiles(totalDistance) + ')' + \
' over ' + str(totalActivitiesRecorded) + ' activities. \n'
statisticsMsg += 'Our total elevation gain is ' + \
"{:,}".format(round(totalElevationGain,2)) + ' m (' + \
metersToFeet(totalElevationGain) +'). \n'
statisticsMsg += 'Our total time spent moving is ' + \
humanMovingTime + '. \n'
embed.description = statisticsMsg
await currChannel.send(embed=embed)
else:
await currChannel.send('Failed to authorize to load activity data.')
else:
await currChannel.send('Error with Strava API. Try again later.')
commandList.append(stats)
@commands.command()
async def strava(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
embed = await help.helpMsg()
await currChannel.send(embed=embed)
commandList.append(strava)
@commands.command(name='time', aliases=('timelb','tlb'))
async def _time(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
await cmdImpl.timeleaderboardImpl(channel=currChannel, bot=ctx.bot)
commandList.append(_time)
@commands.command()
async def update(ctx, *args):
# Update the Mongo DB data for avatar_url and display_name
# ADMIN ONLY
user = ctx.message.author
dmChannel = user.dm_channel
if dmChannel is None:
dmChannel = await user.create_dm()
admin = await botGlobals.checkAdmin(ctx=ctx)
if admin:
failed = await cmdImpl.updateImpl(bot=botGlobals.bot)#await cmdImpl.updateImpl(ctx.bot)
if failed:
# Failure
await dmChannel.send('During the update command there was a failure')
else:
dmChannel.send('!update is an admin only command.')
pass
commandList.append(update)
@commands.command(name='vertleaderboard', aliases=('vertlb','vlb'))
async def _vertleaderboard(ctx, *args):
user = ctx.message.author
currChannel = ctx.message.channel
await cmdImpl.vertleaderboardImpl(channel=currChannel, bot=ctx.bot, entries=30)
commandList.append(_vertleaderboard)