-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpe_discord_api.py
More file actions
1600 lines (1110 loc) · 60.1 KB
/
pe_discord_api.py
File metadata and controls
1600 lines (1110 loc) · 60.1 KB
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
import asyncio
import time
import datetime
from math import *
from requests import TooManyRedirects
import pe_database
import pe_api
import pe_rss
import pe_image
import pe_plot
import pe_events
import pe_session
import pe_decorators
import pe_global_objects as pe_global
import phone_api
import itertools
import requests
import interactions_discord as inters
import discord
from discord import option
import glob
import os
import random
import re
import traceback
from rich.console import Console
from rich import inspect
from pe_global_objects import log
import sympy
from typing import Dict, List, Tuple, Any, Optional
console = Console(record = True)
bot: discord.Bot = pe_global.bot
async def major_update() -> bool:
# global REPEATS_SINCE_START
# global REPEATS_SUCCESSFUL_SINCE_START
pe_global.REPEATS_SINCE_START += 1
# SANITY CHECKS
website_active = pe_session.is_website_active()
session_alive = pe_session.is_connected()
if not website_active or not session_alive:
pe_session.refresh_tokens()
website_active = pe_session.is_website_active()
session_alive = pe_session.is_connected()
if not website_active:
log.error("Skipped major_update because website does not respond.")
await async_set_bot_status(3, "Website died")
return False
if not session_alive:
log.error("Skipped major_update because there is no active session.")
await async_set_bot_status(3, "Session died")
return False
# In the console
log.info(f"Starting repeat #{pe_global.REPEATS_SINCE_START}")
try:
await announce_rss()
except Exception as exc:
log.exception(exc)
# Getting the data required
try:
profiles = pe_api.update_process()
except Exception as exc:
console.log(exc, traceback.format_exc())
log.exception(exc)
await async_set_bot_status(3, "Unknown error")
return False
await async_set_bot_status([1, 2][not pe_api.LAST_REQUEST_SUCCESSFUL])
if profiles is None:
return False
# Not important, you can skip this explanation
# Only goal is to keep each profile in the database with a solve list that is the length of the number of problems
if pe_api.last_problem() != pe_api.last_problem_database():
log.info("[(-) New problem detected, adding one zero to everyone]")
m: pe_api.Member
for m in pe_api.Member.members():
m.push_basics_to_database()
log.info("[(+) Updated all members in the database]")
# event = pe_events.eventSoPE()
# event = pe_events.eventMonthly1()
messages_to_announce = pe_events.update_events_without_profiles()
await announce_messages(messages_to_announce)
if len(profiles) == 0:
return True
problems: List[pe_api.Problem] = pe_api.Problem.complete_list()
awards_specs = pe_api.get_awards_specs()
for profile in profiles:
member: pe_api.Member = profile["member"]
solves: List[pe_api.Solve] = profile["solves"]
awards = profile["awards"]
if member.private():
continue
for solve in solves:
problem: pe_api.Problem = solve.problem()
pe_api.push_solve_to_database(member, solve.problem())
for channel_id in pe_global.CHANNELS_TO_ANNOUNCE:
channel = pe_global.bot.get_channel(channel_id)
#decide what message to send depending on how many solvers there are
if int(problem.solves()) <= 3:
sending_message = pe_global.AWARDING_SENTENCES[problem.solves() - 1].format(member.username_ping(), problem.problem_id(), problem.name())
else:
sending_message = pe_global.AWARDING_SENTENCES[3].format(member.username_ping(), problem.problem_id(), problem.name(), problem.solves())
# add related emojis
# optional_stars = " 🌠" if not event.is_problem_solved(problem.problem_id) else ""
optional_bee = " ⚡" if problem.problem_id() == len(problems) else ""
optional_emojis = optional_bee
sending_message = sending_message + optional_emojis
await channel.send(sending_message, allowed_mentions = discord.AllowedMentions(users=False))
if member.solve_count() % 25 == 0:
if member.is_discord_linked():
await update_member_roles(member)
for channel_id in pe_global.SPECIAL_CHANNELS_TO_ANNOUNCE:
channel = bot.get_channel(channel_id)
sending_message = member.username_ping() + " has just reached level {0}, congratulations!"
sending_message = sending_message.format(member.solve_count() // 25)
await channel.send(sending_message, allowed_mentions = discord.AllowedMentions(users=False))
if member.is_discord_linked() and member.solve_count() == len(member.solve_array()):
await update_member_roles(member)
if awards is None:
continue
for part in [0, 1, 2]:
for award in awards[part]:
for channel_id in pe_global.SPECIAL_CHANNELS_TO_ANNOUNCE:
channel = bot.get_channel(channel_id)
award_name = awards_specs[part][award]
await channel.send(f"{member.username_ping()} got the award '{award_name}', congratulations!",
allowed_mentions = discord.AllowedMentions(users = False))
messages = pe_events.update_events(profiles)
await announce_messages(messages)
return True
@bot.event
async def on_ready():
# Global variables in order to modify them
# global REPEATS_SINCE_START
# global REPEATS_SUCCESSFUL_SINCE_START
# The 'Is playing {}' presence
await bot.change_presence(activity=discord.Game(name="{0} Restarting...".format(pe_global.ORANGE_CIRCLE)))
# For debugging
log.info(f'Login made as {bot.user}')
await tester()
need_to_stop = False
while not need_to_stop:
# Async sleep
await asyncio.sleep(pe_global.AWAIT_TIME)
# Main loop
try:
await major_update()
except Exception as exc:
console.log(exc, traceback.format_exc())
phone_api.bot_crashed(exc)
continue
"""
COMMANDS
"""
@bot.slash_command(name="update", description="Update the known friend list of the bot")
@pe_decorators.command
async def command_hello(ctx):
await ctx.defer()
data = await major_update()
if data in [False, None]:
await ctx.respond("An error occurred during the fetch, this may need human checkup. Use /status to get more details.")
else:
await ctx.respond("The data was updated!")
@bot.slash_command(name="status", description="Give the current status of the bot, concerning recently fetched data")
@pe_decorators.command
async def command_status(ctx):
text_response = "The last fetch of data was `{0}`. The last successful fetch was made on `{1}`.\n"
text_response += "Since the last restart of the bot (`{4}`), there was `{2}` successful requests, over `{3}` in total.\n"
text_response += "(And `{5}` queries to the database).\n"
text_response += "Website status from my computer: `{6}`. Session of the bot status: `{7}`"
fetched_data_status = "successful" if pe_api.LAST_REQUEST_SUCCESSFUL else "unsuccessful"
fetched_data_time_status = pe_api.LAST_REQUEST_TIME.strftime("%Y-%m-%d at %H:%M:%S UTC")
fetch_starting_time = pe_global.STARTING_TIME.strftime("%Y-%m-%d at %H:%M:%S UTC")
website_status = "online" if pe_session.is_website_active() else "down"
session_status = "active" if pe_session.is_connected() else "killed"
text_response = text_response.format(
fetched_data_status,
fetched_data_time_status,
str(pe_api.TOTAL_SUCCESS_REQUESTS),
str(pe_api.TOTAL_REQUESTS),
fetch_starting_time,
pe_database.DB_TOTAL_REQUESTS,
website_status,
session_status
)
await ctx.respond(text_response)
@bot.slash_command(name="profile", description="Render your project euler profile in a cool image")
@option("member", description="Mention the member you want the profile to be displayed", default=None)
@pe_decorators.command
async def command_profile(ctx, member: discord.User):
await ctx.defer()
if member is None:
member = ctx.author
discord_id = member.id
profile_url = "https://cdn.discordapp.com/embed/avatars/{0}.png".format(int(member.discriminator) % 5)
if member.avatar is not None:
profile_url = member.avatar.url
m = pe_api.Member(_discord_id = str(discord_id))
if not m.is_discord_linked():
return await ctx.respond("This user is not linked! Please link your account first")
if m.private() and m.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
user_data = m.solve_array()
rank_in_discord, people_in_discord = m.position_in_discord()
recent_solves = sum(user_data[-10:])
if recent_solves == 10:
recent_solves = (user_data[::-1]+[False]).index(False)
file_path = pe_image.generate_profile_image(
m.username(),
m.solve_count(),
len(m.solve_array()),
rank_in_discord,
people_in_discord,
recent_solves,
profile_url
)
return await ctx.respond(file = discord.File(file_path))
@bot.slash_command(name="link", description="Link your project euler account and your discord account")
@option("username", description="Your Project Euler username account (not nickname)")
@pe_decorators.command
async def command_link(ctx, username: str):
await ctx.defer()
await major_update()
discord_user_id = ctx.author.id
database_discord_user = pe_database.query_single(f"SELECT * FROM members WHERE discord_id = '{discord_user_id}';")
if len(database_discord_user) > 0:
sentence = f"Your discord account is already linked to the account `{database_discord_user[0]['username']}`, type /unlink to unlink it"
return await ctx.respond(sentence)
users = pe_database.query_single(f"SELECT * FROM members WHERE username = '{username}';")
if len(users) == 0:
return await ctx.respond("This username is not in my friend list. Add the bot account on project euler first: 1910895_2C6CP6OuYKOwNlTdL8A5fXZ0p5Y41CZc\nThen ensure your account is not unlisted.\nIf you think this is a mistake, send a DM to <@439143335932854272>.")
user = users[0]
if str(user["discord_id"]) != "":
return await ctx.respond(f"This account is already linked to <@{user['discord_id']}>")
temp_query = f"UPDATE members SET discord_id = '{discord_user_id}' WHERE username = '{username}'"
pe_database.query_single(temp_query)
m = pe_api.Member(_username = username)
await update_member_roles(m)
return await ctx.respond(f"Your account was linked to `{username}`!")
@bot.slash_command(name="unlink", description="Unlink your Project Euler account with your discord account")
@pe_decorators.command
async def command_unlink(ctx):
await ctx.defer()
discord_user_id = ctx.author.id
database_discord_user = pe_database.query_single(f"SELECT * FROM members WHERE discord_id = '{discord_user_id}';")
# database_discord_user = dbqueries.single_req("SELECT * FROM members WHERE discord_id = '{0}'".format(discord_user_id))
if len(database_discord_user) == 0:
return await ctx.respond("Your discord account isn't linked to any profile")
temp_query = f"UPDATE members SET discord_id = '' WHERE discord_id = '{discord_user_id}';"
# dbqueries.single_req(temp_query)
pe_database.query_single(temp_query)
return await ctx.respond("Your discord account was unlinked to the project euler `{0}` account".format(database_discord_user[0]["username"]))
@bot.slash_command(name="kudos", description="Display the kudos progression of your posts on the forum")
@option("member", description="Mention the member you want the kudos to be displayed", default=None)
@pe_decorators.command
async def command_kudos(ctx, member: discord.User):
await ctx.defer()
pe_member = pe_api.Member(_discord_id = (ctx.author.id if member is None else member.id))
if not pe_member.is_discord_linked():
return await ctx.respond("This user does not have a project euler account linked! Please link with /link first")
if pe_member.private() and pe_member.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
if not pe_member.has_kudos_in_database():
pe_member.push_kudo_to_database()
return await ctx.respond("Your current posts have been saved in the database. Next time you use this command,"
"the bot will display how many kudos you earned.")
new_kudos = pe_member.get_new_kudos()
pe_member.push_kudo_to_database()
kudo_count = pe_member.kudo_count()
change = sum([el[1] for el in new_kudos])
if change == 0:
return await ctx.respond(f"No change for user `{pe_member.username_option()}`, still {kudo_count} kudos.")
else:
k = "```" + "\n".join(list(map(lambda x: ": ".join(list(map(str, x))), new_kudos))) + "```"
return await ctx.respond("There was some change for user `{0}`! You gained {1} kudos on the following posts (for a total of {2} kudos):".format(pe_member.username_option(), change, kudo_count) + k)
@bot.slash_command(name="easiest", description="Find the easiest problems you haven't solved yet")
@option("member", description="The member you want you want to see the next possible solves", default=None)
@option("method", description="The method used", choices=["By number of solves", "By order of publication", "By ratio of solves per time unit"], default="By ratio of solves per time unit")
@option("display_nb", description="The number of problems you want to be displayed", min_value=1, max_value=25, default=10)
@pe_decorators.command
async def command_easiest(ctx, member: discord.User, method: str, display_nb: int):
await ctx.defer()
discord_id = ctx.author.id
if member is not None:
discord_id = member.id
m = pe_api.Member(_discord_id = discord_id)
if not m.is_discord_linked():
return await ctx.respond("This user does not have a project euler account linked! Please link with /link first")
if m.private() and m.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
problem_specs = pe_api.Problem.complete_list()
problem_list = [problem_specs[i - 1] for i in m.unsolved_problems()]
def sort_method_key(problem: pe_api.Problem, method: str):
if method == "By number of solves":
return int(problem.solves())
if method == "By order of publication":
return int(problem.unix_publication())
if method == "By ratio of solves per time unit":
time_window = 10
problem_id = problem.problem_id()
last = len(problem_specs)
if problem_id <= last - time_window:
score = problem.solves() / sum([problem_specs[i - 1].solves() for i in range(problem_id, problem_id + time_window)])
else:
score = problem.solves() / sum([problem_specs[i - 1].solves() for i in range(problem_id - time_window, problem_id)])
return score * problem.solves()
problems = sorted(
problem_list,
key=lambda problem: sort_method_key(problem, method),
reverse=True
)
problems = problems[:display_nb]
lst = "```" + "\n".join(list(map(
lambda pb: f"Problem #{pb.problem_id()}: '{pb.name()}' solved by {pb.solves()} members",
problems
))) + "```"
return await ctx.respond(f"Here are the {display_nb} easiest problems available to `{m.username_option()}`:" + lst)
@bot.slash_command(name="graph", description="Graph something!")
@option("data", choices=["solves"], default="solves")
@option("subset", choices=["local", "global"], default="local")
@option("days_count", min_value=0, max_value=1000, default=10)
@pe_decorators.command
async def command_graph(ctx, data: str, subset: str, days_count: int):
await ctx.defer()
if data == "solves":
image_location = pe_plot.graph_solves(days_count, subset == "local")
else:
return await ctx.respond("The given parameters are not actually available")
return await ctx.respond(file = discord.File(image_location))
@bot.slash_command(name="roles-languages", description="Select the languages roles you want to be displayed on your profile")
@pe_decorators.command
async def command_roles_languages(ctx):
view = inters.DropdownView(bot, ctx.author)
# Sending a message containing our View
await ctx.respond("Choose your main languages (by alphabetic order):", view=view, ephemeral=True)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
search = re.finditer("#(\d+)", message.content)
message_problems = set([int(k.group(0)[1:]) for k in search if k.group(0)[1:].isnumeric()])
for problem_id in itertools.islice(message_problems, 10):
if problem_id <= 0 or problem_id > pe_api.last_problem():
continue
try:
data = pe_api.Problem.complete_list()
problem_object: pe_api.Problem = data[problem_id - 1]
problem_embed = discord.Embed(description=
f"[Open problem #{problem_id}](https://projecteuler.net/problem={problem_id}) in web browser: '{problem_object.name()}' (Level {problem_object.difficulty()}/{problem_object.solves()})"
)
except Exception as _:
problem_embed = discord.Embed(description=
f"[Open problem #{problem_id} in web browser](https://projecteuler.net/problem={problem_id})"
)
await message.channel.send(embed=problem_embed)
if len(message.attachments) > 0:
main_attach = message.attachments[0]
if "history" in main_attach.filename and "csv" in main_attach.filename:
filename = main_attach.filename
username = filename.split("_history")[0]
file_url = main_attach.url
content = requests.get(file_url).text
file_path = pe_plot.generate_individual_graph(content, username)
if file_path is None:
await message.channel.send("I could not generate the graph, it requires to know when was each problem published and the request to the server failed.")
else:
await message.channel.send("", file=discord.File(file_path))
path = f"graphs/{username}/"
files = glob.glob(path + "*")
for f in files:
os.remove(f)
@bot.slash_command(name="whosolved", description="Display a list of members who solved a particular problem")
@option("problem", description="The problem")
@pe_decorators.command
async def command_whosolved(ctx, problem: int):
await ctx.defer()
if problem is None:
return await ctx.respond("Please specify a problem!")
members = pe_api.Member.members()
solvers = []
m: pe_api.Member
for m in members:
if m.private():
continue
if m.has_solved(problem):
solvers.append(m.username_option())
# return await ctx.respond("Due to an issue concerning privacy, this command isn't available currently. This should only last for a few days at most, sorry!")
# member_list = pe_api.get_all_members_who_solved(problem)
if len(solvers) == 0:
return await ctx.respond(f"Sadly, no member in my friend list solved problem #{problem}")
try:
boxed_members = "```" + ", ".join(solvers) + "```"
return await ctx.respond(f"Here is the list of members who solved problem #{problem}" + boxed_members)
except Exception as _:
return await ctx.respond(f"The return message must be 2000 or fewer in length, sorry!")
@bot.slash_command(name="compare", description="Compare the solves of two members")
@option("first_member", description="The first member you want to compare the solves of")
@option("second_member", description="The second member you want to compare the solves of")
@option("max_display", description="The maximum displayed number of problems", default=30, min_value=1, max_value=100)
@option("both_color", description="The color displayed for the problems solved by both members", default="#FF5733")
@option("first_color", description="The color displayed for the problems solved by the first member only", default="#C70039")
@option("second_color", description="The color displayed for the problems solved by the second member only", default="#FFC30F")
@pe_decorators.command
async def command_compare(ctx, first_member: discord.User, second_member: discord.User, max_display: int,
both_color: str, first_color: str, second_color: str):
await ctx.defer()
# return await ctx.respond("Due to an issue concerning privacy, this command isn't available currently. This should only last for a few days at most, sorry!")
if first_member is None or second_member is None:
return await ctx.respond("Please specify two valid users!")
first_pe_member = pe_api.Member(_discord_id = first_member.id)
second_pe_member = pe_api.Member(_discord_id = second_member.id)
if not first_pe_member.is_discord_linked() or not second_pe_member.is_discord_linked():
return await ctx.respond("One of the two users has not linked their project euler account!")
if first_pe_member.private() or second_pe_member.private():
return await ctx.respond("One of the two users has a private profile.")
first_username = first_pe_member.username_option()
second_username = second_pe_member.username_option()
common_solves = []
common_not_solves = []
only_first_solves = []
only_second_solves = []
last_problem_id = pe_api.last_problem()
for index in range(1, last_problem_id + 1):
if first_pe_member.has_solved(index) and second_pe_member.has_solved(index):
common_solves.append(index)
elif first_pe_member.has_solved(index) and not second_pe_member.has_solved(index):
only_first_solves.append(index)
elif not first_pe_member.has_solved(index) and second_pe_member.has_solved(index):
only_second_solves.append(index)
else:
common_not_solves.append(index)
def to_rgb(s: str):
s = s.strip('#')
return tuple(map(lambda x: int(x, 16), [s[2*i:2*(i+1)] for i in range(3)]))
print(both_color, to_rgb(both_color))
mix_color = to_rgb(both_color)
color_one = to_rgb(first_color)
color_two = to_rgb(second_color)
solves_with_color = []
for solve in common_solves:
solves_with_color.append((solve, mix_color))
for solve in only_first_solves:
solves_with_color.append((solve, color_one))
for solve in only_second_solves:
solves_with_color.append((solve, color_two))
grid_image = pe_image.project_euler_grid(solves_with_color)
if len(only_first_solves) == 0:
only_first_solves = ["None actually"]
if len(only_second_solves) == 0:
only_second_solves = ["None actually"]
response_text = "The two members have {0} solves in common.\n".format(len(common_solves))
response_text += "Problems solved by `{0}` and not by `{1}`: ".format(first_username, second_username)
response_text += "```" + ", ".join(list(map(str, only_first_solves))[:max_display]) + (" ({0} more)".format(len(only_first_solves) - max_display) if len(only_first_solves) > max_display else "") + "```"
response_text += "Problems solved by `{0}` and not by `{1}`: ".format(second_username, first_username)
response_text += "```" + ", ".join(list(map(str, only_second_solves))[:max_display]) + (" ({0} more)".format(len(only_second_solves) - max_display) if len(only_second_solves) > max_display else "") + "```"
await ctx.respond(response_text, file = discord.File(grid_image))
os.remove(grid_image)
@bot.slash_command(name="thread", description="Create a private thread for a specific problem")
@option("problem", description="The problem you wish to open a thread for")
@pe_decorators.command
async def command_thread(ctx, problem: int):
await ctx.defer()
try:
last_pb = pe_api.Problem.last_problem()
except Exception as _:
last_pb = pe_api.last_problem_database()
console.log(pe_api.Problem.last_problem())
# Just to ensure there's no unused thread
if problem > last_pb:
return await ctx.respond("This problem has not been published yet. Please try another one.")
# Get the list of the threads objects on the server where the command was used
available_threads = await get_available_threads(ctx.guild.id, ctx.channel.id)
# print(available_threads)
thread_name = pe_global.THREAD_DEFAULT_NAME_FORMAT.format(problem)
try:
problem_object = pe_api.Problem(problem)
problem_name = problem_object.name().replace('$', '*')
optional_problem_name = f"'{problem_name}'"
except Exception as _:
optional_problem_name = "Failed to retrieve problem name"
# If a thread already exists (check only with the name), then simply create a new link to it
if thread_name in list(map(lambda element: element.name, available_threads)):
button_view = inters.problem_thread_view(problem_number=problem)
response_text = f"A thread has already been opened for problem #{problem} ({optional_problem_name}). You can join it here:"
return await ctx.respond(response_text, view=button_view)
# Otherwise, find the appropriate channel
adapted_channel = ctx.channel
for chan in ctx.guild.channels:
if chan.name == "problem-discussion":
adapted_channel = chan
break
# Then create the thread in it
thread_object = await adapted_channel.create_thread(name=thread_name, type=discord.ChannelType.private_thread, auto_archive_duration=60)
# Make it impossible for non-moderator to invite people
await thread_object.edit(invitable=False)
# Send the first message of the thread
await thread_object.send(f"Start of the discussion for problem #{problem}, only opened to the solvers :)")
# Retrieve the button object with the correct problem numbers
button_view = inters.problem_thread_view(problem_number=problem)
# Send the button
await ctx.respond(f"Click the button below to join the appropriate thread! (Problem #{problem}: {optional_problem_name})", view=button_view)
@bot.slash_command(name="list-threads", description="Show a list of available threads")
@pe_decorators.command
async def command_list_threads(ctx):
# Allow for more than 3 seconds of thought
await ctx.defer()
# Get the list of all available threads, and retrieve only their name
threads = await get_available_threads(ctx.guild.id, ctx.channel.id)
threads = [x.name for x in threads]
# Keep only those that fit the name for the threads created by the bot
threads = [x for x in threads if x.startswith('Problem #') and x.endswith(" discussion")]
# Get the list of numbers. Go through a set to get rid of duplicates -
# there seem to be multiple threads for some problems?
threads = list({int(x.split()[1][1:]) for x in threads})
threads.sort()
# Merge consecutive threads into runs like "12-15".
# Do not do this for negative bonus problems to avoid "-3--2".
threads.append(threads[-1]+2)
runs = []
start = None
for i in range(len(threads)-1):
if start is None:
start = threads[i]
if threads[i+1] == threads[i]+1 and start > 0:
continue
end = threads[i]
if start == end:
runs.append(str(start))
else:
runs.append(f"{start}-{end}")
start = None
available_message = "Here are the problems with an open thread: ```" + ", ".join(runs) + "```"
return await ctx.respond(available_message)
@bot.slash_command(name="randproblem", description="Give a random problem the user has not solved")
@option("member", description="The targeted member", default=None)
@pe_decorators.command
async def command_randproblem(ctx, member: discord.User):
await ctx.defer()
if member is None:
member = ctx.author
discord_id = member.id
m = pe_api.Member(_discord_id = str(discord_id))
if not m.is_discord_linked():
return await ctx.respond("This user does not have a project euler account linked! Please link with /link first")
if m.private() and m.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
if m.solve_count() == len(m.solve_array()):
return await ctx.respond(f"I *randomly* selected problem #1729 for user: `{m.username_option()}`: <https://teyzer.github.io/problem1729/>")
problems = m.unsolved_problems()
all_problems = pe_api.Problem.complete_list()
choice: pe_api.Problem = all_problems[random.choice(problems) - 1]
text_message = "I randomly selected problem #{0} for user `{1}`: \"{2}\". <https://projecteuler.net/problem={0}>"
text_message = text_message.format(choice.problem_id(), m.username_option(), choice.name())
return await ctx.respond(text_message)
@bot.slash_command(name="events", description="Get the status of an event")
@option("event", description="Which event", choices=["SoPE"])
@option("page", description="Which page of the leaderboard", min=1, max=10, default=1)
@pe_decorators.command
async def command_events(ctx, event: str, page: int):
await ctx.defer()
page_size = 15
if event == "SoPE":
ev = pe_events.eventSoPE()
data = ev.scores()
list_data = [[k, data[k]] for k in data.keys()]
list_data = sorted(list_data, key=lambda element: element[1], reverse=True)
list_data = list_data[page_size * (page - 1) : page_size * page]
text_message = f"Here is the page n°{page} out of {(len(data.keys()) + 14) // page_size} for the event {event}:"
text_message += "```c\n" + "\n".join([f"{page_size * (page - 1) + i + 1}: {list_data[i][0]} with {list_data[i][1]} points" for i in range(len(list_data))]) + "```"
await ctx.respond(text_message)
@bot.slash_command(name="events-data", description="Get the data of an event")
@option("event", description="Which event", choices=["SoPE"])
@pe_decorators.command
async def command_events_data(ctx, event: str):
await ctx.defer()
fls = [f"events/{event}/data.json"]
if event == "SoPE":
ev = pe_events.eventSoPE()
solves = list(map(int, ev.data["solves"].keys()))
solves_with_color = list(map(lambda x: (x, (220, 220, 220)), solves))
grid_image = pe_image.project_euler_grid(solves_with_color)
fls.append(grid_image)
await ctx.respond("", file=discord.File(fls[1]))
os.remove(grid_image)
@bot.slash_command(name="grid", description="Get the solve grid of an user")
@option("member", description="The targeted user", default = None)
@pe_decorators.command
async def commmand_grid(ctx, member: discord.User):
await ctx.defer()
m = pe_api.Member(_discord_id = (ctx.author.id if member is None else member.id))
if not m.is_discord_linked():
return await ctx.respond("This user does not have a project euler account linked! Please link with /link first")
if m.private() and m.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
solves = []
for index, boolean in enumerate(m.solve_array()):
if boolean:
solves.append(index + 1)
solves_with_color = list(map(lambda x: (x, (220, 220, 220)), solves))
grid_image = pe_image.project_euler_grid(solves_with_color)
await ctx.respond(f"Here is the grid for user `{m.username_option()}`", file=discord.File(grid_image))
os.remove(grid_image)
@bot.slash_command(name="grid-animation", description="Get the solve grid of an user")
@option("member", description="The targeted user", default = None)
@pe_decorators.command
async def commmand_grid_animation(ctx, member: discord.User):
await ctx.defer()
m = pe_api.Member(_discord_id = (ctx.author.id if member is None else member.id))
if not m.is_discord_linked():
return await ctx.respond("This user does not have a project euler account linked! Please link with /link first")
if m.private() and m.discord_id() != str(ctx.author.id):
return await ctx.respond("This user has a private profile.")
username = m.username_option()
content = m.solve_csv()
file_path = pe_plot.generate_individual_graph(content, username)
if file_path is None:
await ctx.respond("I could not generate the graph, it requires to know when was each problem published and the request to the server failed.")
else:
await ctx.respond("", file=discord.File(file_path))
path = f"graphs/{username}/"
files = glob.glob(path + "*")
for f in files:
os.remove(f)
@bot.slash_command(name="update-roles")
@option("member", description="The member that you want to be updated", default = None)
@pe_decorators.command
async def command_update_roles(ctx, member: discord.User):
# This allows to give more than 3 seconds to execute the command
await ctx.defer()
discord_id = ctx.author.id
if member is not None:
discord_id = member.id
m = pe_api.Member(_discord_id = discord_id)
await update_member_roles(m)
await ctx.respond("I did not crash during the update, that's all I know", ephemeral=True)
@bot.slash_command(name="announce-back")
@option("problem", description="Which problem", min=1)
@option("member", description="Which member", default = None)
@pe_decorators.command
async def command_announce_back(ctx, problem: int, member: discord.User):
await ctx.defer()
perms = await sufficient_permissions(ctx.guild.get_member(ctx.author.id))
if not perms:
return await ctx.respond("You need to be a moderator or more to use this, sorry!", ephemeral=True)
discord_id = ctx.author.id
if member is not None:
discord_id = member.id
m = pe_api.Member(_discord_id = discord_id)
m.make_problem_unsolved(problem)
await ctx.respond("The solve will quickly be announced. Use /update if you want it to be right now.")
@bot.slash_command(name="force-new-session")
@pe_decorators.command
async def command_force_new_session(ctx):
await ctx.defer()
perms = await sufficient_permissions(ctx.guild.get_member(ctx.author.id))
if not perms:
return await ctx.respond("You need to be a moderator or more to use this, sorry!", ephemeral=True)
values = pe_session.refresh_tokens()
success = not(any([values[k] is None for k in values.keys()]))
pe_api.COOKIES = values
return await ctx.respond(f"Done. Returned keys are non-empty: {success}")
@bot.slash_command(name="leaderboard")
@pe_decorators.command
async def command_leaderboard(ctx):
await ctx.defer()
leaderboard_data = [(m.username_option(), m.solve_count()) for m in pe_api.Member.members()]
return await inters.leaderboard_page(ctx, leaderboard_data, True, True, 10)
@bot.slash_command(name="botisdown")
@option("details", description="If you want to describe why you think so", default="")
@pe_decorators.command
async def bot_is_down(ctx, details: str):
await ctx.defer()
phone_api.bot_info(f"Warning by user: {details}")
return await ctx.respond("Your alert has been sent successfully, sorry for the downtime again!")
# @bot.slash_command(name="awards-requirements", description="Gives the problems you need to solve left to get a specific award")
# @option("award", description="The award you want to get", choices=[
# "As Easy As Pi",
# "Unlucky Squares",
# "Prime Obsession",
# "Trinary Triumph",
# "Fibonacci Fever",
# "Triangle Trophy",
# "Lucky Luke"
# ])
# @option("member", description="Which member", default = None)
# @pe_decorators.command
# async def command_awards_requirements(ctx, award: str, member: discord.User = None):
# await ctx.defer()
# if award is None:
# return await ctx.respond("Please specify an award!")
# discord_id = ctx.author.id
# if member is not None:
# discord_id = member.id
# m = pe_api.Member(_discord_id = discord_id)
# if m.private() and m.discord_id() != str(ctx.author.id):
# return await ctx.respond("This user has a private profile.")
# solve_list = m.solved_problems()
# last_pb = len(m.solve_array())
# valid_problems = []
# solves_needed = 0
# if award == "As Easy As Pi":
# valid_problems = sorted([3, 14, 15, 92, 65, 35, 89, 79, 32, 38, 45])
# solves_needed = len(valid_problems)