-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2188 lines (1591 loc) · 92.7 KB
/
main.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
# ---------- time imports -----------
import asyncio
import calendar
from datetime import datetime, timedelta
import datetime
import functools
import io
import traceback
import typing
import os
from bson import ObjectId
import time
import json
from discord.ext import tasks
import random
# ----------- discord imports ---------
import discord
from discord import app_commands
from typing import Literal
# ----------- json imports ------------
import json
# --------- web imports ---------
import requests
from Helper_Functions.Scheduler import startup_sched
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from motor.motor_asyncio import AsyncIOMotorClient
# --------- other file imports ---------
from Web_Interaction.loopty_loop import master_loop
from Web_Interaction.curator import single_run
from Web_Interaction.scraping import single_scrape, get_image, single_scrape_v2
from Helper_Functions.create_embed import getEmbed
from Helper_Functions.roll_string import get_roll_string
from Helper_Functions.buttons import get_buttons
from Helper_Functions.update import update_p
from Web_Interaction.Screenshot import Screenshot
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from PIL import Image
from Helper_Functions.mongo_silly import get_mongo, dump_mongo, get_unix, collection #TODO: i dont need this anymore but too lazy to figure it out
from Helper_Functions.mongo_silly import *
from Helper_Functions.mongo_silly import _in_ce
from Helper_Functions.os import restart, add_to_windows_startup
from Helper_Functions.spreadsheet import csv_conversion, csv_conversion_roles
# ---------- command imports --------------
from Commands.Rolls.roll_solo import solo_command
from Commands.Rolls.roll_co_op import co_op_command
# --------------------------------------------------- ok back to the normal bot ----------------------------------------------
intents = discord.Intents.default()
intents.reactions = True
intents.members = True
intents.guilds = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
intents.message_content = True
with open('Jasons/help_embed_data.json') as f:
test = json.load(f)
# Grab information from json file
with open('Jasons/secret_info.json') as f :
localJSONData = json.load(f)
if _in_ce:
discord_token = localJSONData['discord_token']
guild_ID = localJSONData['ce_guild_ID']
else :
discord_token = localJSONData['third_discord_token']
guild_ID = localJSONData['test_guild_ID']
# test function that never really worked lol
async def aaaa_auto(interaction : discord.Interaction, current:str) -> typing.List[app_commands.Choice[str]]:
data = []
database_name = await get_mongo("name")
for game in database_name:
name : str = database_name[game]['Name']
if current.lower() in name.lower() :
data.append(app_commands.Choice(name=name,value=name))
if len(data) >= 25 : break
return data[0:25]
@tree.command(name="ce-game", description="Find information on any CE game!", guild=discord.Object(id=guild_ID))
@app_commands.autocomplete(item=aaaa_auto)
async def aaaaa(interaction : discord.Interaction, item : str):
await interaction.response.defer(ephemeral=True)
await interaction.followup.send(f"You chose {item} (testing still in progress!)")
return
"""
Information to return
- Category
- Tier
- Points
- Number of objectives
- Completion rates
- Link to CE
- Link to Steam
"""
"""
Things we'd like to see in feedback
- filter bs responses
- take getting over it, 500 clears
- half want to give feedback
- the problem with this game
"""
# pull database name
database_name = await get_mongo('name')
# get the game id, throw error if not found
game_id = None
for i in database_name:
if database_name[i]['Name'] == item : game_id = i
if game_id == None : return await interaction.followup.send("A strange error has occurred. Please ping andy :(")
game_name = item
# pull api page
api_data = get_api('game', game_id)
# set up the Embed object
embed = discord.Embed(
title=game_name,
color=0x000000,
description="",
timestamp=datetime.datetime.now()
)
embed.add_field(name="Site Status", value=f"{database_name[game_id]['Tier']}{database_name[game_id]['Genre']}"
+ f"\nTotal Completions: {database_name[game_id]['Total Completions']}")
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ----------------------------------------------- ---------------------------------------------------- #
# ----------------------------------------------- HELP COMMAND ---------------------------------------------------- #
# ----------------------------------------------- ---------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
@tree.command(name="help", description="help", guild=discord.Object(id=guild_ID))
async def help(interaction : discord.Interaction) :
await interaction.response.defer(ephemeral=True)
page_data = json.loads(open("Jasons/help_embed_data.json").read())
basic_options = page_data['Options']
selections = []
roll_options = page_data['Rollsy']
rolls = []
admin_options = page_data['Admin']
admin = []
mod_role = discord.utils.get(interaction.guild.roles, name = "Mod")
admin_role = discord.utils.get(interaction.guild.roles, name = "Admin")
embed = discord.Embed(
title="Help",
colour= 0x036ffc,
timestamp=datetime.datetime.now(),
description="Here you can use the drop down menu to learn about various features CE Assistant can help you with."
)
embed.set_thumbnail(url=ce_mountain_icon)
for option in basic_options:
if option == 'Admin Options' and (not mod_role in interaction.user.roles and not admin_role in interaction.user.roles and 413427677522034727 != interaction.user.id):
continue
selections.append(discord.SelectOption(
label=basic_options[option]['Name'],
emoji=basic_options[option]['Emoji'],
description=basic_options[option]['Description']))
for option in roll_options:
rolls.append(discord.SelectOption(
label=roll_options[option]['Name'],
emoji=roll_options[option]['Emoji'],
description=roll_options[option]['Description']))
for option in admin_options:
admin.append(discord.SelectOption(
label=admin_options[option]['Name'],
emoji=admin_options[option]['Emoji'],
description=admin_options[option]['Description']))
class HelpSelect(discord.ui.Select):
def __init__(self, select, message="Select an option...", row=1):
options=select
super().__init__(placeholder=message, max_values=1,min_values=1,options=options, row=row)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
embed = self.get_embed()
if self.values[0] == 'Rolls' or self.values[0] in list(roll_options.keys()):
await interaction.followup.edit_message(embed = embed, view=HelpSelectView(
menu=rolls,
message="Select an option...",
message_2="Select a roll option..."),
message_id = interaction.message.id)
elif self.values[0] == 'Admin Options' or self.values[0] in list(admin_options.keys()):
await interaction.followup.edit_message(embed = embed, view=HelpSelectView(
menu=admin,
message="Select an option...",
message_2="Select an admin option..."),
message_id = interaction.message.id)
else:
await interaction.followup.edit_message(embed=embed, view=HelpSelectView(message="Select an option..."), message_id = interaction.message.id)
def get_embed(self):
if self.values[0] in list(roll_options.keys()):
dict = roll_options
elif self.values[0] in list(admin_options.keys()):
dict = admin_options
else:
dict = basic_options
embed = discord.Embed(
title=dict[self.values[0]]['Name'],
colour= 0x036ffc,
timestamp=datetime.datetime.now(),
description=dict[self.values[0]]['Content']
)
embed.set_thumbnail(url=ce_mountain_icon)
return embed
class HelpSelectView(discord.ui.View):
def __init__(self, *, timeout = 180, menu="", message="Select an option", message_2="Select an option"):
super().__init__(timeout=timeout)
self.add_item(HelpSelect(selections, message, 1))
if menu != "" :
self.add_item(HelpSelect(menu, message_2, 2))
"""async def on_timeout(self):
self.clear_items()"""
return await interaction.followup.send(embed=embed, view=HelpSelectView(), ephemeral=True)
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# --------------------------------------------------- SOLO ROLL COMMAND ------------------------------------------------------------ #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
events_solo = Literal["One Hell of a Day", "One Hell of a Week", "One Hell of a Month", "Two Week T2 Streak",
"Two 'Two Week T2 Streak' Streak", "Never Lucky", "Triple Threat", "Let Fate Decide", "Fourward Thinking",
"Russian Roulette"]
@tree.command(name="solo-roll", description="Participate in Challenge Enthusiast roll events!", guild=discord.Object(id=guild_ID))
@app_commands.describe(event="The event you'd like to participate in")
async def roll_solo_command(interaction : discord.Interaction, event: events_solo) :
await interaction.response.defer()
# run 1/100 chance of pinging jarvis
log_channel = client.get_channel(log_id)
await solo_command(interaction, event, reroll = False, collection=collection, log_channel=log_channel)
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# -------------------------------------------------- CO-OP ROLL COMMAND ------------------------------------------------------------ #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
events_co_op = Literal["Destiny Alignment", "Soul Mates", "Teamwork Makes the Dream Work",
"Winner Takes All", "Game Theory"]
@tree.command(name="co-op-roll", description="Participate in Challenge Enthusiast Co-Op or PvP roll events!", guild=discord.Object(id=guild_ID))
@app_commands.describe(event="The event you'd like to participate in")
@app_commands.describe(partner="The user you'd like to enter the roll with")
async def roll_co_op_command(interaction : discord.Interaction, event : events_co_op, partner : discord.User) :
await interaction.response.defer()
await co_op_command(interaction, event, partner, reroll = False, collection=collection)
events_total = Literal["One Hell of a Day", "One Hell of a Week", "One Hell of a Month", "Two Week T2 Streak",
"Two 'Two Week T2 Streak' Streak", "Never Lucky", "Triple Threat", "Let Fate Decide", "Fourward Thinking",
"Russian Roulette", "Destiny Alignment", "Soul Mates", "Teamwork Makes the Dream Work",
"Winner Takes All", "Game Theory"]
"""List of all events."""
@tree.command(name="force-add", description="Force add a roll completion to any user.", guild=discord.Object(id=guild_ID))
async def force_add(interaction: discord.Interaction, user: discord.Member, roll_event : events_total):
await interaction.response.defer()
database_user = await get_mongo('user')
ce_id = await get_ce_id(user.id)
if ce_id == None : return await interaction.followup.send(f"<@{user.id}> is not registered in the CE Assistant database. Please have them use /register.")
database_user[ce_id]['Completed Rolls'].append({"Event Name" : roll_event})
dump = await dump_mongo('user', database_user)
return await interaction.followup.send(f"{roll_event} has been added to <@{user.id}>'s Completed Rolls array.")
"""
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# -------------------------------------------------------- CHECK_ROLLS COMMAND ----------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
@tree.command(name="check-rolls", description="Check the active rolls of anyone on the server", guild=discord.Object(id=guild_ID))
@app_commands.describe(user="The user you'd like to check the rolls of")
async def checkRolls(interaction : discord.Interaction, user: discord.Member=None) :
# defer the message
print('balls')
await interaction.response.defer()
overflow = False
# this is me trying to fix it but i will deal with this later
if user is None : user = interaction.user
# get mongo data
database_user = await get_mongo('user')
database_name = await get_mongo('name')
ce_id = ""
for u in database_user:
elif database_user[u]['Discord ID'] == user.id:
ce_id = u
break
if ce_id == "" : return await interaction.followup.send("This user is not registered in the CE Assistant database. Please make sure they use /register!")
return await interaction.followup.send("Feature under construction!! Coming soon.")
# if no user is provided default to sender
selfy = False
if user is None :
selfy = True
user = interaction.user
# get mongo data
userInfo = await get_mongo('user')
database_name_info = await get_mongo('name')
# iterate through the json file until you find the
# designated user
steam_user_name = await get_ce_id(user.id)
if(steam_user_name == None) :
if selfy: return await interaction.followup.send("You are not registered in the CE Assistant database. Please use `/register`!")
else: return await interaction.followup.send("This user is not registered in the CE Assistant database. Please make sure they use `/register`!")
#print(steam_user_name)
current_roll_str = get_roll_string(userInfo, steam_user_name, database_name_info, user, 'Current Rolls')
completed_roll_str = get_roll_string(userInfo, steam_user_name, database_name_info, user, 'Completed Rolls')
if len(current_roll_str) > 1020 :
current_roll_str = current_roll_str[:1020]
overflow = True
if len(completed_roll_str) > 1020 :
completed_roll_str = completed_roll_str[:1020]
overflow = True
# make the embed that you're going to send
embed = discord.Embed(colour=0x000000, timestamp=datetime.datetime.now())
embed.add_field(name="User", value = "<@" + str(user.id) + "> " + str(icons[userInfo[steam_user_name]['Rank']]), inline=True)
embed.add_field(name="Current Rolls", value=current_roll_str, inline=False)
embed.add_field(name="Completed Rolls", value=completed_roll_str, inline=False)
if overflow:
embed.add_field(name="Overflow Error!", value="If this doesn't look right, please DM me <@413427677522034727>. This will be fixed in v1.1.", inline=False)
embed.set_thumbnail(url=user.avatar.url)
embed.set_footer(text="CE Assistant",
icon_url=final_ce_icon)
# send the embed
await interaction.followup.send(embed=embed)
del current_roll_str
del completed_roll_str
del embed
del database_name_info
del user
"""
def checkRollsEmbed(user : discord.Member, database_name, database_user, ce_id : str) -> discord.Embed :
"""Returns the embed for the /check-rolls command."""
# iterate through the json file until you find the
# designated user
overflow = False
steam_user_name = ce_id
current_roll_str = get_roll_string(database_user, steam_user_name, database_name, user, 'Current Rolls')
completed_roll_str = get_roll_string(database_user, steam_user_name, database_name, user, 'Completed Rolls')
if len(current_roll_str) > 1020 :
current_roll_str = current_roll_str[:1020]
overflow = True
if len(completed_roll_str) > 1020 :
completed_roll_str = completed_roll_str[:1020]
overflow = True
# make the embed that you're going to send
embed = discord.Embed(colour=0xff9494, timestamp=datetime.datetime.now())
embed.add_field(name="User", value = "<@" + str(user.id) + "> " + str(icons[database_user[steam_user_name]['Rank']]), inline=True)
embed.add_field(name="Current Rolls", value=current_roll_str, inline=False)
embed.add_field(name="Completed Rolls", value=completed_roll_str, inline=False)
if overflow:
embed.add_field(name="Overflow Error!", value="If this doesn't look right, please DM me <@413427677522034727>. This will be fixed in v1.1.", inline=False)
embed.set_thumbnail(url=user.avatar.url)
embed.set_footer(text="CE Assistant",
icon_url=final_ce_icon)
return embed
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ----------------------------------------------------------- THREADING ------------------------------------------------------------ #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
def to_thread(func: typing.Callable) -> typing.Coroutine:
@functools.wraps(func)
async def wrapper(*args, **kwargs):
return await asyncio.to_thread(func, *args, **kwargs)
return wrapper
"""
@tasks.loop(time=datetime.time(hour=0, minute=20, tzinfo=datetime.timezone.utc))
async def check_roll_status():
print('it ran omg it actually ran')
log_channel = client.get_channel(log_id)
log_channel.send("check_roll_status has begun!!")
# get databases
database_user = await get_mongo('user')
database_name = await get_mongo('name')
# create a variable that holds all the messages that need to be sent
all_returns = []
# go through each user in database user. if they have any cooldowns or current rolls.... update their profiles.
for user in database_user:
# if their current rolls are empty and their cooldowns are empty keep checking
if(database_user[user]['Current Rolls'] == [] and database_user[user]['Cooldowns'] == {}) : continue
else:
# update their profile.
returns = update_p(database_user[user]['Discord ID'], "", database_user, database_name)
# update database_user.
database_user = returns[0]
returns[0] = "NEW USER: " + str(database_user[user]['Discord ID'])
# add all returned values to the array except database_user. that has been dealt with.
for i in range(0, len(returns)):
all_returns.append(returns[i])
# make the returns array empty.
returns = []
# update the databases
dump = await dump_mongo("user", database_user)
# initialize the variables ##################################################################################################################
#
casino_channel = client.get_channel(casino_id) #
#
# rank silliness #
ranks = ["E Rank", "D Rank", "C Rank", "B Rank", "A Rank", "S Rank", "SS Rank", "SSS Rank", "EX Rank"] #
rankroles = [] #
ex_rank_role = discord.utils.get(correct_guild_2.roles, name = "EX Rank") #
sss_rank_role = discord.utils.get(correct_guild_2.roles, name = "SSS Rank") #
ss_rank_role = discord.utils.get(correct_guild_2.roles, name = "SS Rank") #
s_rank_role = discord.utils.get(correct_guild_2.roles, name = "S Rank") #
a_rank_role = discord.utils.get(correct_guild_2.roles, name = "A Rank") #
b_rank_role = discord.utils.get(correct_guild_2.roles, name = "B Rank") #
c_rank_role = discord.utils.get(correct_guild_2.roles, name = "C Rank") #
d_rank_role = discord.utils.get(correct_guild_2.roles, name = "D Rank") #
e_rank_role = discord.utils.get(correct_guild_2.roles, name = "E Rank") #
rankroles = [a_rank_role, ex_rank_role, sss_rank_role, ss_rank_role, s_rank_role, b_rank_role, c_rank_role, d_rank_role, e_rank_role] #
correct_guild = discord.Object(id=guild_ID)
correct_guild_2 = client.get_guild(id=guild_ID)
discord.Guild.roles
#############################################################################################################################################
for return_value in all_returns :
current_user = ""
if return_value[:9:] == "NEW USER: ":
current_user_id = int(return_value[10::])
current_user = correct_guild_2.get_member(current_user_id)
# you've reached the end
# if return_value == "Updated" :
# # Create confirmation embed
# embed = discord.Embed(
# title="Updated!",
# color=0x000000,
# timestamp=datetime.datetime.now()
# )
# embed.add_field(name="Information", value=f"Your information has been updated in the CE Assistant database.")
# embed.set_author(name="Challenge Enthusiasts", url="https://example.com")
# embed.set_footer(text="CE Assistant",
# icon_url=final_ce_icon)
# embed.set_thumbnail(url=interaction.user.avatar)
# change the rank
# TODO: maybe get folkius to give theron points to test this out?
# TODO: given that i have no way of knowing if it works rn
elif return_value[:5:] == "rank:" :
for rankrole in rankroles :
if rankrole in current_user.roles :
role = rankrole
break
if role.name == return_value[6::] : continue
else :
for rankrole in rankroles :
if rankrole in current_user.roles : await current_user.remove_roles(rankrole)
if rankrole.name == return_value[6::] : await current_user.add_roles(rankrole)
# log channel shit
elif return_value[:4:] == "log:" :
await log_channel.send(return_value[5::])
# casino channel shit
elif return_value[:7:] == "casino:":
await casino_channel.send(return_value[8::])
# else
else :
await log_channel.send("BOT ERROR: recieved unrecognized update code: \n'{}'".format(return_value))
await log_channel.send("holy fucking shit the once-a-day actually ran???")
# delete all variables (mmmmm...... my precious ram.... mmmmmmffgggggggg......)
del dump
del database_user
del database_name
del all_returns
del returns
"""
@tree.command(name='purge-roll', description="Remove a roll from a specific user (in the event of catastrophe)",
guild=discord.Object(id=guild_ID))
async def purge_roll(interaction : discord.Interaction, user : discord.User, roll_event : events_solo):
await interaction.response.defer()
# pull the database
database_user = await get_mongo('user')
# find the user
ce_id = await get_ce_id(user.id)
if ce_id == None:
return await interaction.followup.send("<@{}> is not registered in the CE Assistant database.".format(user.id))
if roll_event in database_user[ce_id]['Pending Rolls'] : del database_user[ce_id]['Pending Rolls'][roll_event]
if roll_event in database_user[ce_id]['Cooldowns'] : del database_user[ce_id]['Cooldowns'][roll_event]
await dump_mongo('user', database_user)
# find the roll
r_index = -1
for i, r in enumerate(database_user[ce_id]['Current Rolls']):
if r['Event Name'] == roll_event : r_index = i
if r_index == -1:
return await interaction.followup.send("<@{}> does not have {} in their Current Rolls array.".format(user.id, roll_event))
# user does exist and has the roll in their array
del database_user[ce_id]['Current Rolls'][r_index]
# dump the database
await dump_mongo('user', database_user)
# send message (dumbass!)
return await interaction.followup.send(f"{roll_event} was dropped from <@{user.id}>'s Current Rolls array.")
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# --------------------------------------------------------- SCRAPING --------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------------------- #
@to_thread
def scrape_thread_call(curator_count):
"""
Returns
--------
[`database_name`, `curator_count`, `database_tier`]
"""
return single_scrape_v2(curator_count)
"""
@tree.command(name="jaaaarviiiissssss", description="make daddy fix what he broke", guild=discord.Object(id=guild_ID))
async def jarvis(interaction : discord.Interaction):
general_channel = client.get_channel(639112509445505046)
await general_channel.send("<@687876105473884174> fix it")
"""
@tree.command(name="scrape", description="Force update every game without creating embeds. DO NOT RUN UNLESS NECESSARY.", guild=discord.Object(id=guild_ID))
async def scrape(interaction : discord.Interaction):
await interaction.response.send_message('scraping... (v2)')
curator_count = await get_mongo('curator')
objects = await scrape_thread_call(curator_count)
# dump the databases back onto mongoDB
dump1 = await dump_mongo('curator', objects[1]) #curator
dump2 = await dump_mongo('name', objects[0]) #name
dump3 = await dump_mongo('tier', objects[2]) #tier
await interaction.channel.send('scraped')
del dump3
del dump1
del dump2
del curator_count
del objects
# godspeed, get_times :pray:
"""
@tree.command(name="get_times", description="Prints out a table of times fifteen minutes apart in UTC", guild=discord.Object(id=guild_ID))
async def get_times(interaction):
await interaction.response.send_message('times...')
fin = "times = ['
for i in range(0, 24):
for j in range(0, 4):
fin += "\n datetime.time(hour={}, minute={}, tzinfo=utc),".format(i,j*15)
fin = fin[:-1:] + "\n]"
print(fin)
"""
class NewModal(discord.ui.Modal):
def __init__(self) :
super().__init__(title="My first Modal!")
name = discord.ui.TextInput(label="Peepo")
answer = discord.ui.TextInput(label="Response", style=discord.TextStyle.paragraph)
async def on_submit(self, interaction : discord.Interaction) :
await interaction.response.send_message(f'Thank you for your response, {self.name}!', ephemeral=False)
class RequestCEGame(discord.ui.Modal):
def __init__(self) :
super().__init__(title="Request CE Game...")
game_name = discord.ui.TextInput(label="Game Name", required=False, placeholder="Select a game name")
tier = discord.ui.TextInput(label="Tier", style=discord.TextStyle.short, min_length=1, max_length=1, required=False, placeholder="Select a tier number.")
max_points = discord.ui.TextInput(label="Min-Max Points", style=discord.TextStyle.short, required=False, placeholder="Please format as such: min-max, or 20-100", max_length=9)
genre = discord.ui.TextInput(label="Genre", style=discord.TextStyle.short, required=False, placeholder="Select a genre.", max_length=12)
owned = discord.ui.TextInput(label="Owned", style=discord.TextStyle.short, required=False, placeholder="Separate games by owned (\"true\") or not owned (\"false\").", max_length=5)
async def on_submit(self, interaction : discord.Interaction) :
# d efer
await interaction.response.defer()
# grab all submitted queries
game_name = str(self.game_name)
tier = str(self.tier)
points = str(self.max_points)
genre = str(self.genre)
owned = str(self.owned)
# format them correctly
if tier != "":
try:
tier = int(tier)
if tier > 7 : tier = "invalid"
elif tier < 1 : tier = "invalid"
except ValueError:
tier = "invalid"
if points != "":
splitter = points.find('-')
if splitter == -1 : points = "invalid"
try:
min_points = points[0:splitter]
max_points = points[splitter+1:]
min_points = int(min_points)
max_points = int(max_points)
if max_points < min_points : points = "invalid"
except ValueError:
points = "invalid"
if genre != "":
genre = genre.replace('-','').replace(' ','')
g_changed = False
for g in all_genres:
g_save = g
g = g.replace('-','').replace(' ','')
if g.lower() == genre.lower() :
genre = g_save
g_changed = True
break
if not g_changed : genre = "invalid"
if owned == "False" or owned == "false" or owned == "f" : owned = False
elif owned == "True" or owned == "true" or owned == "t" : owned = True
elif owned != "" : owned = "invalid"
# -------- all variables formatted. start grabbing -----------
if True:
description_str = ""
description_str += f"✅Game recieved: {game_name}.\n" if game_name != "" else "" #"🛑No game name recieved.\n"
if tier == "invalid" :
description_str += "⚠️Invalid tier recieved.\n"
tier = None
elif tier == "":
#description_str += "🛑No tier recieved.\n"
tier = None
else: description_str += f"✅Tier recieved: {icons['Tier {}'.format(tier)]}.\n"
if points == "" :
#description_str += "🛑No min-max points recieved.\n"
points = None
elif points == "invalid" :
description_str += "⚠️Invalid min-max syntax."
points = None
else : description_str += f"✅Min points recieved: {min_points} {icons['Points']}\n✅Max points recieved: {max_points} {icons['Points']}.\n"
if genre == "":
#description_str += "🛑No genre recieved.\n"
genre = None
elif genre == "invalid":
description_str += "⚠️Invalid genre recieved.\n"
genre = None
else: description_str += f"✅Genre recieved: {genre}{icons[genre]}.\n"
if owned == "" :
#description_str += "🛑No ownership query recieved.\n"
owned = None
elif owned == "invalid" :
description_str += "⚠️Invalid ownership (not \"true\" or \"false\").\n"
owned = None
else: description_str += f"✅Ownership recieved: {owned}"
database_name = await get_mongo('name')
database_user = await get_mongo('user')
game_list : list[str] = []
ce_id = get_ce_id_normal(interaction.user.id, database_user)
if ce_id == None and type(owned) == bool:
return await interaction.followup.send("You selected \"true\" or \"false\" for Owned, but you are not registered. Please use `/register` with the link to your CE page!")
elif game_name == "" and tier == None and points == None and genre == None and owned == None:
return await interaction.followup.send("You either left all the options blank or inputted only invalid answers. Please try again!")
for game_id in database_name:
valid = True
if game_name != "" and not game_name.lower() in database_name[game_id]['Name'].lower() : valid = False #database_name[game_id]['Name'].lower()[0:len(game_name)] == game_name.lower() : valid = False
if tier != None :
if tier == 6 or tier == 7:
total_points = 0
for obj_id in database_name[game_id]['Primary Objectives'] : total_points += database_name[game_id]['Primary Objectives'][obj_id]['Point Value']
if tier == 6 and (total_points < 500 or total_points >= 1000) : valid = False
elif tier == 7 and total_points < 1000 : valid = False
if not database_name[game_id]['Tier'] == f"Tier {tier}" and tier != 6 and tier != 7 : valid = False
if points != None:
total_points = 0
for obj_id in database_name[game_id]['Primary Objectives'] : total_points += database_name[game_id]['Primary Objectives'][obj_id]['Point Value']
if total_points < min_points or total_points > max_points : valid = False
if genre != None and not database_name[game_id]['Genre'] == genre : valid = False
if owned != None and not game_id in database_user[ce_id]['Owned Games'] : valid = False
if valid : game_list.append(game_id)
del database_user
list_strings : list[str] = []
for i in range(0, 25) :
list_strings.append("")
index = -1
for i, item in enumerate(game_list):
if(i % 10 == 0) : index += 1
if index > 24 : return await interaction.followup.send("Too many games! Please lower your search queries.")
list_strings[index] += f"[{database_name[item]['Name']}](https://cedb.me/game/{item})\n"
if len(game_list) == 0: return await interaction.followup.send("No games on CE fit the queries provided.")
embeds : list[discord.Embed] = []
for i in range(0, index+1) :
embed = discord.Embed(title="Requested games...", description=list_strings[i], timestamp=datetime.datetime.now(), color=0x000000)
embed.add_field(name="Parameters", value=description_str)
embed.set_author(name="Challenge Enthusiasts", url=f"https://cedb.me/user/{ce_id}", icon_url=final_ce_icon)
embed.set_footer(text=f"Page {i+1} of {index+1}")
embeds.append(embed)
view = discord.ui.View(timeout=600)
await get_buttons(view, embeds)
dice_emoji = await interaction.guild.fetch_emoji(1128844342732263464)
random_button = discord.ui.Button(emoji=dice_emoji)
async def random_callback(interaction : discord.Interaction) :
await interaction.response.defer(ephemeral=True)
database_name = await get_mongo('name')
r = random.choice(game_list)
r = f"Randomly selected: [{database_name[r]['Name']}](https://cedb.me/game/{r})"
del database_name
return await interaction.followup.send(r)
random_button.callback = random_callback
view.add_item(random_button)
try:
await interaction.followup.send(embed=embeds[0], view=view)
except:
await interaction.followup.send('Too many games!')
@tree.command(name='game-list', description='Get a list of games that meet certain queries!', guild=discord.Object(id=guild_ID))
async def testagain(interaction : discord.Interaction) :
await interaction.response.send_modal(RequestCEGame())
@tree.command(name="bounty", description="Adjust bounty points and/or bounty-related Roles!", guild=discord.Object(id=guild_ID))
@app_commands.describe(function="Whether you'd like to add points or remove them")
@app_commands.describe(user="The user you'd like to adjust the bounty points/roles of")
@app_commands.describe(points="The amount of points you'd like to add/remove")
async def bounty(interaction : discord.Interaction, user : discord.Member, function : Literal["add", "remove"], points : int):
await interaction.response.defer() # defer the message
# get dbU and ce-id
database_user = await get_mongo('user')
ce_id = await get_ce_id(user.id)
if ce_id == None : return await interaction.followup.send(f"<@{user.id}> is not registered in CE Assistant's database!")
# check if the user has bounty points already
if 'Bounty Points' not in database_user[ce_id] :
database_user[ce_id]['Bounty Points'] = 0
await dump_mongo('user', database_user)
database_user = await get_mongo('user')
# points removed
if function == "remove" :
if points > database_user[ce_id]['Bounty Points']:
return await interaction.followup.send(f"<@{user.id}> has {database_user[ce_id]['Bounty Points']} bounty points. You can't remove {points} bounty points!")
database_user[ce_id]['Bounty Points'] -= points
# points added
elif function == "add" :
database_user[ce_id]['Bounty Points'] += points
await dump_mongo('user', database_user)
return await interaction.followup.send(f"{points} have been {function}" + "d" if function == "remove" else "ed"
+ f" to <@{user.id}>'s Bounty Points for a total of {database_user[ce_id]['Bounty Points']}.")
@tree.command(name="user-data", description="Get CE Assistant's data on any user", guild=discord.Object(id=guild_ID))
async def getuserdata(interaction : discord.Interaction, user : discord.Member) :
await interaction.response.defer(ephemeral=True)
ce_id = await get_ce_id(user.id)
if ce_id == None : return await interaction.followup.send('user not in database')
database_user = await get_mongo('user')
f = json.dumps(database_user[ce_id]).encode('utf-8')
return await interaction.followup.send(file=discord.File(io.BytesIO(f), "data.json"))