-
Notifications
You must be signed in to change notification settings - Fork 17
/
Commands.py
2159 lines (1733 loc) · 87.1 KB
/
Commands.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
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
# Author: Michael Conard and Maxbrand99
# Purpose: An Axie Infinity utility bot. Gives QR codes and daily progress/alerts.
import asyncio
import datetime
import os
import time
import traceback
import discord
import pandas as pd
import plotly.graph_objects as go
from loguru import logger
from web3 import Web3
import ClaimSLP
import Common
import DB
import UtilBot
from Common import prefix, client, dmPayoutsToScholars
# Returns information on available commands
async def helpCommand(message, isManager, discordId, isSlash=False):
if not isSlash:
await message.channel.trigger_typing()
msg = 'Hello <@' + str(discordId) + '>! Here are the text command options:\n'
msg += ' - `' + prefix + 'help`: returns this help message\n'
msg += ' - `' + prefix + 'daily [name/ping/discordID]`: returns the player\'s match/SLP/quest data for today\n'
msg += ' - `' + prefix + 'axies [name/ping/discordID] [index] [m]`: returns the player\'s Axies, [index] is to select a team (default 0), set [m] for mobile friendly\n'
# msg += ' - `' + prefix + 'battles [name/ping/discordID]`: returns the scholar\'s recent battle records\n'
msg += ' - `' + prefix + 'membership`: returns information about the status of the user database\n'
if not isManager: # scholar
msg += ' - `' + prefix + 'qr`: DMs you your QR code to login to the mobile app\n'
msg += ' - `' + prefix + 'login`: DMs you your login info if your manager set it up\n'
msg += ' - `' + prefix + 'setPayoutAddress roninAddress`: sets the user\'s payout address, can be ronin: or 0x form\n'
msg += ' - `' + prefix + 'payout discordID`: triggers a payout for the user\n'
logger.info(len(msg))
await Common.handleResponse(message, msg, isSlash)
else: # manager
logger.info(len(msg))
await Common.handleResponse(message, msg, isSlash)
msg = ""
msg += ' - `' + prefix + 'export`: returns a listing of scholar information from the database\n'
msg += ' - `' + prefix + 'exportRole role`: returns a spreadsheet of users with a role; finds the closest match ("Scho" would likely find "Scholar")\n'
msg += ' - `' + prefix + 'getScholar [discordID]`: returns information on the caller, or the specified discord ID\n'
msg += ' - `' + prefix + 'addScholar seedNum accountNum accountAddr discordID scholarShare [scholarPayoutAddr]`: add a scholar to the database; scholar share is 0.50 to 1.00\n'
msg += ' - `' + prefix + 'removeScholar discordID`: removes the user\'s status as a scholar\n'
msg += ' - `' + prefix + 'addManager discordID`: add a manager to the database\n'
msg += ' - `' + prefix + 'removeManager discordID`: removes the user\'s status as a manager\n'
msg += ' - `' + prefix + 'updateScholarShare discordID scholarShare`: sets the user\'s share to the new value, 0.50 to 1.00\n'
msg += ' - `' + prefix + 'setPayoutAddress roninAddress discordID`: sets the specified user\'s payout address, can be ronin: or 0x form\n'
msg += ' - `' + prefix + 'setAccountLogin discordID roninAddress email pass`: records the account\'s login info, only usable by managers\n'
msg += ' - `' + prefix + 'setProperty property value`: sets a property to a value (like "massPay 0" to enable individual payouts)\n'
msg += ' - `' + prefix + 'getProperty property`: gets a property\'s value (try "massPay")\n'
msg += ' - `' + prefix + 'massPayout [seedFilter] [minIndex] [maxIndex]`: triggers a scholar payout for all scholars, optional filters\n'
msg += ' - `' + prefix + 'payout discordID`: triggers a payout for the specified user\n'
msg += ' - `' + prefix + 'disperse [amount]`: returns a csv that you can use in scatter\n'
msg += ' - `' + prefix + 'summary [sort] [ascending] [csv]`: returns a scholar summary, [avgslp/slp, mmr/rank, claim], [asc, desc], [csv]\n'
msg += ' - `' + prefix + 'top [sort] [csv]`: returns the scholar top 10 rankings, [avgslp/slp, mmr/rank, claim], [csv]\n'
logger.info(len(msg))
await Common.handleResponse(message, msg, isSlash)
return
# DM the caller their QR login code
async def qrCommand(message, discordId, guildId, isSlash=False):
if not isSlash:
await message.channel.trigger_typing()
if os.path.exists("./qr/" + str(message.author.id) + "QRCode.png"):
os.remove("./qr/" + str(message.author.id) + "QRCode.png")
# check for user's Discord ID
if message.author.id in Common.qrBlacklist:
msg = "Sorry, but QR generation isn't working for your account right now. Please talk to your manager."
await message.author.send(msg)
if guildId is not None:
msg = 'Hi <@' + str(discordId) + '>, please check your DMs!'
await Common.handleResponse(message, msg, isSlash)
return
author = await DB.getDiscordID(message.author.id)
if author["success"] and author["rows"]["is_scholar"]:
logger.info("This user received their QR Code : " + message.author.name)
scholar = author["rows"]
accountPrivateKey, accountAddress = await UtilBot.getKeyForUser(scholar)
if accountPrivateKey is None or accountAddress is None:
await Common.handleResponse(message, "Mismatch detected between configured scholar account address and seed/account indices, or scholar not found.", isSlash)
return
logger.info(f"Scholar {discordId} account addr confirmed as {accountAddress} via mnemonic")
if accountPrivateKey == "" or accountAddress == "":
msg = 'Sorry <@' + str(discordId) + '>, your manager has not configured QR code generation.'
await Common.handleResponse(message, msg, isSlash)
return
accessToken = UtilBot.getPlayerToken(accountPrivateKey, accountAddress)
if accessToken is None:
msg = 'Sorry <@' + str(discordId) + '>, there was an issue with your request. Please try again later.'
await Common.handleResponse(message, msg, isSlash)
return
# Create a QrCode with that accessToken
qrFileName = UtilBot.getQRCode(accessToken, message.author.id)
# Send the QrCode the the user who asked for
if isSlash:
# respond with hidden message QR
await message.edit(content="QR code sent!")
await message.channel.send(content="Here is your new QR Code to login, remember to always keep it safe and not to let anyone else see it:", file=discord.File(qrFileName), flags=(1 << 6))
# msg = 'Hi <@' + str(discordId) + f">, this slash command isn\'t implemented yet! Please try {prefix}qr"
# await Common.handleResponse(message, msg, isSlash)
else:
# respond with DM
await message.author.send(
"------------------------------------------------\n\n\nHello " + message.author.name + "\nHere is your new QR Code to login: ")
await message.author.send(file=discord.File(qrFileName))
await message.author.send("Remember to keep your QR code safe and don't let anyone else see it!")
if guildId is not None:
msg = 'Hi <@' + str(discordId) + '>, please check your DMs!'
await Common.handleResponse(message, msg, isSlash)
return
else:
logger.warning("This user didn't receive a QR Code : " + message.author.name)
msg = 'Hello <@' + str(discordId) + '>. Unfortunately, you do not appear to be one of ' + Common.programName + '\'s scholars.'
await Common.handleResponse(message, msg, isSlash)
return
# DM the caller their login info
async def loginInfoCommand(message, discordId, guildId, isSlash=False):
if not isSlash:
await message.channel.trigger_typing()
# check for user's Discord ID
if message.author.id in Common.qrBlacklist:
msg = "Sorry, but login isn't working for your account right now. Please talk to your manager."
await message.author.send(msg)
if guildId is not None:
msg = 'Hi <@' + str(discordId) + '>, please check your DMs!'
await Common.handleResponse(message, msg, isSlash)
return
author = await DB.getDiscordID(message.author.id)
if author["success"] and author["rows"]["is_scholar"]:
logger.info("This user received their login info : " + message.author.name)
scholar = author["rows"]
email = scholar["account_email"]
password = scholar["account_pass"]
if email is None or password is None:
msg = 'Sorry <@' + str(discordId) + '>, your manager has not configured login info.'
await Common.handleResponse(message, msg, isSlash)
return
# Send the info to the user who asked for it
if isSlash:
# respond with hidden message with info
await message.edit(content=f"Here is your login info, remember to always keep it safe and not to let anyone else see it:\nEmail: ||{email}||\nPassword: ||{password}||", flags=(1 << 6))
# msg = 'Hi <@' + str(discordId) + f">, this slash command isn\'t implemented yet! Please try {prefix}login"
# await Common.handleResponse(message, msg, isSlash)
else:
# respond with DM
await message.author.send(
"------------------------------------------------\n\n\nHello " + message.author.name + "\nHere is your new info to login: ")
await message.author.send(f"Email: ||{email}||\nPassword: ||{password}||")
await message.author.send(f"Remember to keep your login info safe and don't let anyone else see it!")
if guildId is not None:
msg = 'Hi <@' + str(discordId) + '>, please check your DMs!'
await Common.handleResponse(message, msg, isSlash)
return
else:
logger.warning("This user didn't receive login info : " + message.author.name)
msg = 'Hello <@' + str(discordId) + '>. Unfortunately, you do not appear to be one of ' + Common.programName + '\'s scholars.'
await Common.handleResponse(message, msg, isSlash)
return
# Set a database property, such as massPay
async def setPropertyCommand(message, args, isSlash=False):
authorID = message.author.id
if not await DB.isManager(authorID):
await Common.handleResponse(message, "You must be a manager to use this command", isSlash)
return
if len(args) < 3:
await Common.handleResponse(message, f"Please enter: {prefix}setProperty property value", isSlash)
return
prop = args[1]
val = args[2]
res = await DB.setProperty(prop, val)
await Common.handleResponse(message, res["msg"], isSlash)
# Get a database property, such as massPay
async def getPropertyCommand(message, args, isSlash=False):
if len(args) < 2:
await Common.handleResponse(message, f"Please enter: {prefix}getProperty property", isSlash)
return
prop = args[1]
res = await DB.getProperty(prop)
if not res["success"] or (res["success"] and res["rows"] is None):
await Common.handleResponse(message, f"Failed to get property {prop}", isSlash)
return
realV = res["rows"]["realVal"]
textV = res["rows"]["textVal"]
val = realV
if realV is None:
val = textV
embed = discord.Embed(title="Property Information", description=f"Request for property {prop}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name="Property", value=f"{prop}")
embed.add_field(name="Value", value=f"{val}")
if isSlash:
await message.edit(embed=embed)
else:
await message.reply(embed=embed)
# Command helper to issue and check a confirmation embed to the caller
async def processConfirmationAuthor(message, embed, timeoutSecs=None):
authorID = message.author.id
confMsg = await message.channel.send(embed=embed)
greenCheck = "\N{White Heavy Check Mark}"
redX = "\N{Cross Mark}"
options = [greenCheck, redX]
await confMsg.add_reaction(greenCheck)
await confMsg.add_reaction(redX)
def check(reaction, user):
emoji = UtilBot.getEmojiFromReact(reaction)
return int(user.id) == int(authorID) and emoji in options and int(reaction.message.id) == int(confMsg.id)
try:
reaction, user = await Common.client.wait_for('reaction_add', timeout=timeoutSecs, check=check)
emoji = UtilBot.getEmojiFromReact(reaction)
if emoji == greenCheck:
return confMsg, True
elif emoji == redX:
return confMsg, False
else:
return confMsg, None
except asyncio.TimeoutError:
return confMsg, None
# Command helper to issue and check a confirmation embed for any manager
async def processConfirmationManager(message, embed, timeoutSecs=None):
mgrIds = await DB.getAllManagerIDs()
confMsg = await message.channel.send(embed=embed)
greenCheck = "\N{White Heavy Check Mark}"
redX = "\N{Cross Mark}"
options = [greenCheck, redX]
await confMsg.add_reaction(greenCheck)
await confMsg.add_reaction(redX)
def check(reaction, user):
emoji = UtilBot.getEmojiFromReact(reaction)
return user.id in mgrIds and emoji in options and reaction.message == confMsg
try:
reaction, user = await Common.client.wait_for('reaction_add', timeout=timeoutSecs, check=check)
emoji = UtilBot.getEmojiFromReact(reaction)
if emoji == greenCheck:
return confMsg, True
elif emoji == redX:
return confMsg, False
else:
return confMsg, None
except asyncio.TimeoutError:
return confMsg, None
# Get a scholar's data
async def getScholar(message, args, discordId, isSlash=False):
authorID = message.author.id
if len(args) > 1 and not args[1].isnumeric():
await Common.handleResponse(message, "Please ensure the discord ID is correct", isSlash)
return
if len(args) > 1:
discordId = int(args[1])
name = await Common.getNameFromDiscordID(discordId)
if name is None:
await Common.handleResponse(message, "Could not find user with that discord ID", isSlash)
return
scholarRes = await DB.getDiscordID(discordId)
if not scholarRes["success"]:
await Common.handleResponse(message, "Failed to get scholar from database", isSlash)
return
if scholarRes["rows"] is None or scholarRes["rows"]["is_scholar"] is None or scholarRes["rows"]["is_scholar"] == 0:
await Common.handleResponse(message, f"Did not find a scholar with discord ID {discordId}", isSlash)
return
scholar = scholarRes["rows"]
scholarShare = round(float(scholar["share"]), 3)
scholarAddr = scholar["payout_addr"]
seedNum = scholar["seed_num"]
accountNum = scholar["account_num"]
createdTime = scholar["created_at"]
if Common.hideScholarRonins:
roninAddr = "<hidden>"
else:
roninAddr = scholar["scholar_addr"]
embed = discord.Embed(title="Scholar Information", description=f"Information about scholar {name}/{discordId}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordId}")
embed.add_field(name=":bar_chart: Scholar Share", value=f"{round(scholarShare * 100, 2)}%")
embed.add_field(name=":clock1: Scholar Created", value=f"<t:{createdTime}:D>")
embed.add_field(name="Seed", value=f"{seedNum}")
embed.add_field(name="Account", value=f"{accountNum}")
embed.add_field(name="Account Address", value=f"{roninAddr}")
embed.add_field(name="Payout Address", value=f"{scholarAddr}")
if isSlash:
await message.edit(content=f"<@{authorID}>", embed=embed)
else:
await message.reply(content=f"<@{authorID}>", embed=embed)
# Add a scholar to the system
async def addScholar(message, args, discordId, isSlash=False):
authorID = message.author.id
if not await DB.isManager(authorID):
await Common.handleResponse(message, "You must be a manager to use this command", isSlash)
return
if len(args) < 5:
await Common.handleResponse(message, "Please specify: seedNum accountNum roninAddr discordUID scholarShare [payoutAddress]", isSlash)
return
seedNum = args[1]
accountNum = args[2]
roninAddr = args[3]
discordUID = args[4]
payoutAddress = ""
scholarShare = 0.5 # pull from default config
if (not seedNum.isnumeric() or int(seedNum) < 1) or (not accountNum.isnumeric() or int(accountNum) < 1) or not str(discordUID).isnumeric():
await Common.handleResponse(message, "Please ensure your seed/account indices are >= 1 and the discord ID is correct", isSlash)
return
if (not roninAddr.startswith("0x")) and (not roninAddr.startswith("ronin:")):
await Common.handleResponse(message, "Please ensure your ronin address begins with '0x' or 'ronin:'", isSlash)
return
roninAddr = roninAddr.replace("ronin:", "0x").strip()
name = await Common.getNameFromDiscordID(discordUID)
if name is None:
await Common.handleResponse(message, "Could not find user with that discord ID", isSlash)
return
if len(args) >= 6 and Common.isFloat(args[5]):
scholarShare = round(float(args[5]), 3)
if scholarShare < 0.50 or scholarShare > 1.0:
await Common.handleResponse(message, "Please ensure your scholar share is between 0.50 and 1.00", isSlash)
return
if len(args) >= 7 and args[6]:
payoutAddress = args[6].replace("ronin:", "0x").strip()
if not Web3.isAddress(payoutAddress):
await Common.handleResponse(message, "Payout address does not appear to be a valid address. Please check it.", isSlash)
return
scholarsDB = await DB.getAllScholars()
if not scholarsDB["success"]:
await Common.handleResponse(message, "Failed to query database for scholars", isSlash)
return
for scholar in scholarsDB["rows"]:
seedNum2 = int(scholar["seed_num"])
accNum2 = int(scholar["account_num"])
if int(seedNum) == seedNum2 and accNum2 == int(accountNum):
await Common.handleResponse(message, "A scholar already exists with that seed/account pair", isSlash)
return
user = {"seed_num": seedNum, "account_num": accountNum, "scholar_addr": roninAddr}
key, address = await UtilBot.getKeyForUser(user)
if key is None or address is None:
await Common.handleResponse(message, "Mismatch detected between given wallet address and seed/account indices, or scholar not found. Please try again with the correct wallet information.", isSlash)
return
# confirm with react
embed = discord.Embed(title="Add Scholar Confirmation", description=f"Confirming addition of scholar {name}/{discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordUID}")
embed.add_field(name=":bar_chart: Scholar Share", value=f"{round(scholarShare * 100, 2)}%")
embed.add_field(name="Seed", value=f"{seedNum}")
embed.add_field(name="Account", value=f"{accountNum}")
embed.add_field(name="Address", value=f"{roninAddr}")
if payoutAddress != "":
embed.add_field(name="Payout Address", value=f"{payoutAddress}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# add scholar to DB
msg = f"<@{discordId}>: \n"
res = await DB.addScholar(discordUID, name, seedNum, accountNum, roninAddr, scholarShare)
msg += res['msg'] + "\n"
if payoutAddress != "":
res2 = await DB.updateScholarAddress(discordUID, payoutAddress)
msg += res2['msg']
await confMsg.reply(content=msg)
# Revoke a scholar's scholar status
async def removeScholar(message, args, discordId, isSlash=False):
authorID = message.author.id
if not await DB.isManager(authorID):
await Common.handleResponse(message, "You must be a manager to use this command", isSlash)
return
if len(args) < 2:
await Common.handleResponse(message, "Please specify: discordUID", isSlash)
return
discordUID = args[1]
name = await Common.getNameFromDiscordID(discordUID)
# confirm with react
embed = discord.Embed(title="Remove Scholar Confirmation", description=f"Confirming removal of scholar {discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordUID}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# remove scholar from DB
res = await DB.removeScholar(discordUID)
await confMsg.reply(content=f"<@{discordId}>: " + res['msg'])
# Update a scholar's payout share
async def updateScholarShare(message, args, discordId, isSlash=False):
authorID = message.author.id
if not await DB.isManager(authorID):
await Common.handleResponse(message, "You must be a manager to use this command", isSlash)
return
if len(args) < 3:
await Common.handleResponse(message, "Please specify: discordUID scholarShare", isSlash)
return
if not args[1].isnumeric() or not Common.isFloat(args[2]):
await Common.handleResponse(message, "Please ensure your inputs are numbers", isSlash)
return
discordUID = args[1]
scholarShare = round(float(args[2]), 3)
name = await Common.getNameFromDiscordID(discordUID)
if scholarShare < 0.01 or scholarShare > 1.0:
await Common.handleResponse(message, "Please ensure your scholar share is between 0.01 and 1.00", isSlash)
return
res = await DB.getDiscordID(discordUID)
user = res["rows"]
if user is None or int(user["is_scholar"]) == 0:
await Common.handleResponse(message, "Did not find a scholar with this discord ID", isSlash)
return
oldShare = float(user["share"])
change = float(scholarShare) - oldShare
if change == 0.0:
await Common.handleResponse(message, "This is not a change, please specify a new share", isSlash)
return
# confirm with react
embed = discord.Embed(title="Update Scholar Share Confirmation", description=f"Confirming update for scholar {discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordUID}")
if change > 0.0:
embed.add_field(name="Change Type", value="Promotion")
else:
embed.add_field(name="Change Type", value="Demotion")
embed.add_field(name="Old Share", value=f"{round(oldShare * 100, 2)}%")
embed.add_field(name="New Share", value=f"{round(scholarShare * 100, 2)}%")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# update scholar share in DB
res = await DB.updateScholarShare(discordUID, scholarShare)
await confMsg.reply(content=f"<@{discordId}>: " + res['msg'])
# Update a scholar's login info
async def updateScholarLogin(message, args, discordId, isSlash=False):
authorID = message.author.id
if not await DB.isManager(authorID):
await Common.handleResponse(message, "You must be a manager to use this command", isSlash)
return
if len(args) < 5:
await Common.handleResponse(message, "Please specify: discordUID address email password", isSlash)
return
discordUID = args[1]
scholarAddr = args[2].replace("ronin:", "0x")
email = args[3]
password = args[4]
name = await Common.getNameFromDiscordID(discordUID)
res = await DB.getDiscordID(discordUID)
user = res["rows"]
if user is None or (user is not None and int(user["is_scholar"]) == 0):
await Common.handleResponse(message, "Did not find a scholar with this discord ID", isSlash)
return
# confirm with react
embed = discord.Embed(title="Update Scholar Login Info", description=f"Confirming update for scholar {discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordUID}")
embed.add_field(name=":house: Scholar Account Address", value=f"{scholarAddr}")
embed.add_field(name=":email: Scholar Account Email", value=f"{email}")
embed.add_field(name=":man_technologist: Scholar Account Password", value=f"{password}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# update scholar login in DB
res = await DB.updateScholarLogin(discordUID, scholarAddr, email, password)
await confMsg.reply(content=f"<@{discordId}>: " + res['msg'])
async def updateScholarAddress(message, args, isManager, discordId, isSlash=False):
authorID = message.author.id
if len(args) < 2:
await Common.handleResponse(message, f"Please specify: {prefix}payoutAddress", isSlash)
return
if len(args) > 2 and args[2].isnumeric() and isManager:
discordId = int(args[2])
payoutAddr = args[1].replace("ronin:", "0x").strip()
name = await Common.getNameFromDiscordID(discordId)
if not payoutAddr.startswith("ronin:") and not payoutAddr.startswith("0x"):
await Common.handleResponse(message, "Please ensure the payout address starts with ronin: or 0x", isSlash)
return
if not Web3.isAddress(payoutAddr):
await Common.handleResponse(message, "That does not seem to be a valid Ronin address. Please double check it and try again.", isSlash)
return
res = await DB.getDiscordID(discordId)
user = res["rows"]
if user is None or user["is_scholar"] is None or int(user["is_scholar"]) == 0:
await Common.handleResponse(message, "Did not find a scholar with this discord ID", isSlash)
return
marketName = await UtilBot.getMarketplaceProfile(payoutAddr)
if (Common.requireNaming and (marketName is None or Common.requiredName.lower() not in marketName.lower())) and (len(args) < 4 or not isManager or args[3] != "Force"):
await Common.handleResponse(message, f"The marketplace account of this payout address does not contain the requirement of: {Common.requiredName}", isSlash)
return
oldAddr = user["payout_addr"]
# confirm with react
embed = discord.Embed(title="Update Scholar Payout Confirmation", description=f"Confirming update for scholar {discordId}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":id: Scholar Discord ID", value=f"{discordId}")
embed.add_field(name="Note!", value="Please check the new address carefully!")
embed.add_field(name="Old Address", value=f"{oldAddr}")
embed.add_field(name="New Address", value=f"{payoutAddr}")
embed.add_field(name="Marketplace Name", value=f"{marketName}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# update scholar address in DB
res = await DB.updateScholarAddress(discordId, payoutAddr)
await confMsg.reply(content=f"<@{authorID}>: " + res['msg'])
# Give a user manager privileges
async def addManager(message, args, isSlash=False):
authorID = message.author.id
if not await DB.isOwner(authorID):
await Common.handleResponse(message, "You must be the owner to use this command", isSlash)
return
if len(args) < 2:
await Common.handleResponse(message, "Please specify: discordUID", isSlash)
return
discordUID = args[1]
name = await Common.getNameFromDiscordID(discordUID)
# confirm with react
embed = discord.Embed(title="Add Manager Confirmation", description=f"Confirming adding Manager {discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Manager Name", value=f"{name}")
embed.add_field(name=":id: Manager Discord ID", value=f"{discordUID}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# add manager to DB
res = await DB.addManager(discordUID, name)
if res is None:
confMsg.reply(content="Experienced unusual error, please check logs.")
return
await confMsg.reply(content=f"<@{authorID}>: " + res['msg'])
# Revoke a user's manager privileges
async def removeManager(message, args, isSlash=False):
authorID = message.author.id
if not await DB.isOwner(authorID):
await Common.handleResponse(message, "You must be the owner to use this command", isSlash)
return
if len(args) < 2:
await Common.handleResponse(message, "Please specify: discordUID", isSlash)
return
discordUID = args[1]
name = await Common.getNameFromDiscordID(discordUID)
# confirm with react
embed = discord.Embed(title="Remove Manager Confirmation", description=f"Confirming removing Manager {discordUID}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Manager Name", value=f"{name}")
embed.add_field(name=":id: Manager Discord ID", value=f"{discordUID}")
embed.set_footer(text="Click \N{White Heavy Check Mark} to confirm.")
confMsg, conf = await processConfirmationAuthor(message, embed, 60)
if conf is None:
# timeout
await confMsg.reply(content="You did not confirm within the timeout period, canceling!")
return
elif conf:
# confirmed
pass
else:
# denied/error
await confMsg.reply(content="Canceling the request!")
return
# remove manager from DB
res = await DB.removeManager(discordUID)
await confMsg.reply(content=f"<@{authorID}>: " + res['msg'])
# Command to output a summary of user data
async def membershipCommand(message, isSlash=False):
res = await DB.getMembershipReport()
name = await Common.getNameFromDiscordID(Common.ownerID)
embed = discord.Embed(title="Program Membership Report", description=f"Membership report for {Common.programName}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Owner Name", value=f"{name}")
embed.add_field(name="Owner Count", value=f"{res['owner']}")
embed.add_field(name="Manager Count", value=f"{res['managers']}")
embed.add_field(name="Scholar Count", value=f"{res['scholars']}")
embed.add_field(name="No Role Count", value=f"{res['noRole']}")
embed.add_field(name="Total Users", value=f"{res['total']}")
if isSlash:
await message.edit(embed=embed)
else:
await message.reply(embed=embed)
# Helper to produce a loading bar
def getLoadingContent(complete, total):
if massPayoutGlobal["txs"] is not None:
scholars = massPayoutGlobal["scholarSLP"]
manager = massPayoutGlobal["managerSLP"]
devs = massPayoutGlobal["devSLP"]
msg = 'Mass Payout Progress\n\n'
msg += f"Paid to scholars: {scholars}\n"
msg += f"Paid to manager: {manager}\n"
msg += f"Paid to devs: {devs}\n"
else:
msg = 'Mass Payout Progress\n'
msg += '\n['
percent = (float(complete) / float(total)) * 100.0
for i in range(1, 11):
if i * 10 <= percent < (i + 1) * 10:
msg += ':rocket:'
elif percent > i * 10:
msg += ':cloud:'
else:
msg += ':black_large_square:'
msg += ':full_moon:] ({:.2f}%, {}/{})'.format(percent, complete, total)
return msg
# Helper to live update a loading bar
massPayoutGlobal = {"counter": 0, "total": 0, "devSLP": 0, "managerSLP": 0, "scholarSLP": 0, "txs": None}
async def asyncLoadingUpdate(message):
global massPayoutGlobal
total = massPayoutGlobal["total"]
lastCount = 0
while massPayoutGlobal["counter"] <= massPayoutGlobal["total"]:
try:
if massPayoutGlobal["counter"] == lastCount:
await asyncio.sleep(15)
continue
await client.wait_until_ready()
complete = massPayoutGlobal["counter"]
lastCount = complete
scholars = massPayoutGlobal["scholarSLP"]
manager = massPayoutGlobal["managerSLP"]
devs = massPayoutGlobal["devSLP"]
msg = 'Mass Payout Progress\n\n'
msg += f"Paid to scholars: {scholars}\n"
msg += f"Paid to manager: {manager}\n"
msg += f"Paid to devs: {devs}\n"
msg += '\n['
percent = (float(complete) / float(total)) * 100.0
for i in range(1, 11):
if i * 10 <= percent < (i + 1) * 10:
msg += ':rocket:'
elif percent > i * 10:
msg += ':cloud:'
else:
msg += ':black_large_square:'
msg += ':full_moon:] ({:.2f}%, {}/{})'.format(percent, complete, total)
logger.info("Updating progress/tracker message in discord")
await message.edit(content=msg)
if massPayoutGlobal["counter"] == massPayoutGlobal["total"]:
logger.success("Final payout thread completed")
break
await asyncio.sleep(10)
except Exception as e:
logger.warning("Failed to update the mass payout log message, shouldn't be an issue, happens sometimes")
# logger.error(e)
await asyncio.sleep(10)
pass
# Wrapper to multi-call payouts
async def massPayoutWrapper(key, address, scholarAddress, ownerRonin, scholarShare, d, discordId, name):
global massPayoutGlobal
try:
addresses = [scholarAddress, ownerRonin]
percents = [scholarShare, (1 - (d + scholarShare))]
res = await ClaimSLP.slpClaiming(key, address, addresses, percents, d)
# res = await ClaimSLP.slpClaiming(key, address, scholarAddress, ownerRonin, scholarShare, d)
except Exception as e:
logger.error(f"Exception thrown during claiming for {address}/{name}")
logger.error(e)
res = None
if res is None or isinstance(res, int) or isinstance(res, Exception):
logger.warning(f"Claim returned nothing for {address}/{name}")
massPayoutGlobal["counter"] += 1
return res
if "scholarTx" in res and "scholarAmount" in res and res["scholarAmount"] > 0:
if res["scholarTx"] is not None:
massPayoutGlobal["scholarSLP"] += res["scholarAmount"]
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Scholar", scholarAddress, res["scholarAmount"], "SUCCESS", res["scholarTx"]]
else:
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Scholar", scholarAddress, res["scholarAmount"], "FAILURE", None]
if "ownerTx" in res and "ownerAmount" in res and res["ownerAmount"] > 0:
if res["ownerTx"] is not None:
massPayoutGlobal["managerSLP"] += res["ownerAmount"]
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Owner", ownerRonin, res["ownerAmount"], "SUCCESS", res["ownerTx"]]
else:
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Owner", ownerRonin, res["ownerAmount"], "FAILURE", None]
if "devTx" in res and "devAmount" in res and res["devAmount"] > 0:
if res["devTx"] is not None:
massPayoutGlobal["devSLP"] += res["devAmount"]
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Devs", "0xc381c963ec026572ea82d18dacf49a1fde4a72dc", res["devAmount"], "SUCCESS", res["devTx"]]
else:
massPayoutGlobal["txs"].loc[len(massPayoutGlobal["txs"].index)] = [discordId, name, address, "Devs", "0xc381c963ec026572ea82d18dacf49a1fde4a72dc", res["devAmount"], "FAILURE", None]
# DM scholar
try:
devTx = res["devTx"]
ownerTx = res["ownerTx"]
scholarTx = res["scholarTx"]
devAmt = res["devAmount"]
ownerAmt = res["ownerAmount"]
scholarAmt = res["scholarAmount"]
totalAmt = res["totalAmount"]
claimTx = res["claimTx"]
if not dmPayoutsToScholars or claimTx is None or totalAmt == 0:
massPayoutGlobal["counter"] += 1
return res
roninTx = "https://explorer.roninchain.com/tx/"
roninAddr = "https://explorer.roninchain.com/address/"
embed2 = discord.Embed(title="Individual Scholar Payout Results", description=f"Data regarding the payout for {discordId}/{name}",
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
failedSend = ""
if scholarTx is not None:
embed2.add_field(name="SLP Paid to Scholar", value=f"[{scholarAmt}]({roninTx}{scholarTx})")
else:
failedSend += f"Scholar ({scholarAmt}), "
if devTx is not None:
embed2.add_field(name="SLP Donated to Devs", value=f"[{devAmt}]({roninTx}{devTx})")
elif devAmt > 0:
failedSend += f"Devs ({devAmt}), "
if ownerTx is not None:
embed2.add_field(name="SLP Paid to Manager", value=f"[{ownerAmt}]({roninTx}{ownerTx})")
else:
failedSend += f"Owner ({ownerAmt})"
embed2.add_field(name="Total SLP Farmed", value=f"[{totalAmt}]({roninTx}{claimTx})")
embed2.add_field(name="Scholar Share Paid To", value=f"[{scholarAddress}]({roninAddr}{scholarAddress})")
if failedSend != "":
embed2.add_field(name="Possible Failures", value=f"{failedSend}")
logger.info(f"DMing payout info to scholar {discordId}/{name}")
user = await Common.client.fetch_user(int(discordId))
if user is not None:
tm = int(time.time())
await user.send(content=f"<t:{tm}:f> Payout Info", embed=embed2)
else:
logger.error(f"Failed to DM payout info to scholar {discordId}/{name}")
except Exception as e:
logger.error(f"Failed to DM scholar {discordId}/{name}")
logger.error(e)
massPayoutGlobal["counter"] += 1
return res
# Command for an individual scholar payout
async def payoutCommand(message, args, isManager, discordId, isSlash=False):
authorID = message.author.id
mp = await DB.getProperty("massPay")
if not mp["success"]:
await Common.handleResponse(message, "Failed to query database for massPay property", isSlash)
return
if not isManager and mp["rows"] is not None and (mp["rows"]["realVal"] is None or int(mp["rows"]["realVal"]) != 0):
await Common.handleResponse(message, "Individual payouts are disabled. Ask your manager to run a mass payout or to enable individual payouts.", isSlash)
return
res = await DB.getProperty("d")
if not res["success"]: