-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfunctions.py
More file actions
1238 lines (1123 loc) · 57.4 KB
/
functions.py
File metadata and controls
1238 lines (1123 loc) · 57.4 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 re
import time
import json
import pickle
import random
import discord
import datetime
import asyncio
import shutil
from discord.ext import commands
from discord import Embed
from logger import log_to_hof, log_error, log_info
from discord.ext.commands import Bot
import requests
from PIL import Image, ImageDraw
from discord.ui import button, View, Button, view
from discord.interactions import Interaction
from vars import *
# bot = commands.Bot(command_prefix='')
# 86400 : 24h
# 43200 : 12h
# Test channel : 873627093840314401
# Framed channel : 549986930071175169
DELAY = 7200
LIMIT = 5
HOF_REACTION_THRESHOLD = 28 # reactions needed to enter Hall of Fame
REQUEST_TIMEOUT = 10 # seconds for web requests (Google Sheets, framedsc, etc)
usersMessages = []
# track message ids deleted by bot so on_message_delete doesn't decrement count
botDeletedMessages = set()
class UserMessage:
def __init__(self, id, name, time, count, reachedLimit):
self.id = id
self.name = name
self.time = time
self.count = count
self.reachedLimit = reachedLimit
async def checkMessage(message):
try:
if (message.author.bot):
await log_info("bot message ignored")
return
userId = message.author.id
# Debug: incoming message timestamp
await log_info(str(message.created_at))
embeds = message.embeds
attachmentCount = message.attachments
DMChannel = await message.author.create_dm()
# if message.content != '':
# rightTitle = next((i for i, item in enumerate(titleAlts) if message.content in next(iter(item))), None)
# if rightTitle is None:
# altTitle = next((i for i, item in enumerate(titleAlts) if message.content in item[next(iter(item))]), None)
# if altTitle is None:
# # await DMChannel.send("It looks like the name of that game isn't registered on my database, could you ask to one of the moderator to add it please")
# pass
# else:
# goodTitle = next(iter(titleAlts[altTitle]))
# await DMChannel.send(f"The name you used isn't very clear, could you rename it with : **{goodTitle}**")
if len(attachmentCount) > 1:
await DMChannel.send(f"Please post your shots one by one.")
await message.delete()
return
if len(attachmentCount) == 0 and len(embeds) == 0:
await log_info('ignored')
return
# await DMChannel.send(f"Please do n„t talk in this channel.")
# await message.delete()
await log_info(f"Attachment count: {len(attachmentCount)}")
await log_info(f"Embeds count: {len(embeds)}")
for msg in usersMessages:
if msg.id == userId:
endTime = msg.time + DELAY
remainingTime = DELAY - (time.time() - msg.time)
# Mark when next post reaches the limit
if msg.count == LIMIT - 1:
msg.reachedLimit = True
await log_info(f"Window ends at: {endTime}")
if time.time() <= endTime:
# Compute would-be count for this incoming message
new_count = msg.count + 1
if new_count > LIMIT:
await log_info(f"Limit exceeded for {msg.name}, deleting message {message.id}")
# mark this message as bot-deleted so on_message_delete ignores it
botDeletedMessages.add(message.id)
try:
# Extensive debug logging before deletion attempt
bot_member = message.guild.me
author_member = message.author if isinstance(message.author, discord.Member) else None
await log_info(f"[DELETE_DEBUG] Guild: {message.guild.name} (ID: {message.guild.id})")
await log_info(f"[DELETE_DEBUG] Channel: {message.channel.name} (ID: {message.channel.id}, Type: {message.channel.type})")
await log_info(f"[DELETE_DEBUG] Bot member exists: {bot_member is not None}")
await log_info(f"[DELETE_DEBUG] Author: {message.author} (ID: {message.author.id})")
if bot_member:
bot_perms = message.channel.permissions_for(bot_member)
author_perms = message.channel.permissions_for(author_member) if author_member else None
overwrite_bot = message.channel.overwrites_for(bot_member)
overwrite_author = message.channel.overwrites_for(author_member) if author_member else None
await log_info(
f"[DELETE_DEBUG] Bot perms - Manage Messages: {bot_perms.manage_messages}, Admin: {bot_perms.administrator}, "
f"Overwrite manage_messages: {overwrite_bot.manage_messages}"
)
await log_info(f"[DELETE_DEBUG] Bot top role: {bot_member.top_role} (Position: {bot_member.top_role.position})")
if author_member:
await log_info(
f"[DELETE_DEBUG] Author top role: {author_member.top_role} (Position: {author_member.top_role.position}), "
f"Overwrite manage_messages: {overwrite_author.manage_messages if overwrite_author else None}"
)
await log_info(f"[DELETE_DEBUG] Bot higher than author: {bot_member.top_role.position > author_member.top_role.position}")
else:
await log_error(f"[DELETE_DEBUG] Bot member is None! Guild me: {message.guild.me}")
await log_info(f"[DELETE_DEBUG] Message ID: {message.id}, Author ID: {message.author.id}, Timestamp: {message.created_at}")
await message.delete()
await log_info(f"Successfully deleted message {message.id}")
except discord.Forbidden as e:
bot_member = message.guild.me
bot_perms = message.channel.permissions_for(bot_member) if bot_member else None
overwrite_bot = message.channel.overwrites_for(bot_member) if bot_member else None
await log_error(f"[FORBIDDEN] Cannot delete message from {msg.name} (ID: {message.author.id})")
await log_error(f"[FORBIDDEN] Guild: {message.guild.name}, Channel: {message.channel.name}")
if bot_perms:
await log_error(
f"[FORBIDDEN] Bot perms - Manage Messages: {bot_perms.manage_messages}, Admin: {bot_perms.administrator}, "
f"Overwrite manage_messages: {overwrite_bot.manage_messages if overwrite_bot else None}"
)
await log_error(f"[FORBIDDEN] Full error: {e}")
botDeletedMessages.discard(message.id)
except discord.NotFound:
await log_error(f"Message already deleted from {msg.name}")
botDeletedMessages.discard(message.id)
except Exception as e:
await log_error(f"Failed to delete message from {msg.name}: {type(e).__name__}: {e}")
botDeletedMessages.discard(message.id)
try:
await DMChannel.send(
f"Sorry, you can't post more than **{LIMIT}** shots per window.\n"
f"You can post again at **<t:{round(endTime)}:F>** (in **{datetime.timedelta(seconds=round(remainingTime))}**)."
)
except Exception:
await log_error("DM failed, probably blocked by the user")
return
else:
msg.count = new_count
else:
msg.time = time.time()
msg.count = 1
msg.reachedLimit = False
await log_info(
f"UserId:{msg.id} first:{msg.time} count:{msg.count} by:{msg.name}"
)
return
usersMessages.append(UserMessage(userId, message.author.name + "#" + message.author.discriminator, time.time(), 1, False))
await log_info(f"UserId:{userId} first:{time.time()} count:1 by:{message.author.name}#{message.author.discriminator}")
except Exception as e:
await log_error(f"checkMessage crashed: {e}")
import traceback
await log_error(traceback.format_exc())
async def save():
with open('messages.pkl', 'wb') as f:
pickle.dump(usersMessages, f)
def saveBingo():
with open('bingo.pkl', 'wb') as f:
pickle.dump(emptyBingo, f)
def saveTitleAlts():
with open('titleAlts.pkl', 'wb') as f:
pickle.dump(titleAlts, f)
def saveConfig():
with open('./config.ini', 'w') as configfile:
config.write(configfile)
def removeFilesInFolder(folder = './todaysGallery'):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
def changeCurrentLimit(ctx, arg):
try:
new_limit = int(arg)
if new_limit <= 0:
print(f"Invalid limit {new_limit}: must be > 0")
return
print(f"'changeLimit' command has been used by {ctx.author.name}#{ctx.author.discriminator}")
global LIMIT
LIMIT = new_limit
config['DEFAULT']['limit'] = str(LIMIT)
saveConfig()
print("Limit has been changed to", arg)
except ValueError:
print(f"Invalid limit value: {arg} (expected integer)")
except Exception as e:
print(f"Error changing limit: {e}")
def changeCurrentDelay(ctx, arg):
try:
new_delay = int(arg)
if new_delay <= 0:
print(f"Invalid delay {new_delay}: must be > 0")
return
print(f"'changeDelay' command has been used by {ctx.author.name}#{ctx.author.discriminator}")
global DELAY
DELAY = new_delay
config['DEFAULT']['delay'] = str(DELAY)
saveConfig()
print("Delay has been changed to", arg)
except ValueError:
print(f"Invalid delay value: {arg} (expected integer)")
except Exception as e:
print(f"Error changing delay: {e}")
def getCurrentValue(): return (LIMIT, DELAY)
async def resetUser(arg):
try:
user_id = int(arg)
except ValueError:
return f"Invalid user ID: {arg} (expected integer)"
curUser = ""
response = ""
global usersMessages
for msg in usersMessages:
if msg.id == user_id:
msg.count = 0
msg.reachedLimit = False
curUser = msg.name
if curUser == "":
response = "This user either doesn't exist or didn't post anything yet"
else:
response = f"{curUser} has been reset"
await save()
return response
async def resetAllUsers():
global usersMessages
for msg in usersMessages:
msg.count = 0
msg.reachedLimit = False
await save()
async def getCams(args):
try:
response = requests.get('https://docs.google.com/spreadsheet/ccc?key=1lnM2SM_RBzqile870zG70E39wuuseqQE0AaPW-P1p5E&output=csv', timeout=REQUEST_TIMEOUT)
assert response.status_code == 200, 'Wrong status code'
except requests.Timeout:
return "", []
except Exception as e:
print(f"Error fetching cams: {e}")
return "", []
# print(response.content)
spreadData = str(response.content).split('\\r\\n')
spreadData.pop(0)
matched_lines = []
line_index = 0
args = ' '.join(args) if type(args) is tuple else args
args = args.replace("'", "\\'")
for line in spreadData:
if str(args).lower() in line.lower().split(',')[0]:
next_index = 1
if line.find(',') > -1:
matched_lines += [line]
try:
if(spreadData[line_index + next_index] == ''): next_index += 1
except: pass
while (line_index + next_index < len(spreadData)
and spreadData[line_index + next_index].split(',')[0] == ''):
if spreadData[line_index + next_index].split(',')[1].startswith('http'):
matched_lines += [spreadData[line_index + next_index]]
next_index += 1
line_index += 1
data = ''
gameNames = []
for item in matched_lines:
line_note = ""
if item.split(',')[2] != "":
first_two_length = len(item.split(',')[0]) + len(item.split(',')[1])
line_note = " *(" + item[item.find('"', first_two_length + 1):-1] + ")*" if '"' in item.split(',')[2] else " *(" + item.split(',')[2] + ")*"
line_note = line_note.replace("\\n", "\n\t")
line_note = line_note.replace('"', "")
if item.split(',')[1].startswith('"'):
for el in item.split(',')[1].strip('"').split('\\n'):
data += item.split(',')[0] + " : " + el + line_note + "\n"
continue
data += "**" + item.split(',')[0] + "** : <" + item.split(',')[1] + ">" + line_note + "\n" if item.split(',')[0] != "" else "**╘** : <" + item.split(',')[1] + ">" + line_note + "\n"
gameNames.append(item.split(',')[0])
gameNames[:] = ["**" + x + "**" for x in gameNames if x]
return data, gameNames
async def getUUU(args):
args = ' '.join(args) if type(args) is tuple else args
args = args.replace("'", "\\'")
try:
response = requests.get('https://framedsc.github.io/GeneralGuides/universal_ue4_consoleunlocker.htm', timeout=REQUEST_TIMEOUT)
assert response.status_code == 200, 'Wrong status code'
except requests.Timeout:
return "", []
except Exception as e:
print(f"Error fetching UUU guide: {e}")
return "", []
try:
gamesListPage = re.findall(r'(?s)known to work with the unlocker.*Additionally, mos', str(response.content), flags=re.S | re.M)
except Exception as e:
print(f"Error parsing UUU content: {e}")
return "", []
normalizedList = re.sub(r'<code>|<\/code>', '', gamesListPage[0])
normalizedList = re.sub(r'\\t\\n', '', normalizedList)
normalizedList = re.sub(r'timestop/pause', 'timestop & pause', normalizedList)
normalizedList = re.sub(r'Gamepass / MS', 'Gamepass & MS', normalizedList)
normalizedList = re.sub(r'console/timestop', 'console & timestop', normalizedList)
games = re.finditer(r'<td>([\(\)&\+\,\.\':-`-\w\s^\\t]*)<\/td>', normalizedList, flags=0)
gameList = []
data = ""
gameNames = []
for matchNum, match in enumerate(games, start=1):
gameList.append(match.group(1))
arg = args.lower()
for index, game in enumerate(gameList):
if arg in game.lower() and index % 2 == 0:
data += "**" + gameList[index] + "** works with UUU. Notes : " + gameList[index+1] + "\n" if gameList[index+1] != '' else "**" + gameList[index] + "** works with UUU\n"
gameNames.append("**" + gameList[index] + "**")
return data, gameNames
async def getGuides(args):
args = ' '.join(args) if type(args) is tuple else args
args = args.replace("'", "\\'")
urls = [
'https://framedsc.github.io/A-L.htm',
'https://framedsc.github.io/M-Z.htm',
'https://framedsc.com/Consoleguides.htm',
'https://framedsc.github.io/GeneralGuides/index.htm',
'https://framedsc.github.io/GeneralGuidesAdvanced.htm',
'https://framedsc.github.io/ReshadeGuides/index.htm',
'https://framedsc.github.io/ReshadeGuidesShaders/index.htm',
'https://framedsc.com/ReshadeGuidesAddonguides.htm'
]
responses = []
for url in urls:
try:
r = requests.get(url, timeout=REQUEST_TIMEOUT)
assert r.status_code == 200, f'Wrong status code for {url}'
responses.append(r)
except requests.Timeout:
print(f"Timeout fetching {url}")
continue
except Exception as e:
print(f"Error fetching {url}: {e}")
continue
if not responses:
return "", []
combined_content = ""
for r in responses:
combined_content += str(r.content)
try:
normalizedList = re.sub(r'\\t|\\n|\\r', '\n', combined_content)
guidesRegex = r'"><a href="(GameGuides\/.*\.htm|..\/ReshadeGuides\/.*\.htm|..\/GeneralGuides\/.*\.htm|ReshadeGuides\/Shaders\/.*\.htm|ReshadeGuides\/Addons\/.*\.htm)">(.*)<\/a>'
guides = re.finditer(guidesRegex, normalizedList, flags=re.M)
guideLinks = []
guideNames = []
for matchNum, match in enumerate(guides, start=1):
guideLinks.append(match.group(1))
guideNames.append(match.group(2))
except Exception as e:
print(f"Error parsing guides: {e}")
return "", []
arg = args.lower()
data = ""
gameNames = []
for index, game in enumerate(guideNames):
if arg in game.lower():
data += "**" + guideNames[index] + "** : <https://framedsc.github.io/" + guideLinks[index] + ">\n"
gameNames.append("**" + guideNames[index] + "**")
return data, gameNames
async def getCheats(args):
args = ' '.join(args) if type(args) is tuple else args
# args = args.replace("'", "\\'")
try:
response = requests.get("https://framedsc.github.io/cheattablearchive.htm", allow_redirects=True, timeout=REQUEST_TIMEOUT)
assert response.status_code == 200, 'Wrong status code'
except requests.Timeout:
return "", []
except Exception as e:
print(f"Error fetching cheats: {e}")
return "", []
try:
cheats = re.finditer(r'^<h3.*?>(.*?)<.*?<\/ul', response.text, flags=re.S | re.M)
except Exception as e:
print(f"Error parsing cheats: {e}")
return "", []
cheatsName = []
cheatsContent = []
data = ""
gameNames = []
for matchNum, match in enumerate(cheats, start=1):
cheatsName.append(match.group(1))
cheatsContent.append(match.group(0))
arg = args.lower()
for index, cheat in enumerate(cheatsName):
if arg in cheat.lower():
if cheat.find("(") > -1:
cheat = cheat[:-2]
data += "**" + cheat + "** : "
gameNames.append("**" + cheat + "**")
cheatsRegex = re.finditer(r'(CheatTables\/Archive\/.*\.(?:CT|ct))">', cheatsContent[index])
for matchNum2, match2 in enumerate(cheatsRegex, start=1):
data += "<https://framedsc.github.io/" + match2.group(1) + ">\n" if matchNum2 == 1 else "\t**╘** : <https://framedsc.github.io/" + match2.group(1) + ">\n"
return data, gameNames
async def secondLook(message):
authorName = message.author.name + "#" + message.author.discriminator
authorId = message.author.id
SLDchannel = bot.get_channel(SLDump)
if message.author.bot and len(message.mentions) > 0:
authorName = message.mentions[0].name + "#" + message.mentions[0].discriminator
authorId = message.mentions[0].id
userDict = {}
links = re.findall(r"(https://discord\.com/channels/.*/.*/\d)(?:| )", message.content)
if len(links) <= 3:
return
await log_info(f"Building second-look message for {authorName} with {len(links)} links")
async with message.channel.typing():
for link in links:
try:
slink = link.split("/")
original_message = await bot.get_guild(int(slink[-3])).get_channel(int(slink[-2])).fetch_message(int(slink[-1]))
except Exception as e:
await log_error(f"Failed to fetch message from link {link}: {e}")
continue
try:
raw_shot = requests.get(original_message.attachments[0].url, stream=True, timeout=REQUEST_TIMEOUT).raw
except requests.Timeout:
await log_error(f"Timeout downloading attachment from {original_message.author.name}")
continue
except Exception as e:
await log_error(f"Failed to download attachment: {e}")
continue
try:
shot = Image.open(raw_shot)
shot = shot.convert(mode="RGB")
shot_filename = f'secondLook/{original_message.author.name}-{original_message.created_at.timestamp()}.jpg'
shot.save(shot_filename, format="JPEG", quality=60)
except Exception as e:
await log_error(f"Failed to process image: {e}")
continue
try:
sent_message = await SLDchannel.send(file=discord.File(shot_filename))
except Exception as e:
await log_error(f"Failed to send to Discord: {e}")
continue
try:
blob = bucket.blob(shot_filename)
blob.upload_from_filename(shot_filename)
blob.make_public()
except Exception as e:
await log_error(f"Failed to upload to Firebase: {e}")
continue
tempDict = {}
tempDict['id'] = f"{original_message.author.id}"
tempDict['name'] = original_message.author.name
tempDict['displayName'] = original_message.author.display_name
tempDict['globalName'] = original_message.author.global_name
tempDict['isSpoiler'] = original_message.attachments[0].is_spoiler()
tempDict['createdAt'] = original_message.created_at.timestamp()
tempDict['imageUrl'] = blob.public_url
tempDict['width'] = sent_message.attachments[0].width
tempDict['height'] = sent_message.attachments[0].height
tempDict['messageUrl'] = link
userDict[str(original_message.id)] = tempDict
await log_info(f"Processed shot from {original_message.author.name}")
try:
await bot.get_channel(SLChannel).send(f"Here is your link : https://second-look.netlify.app/gallery/{authorId}")
await log_info(f"Second look complete for {authorName}")
except Exception as e:
await log_error(f"Failed to send second look summary: {e}")
try:
ref.child(str(authorId)).set(userDict)
except Exception as e:
await log_error(f"Failed to update Firebase for {authorName}: {e}")
removeFilesInFolder("./secondLook")
async def todaysGallery():
bot.dispatch("today_gallery_end")
userDict = {}
day_ago = datetime.datetime.today() - datetime.timedelta(days=1)
SYSchannel = bot.get_channel(SYSChannel)
SLDchannel = bot.get_channel(SLDump)
if SYSchannel is None:
await log_error("SYSChannel not found, skipping todaysGallery")
return
await log_info("Building today's gallery")
try:
messages = [message async for message in SYSchannel.history(limit=200, after=day_ago)]
except Exception as e:
await log_error(f"Failed to fetch message history: {e}")
return
for msg in messages:
try:
# Get reaction count
try:
enough_reaction = False if await getShotReactions(msg) <= HOF_REACTION_THRESHOLD else True
except Exception as e:
await log_error(f"Failed to get reactions for msg {msg.id}: {e}")
continue
# Download attachment with timeout
try:
raw_shot = requests.get(msg.attachments[0].url, stream=True, timeout=REQUEST_TIMEOUT).raw
except requests.Timeout:
await log_error(f"Request timeout for attachment from {msg.author.name}")
continue
except Exception as e:
await log_error(f"Failed to download attachment from {msg.author.name}: {e}")
continue
# Process image
try:
shot = Image.open(raw_shot)
shot = shot.convert(mode="RGB")
shot_filename = f'todaysGallery/{msg.author.name}-{msg.created_at.timestamp()}.jpg'
shot.save(shot_filename, format="JPEG", quality=50)
except Exception as e:
await log_error(f"Failed to process/save image from {msg.author.name}: {e}")
continue
# Send to Discord
try:
sent_message = await SLDchannel.send(file=discord.File(shot_filename))
except Exception as e:
await log_error(f"Failed to send image to Discord from {msg.author.name}: {e}")
continue
# Upload to Firebase
try:
blob = bucket.blob(shot_filename)
blob.upload_from_filename(shot_filename)
blob.make_public()
except Exception as e:
await log_error(f"Failed to upload to Firebase from {msg.author.name}: {e}")
continue
# Add to userDict
tempDict = {}
tempDict['id'] = f"{msg.author.id}"
tempDict['name'] = msg.author.name
tempDict['displayName'] = msg.author.display_name
tempDict['createdAt'] = msg.created_at.timestamp()
tempDict['imageUrl'] = blob.public_url
tempDict['width'] = sent_message.attachments[0].width
tempDict['height'] = sent_message.attachments[0].height
tempDict['messageUrl'] = msg.jump_url
tempDict['isHoffed'] = enough_reaction
userDict[str(msg.id)] = tempDict
await log_info(f"Processed shot from {msg.author.name}")
except Exception as e:
await log_error(f"Unexpected error processing message {msg.id}: {e}")
continue
# Update Firebase with all processed shots
try:
botsData = ref.child(str(bot.user.id)).get()
if botsData is not None:
global_len = len(botsData) + len(userDict)
else:
botsData = {}
global_len = len(userDict)
# Keep only last 1000 shots
if global_len >= 1000:
for i in range(global_len - 1000):
botsData.pop(next(iter(botsData)))
botsData.update(userDict)
ref.child(str(bot.user.id)).set(botsData)
await log_info(f"Gallery updated with {len(userDict)} new shots, total: {len(botsData)}")
except Exception as e:
await log_error(f"Failed to update Firebase: {e}")
return
# Send summary to channel
try:
await bot.get_channel(SLChannel).send(f"Today's gallery has been updated with today's shot : https://second-look.netlify.app/gallery/todays-gallery")
except Exception as e:
await log_error(f"Failed to send gallery update message: {e}")
removeFilesInFolder("./todaysGallery")
await log_info("Gallery building completed")
async def startThread(message):
title = f"Hello There, {message.author.name}"
thread = await message.channel.create_thread(name=title, message=message, reason="Thread created for new member")
await thread.send("https://tenor.com/view/hello-there-general-kenobi-gif-18841535")
member = message.guild.get_member(message.author.id)
if member is None:
member = await message.guild.fetch_member(message.author.id)
try:
welcome_role = discord.utils.get(member.guild.roles, id=WelcomeRole)
padawan_role = discord.utils.get(member.guild.roles, id=PadawanRole)
if welcome_role is None:
await log_error(f"Welcome role not found: {WelcomeRole}")
else:
await member.remove_roles(welcome_role)
await log_info(f"Removed Welcome role from {member.name}")
await asyncio.sleep(0.5)
if padawan_role is None:
await log_error(f"Padawan role not found: {PadawanRole}")
else:
await member.add_roles(padawan_role)
await log_info(f"Added Padawan role to {member.name}")
except Exception as e:
await log_error(f"Failed to modify roles for {member.name}: {e}")
async def over2000(data, gameNames, query):
isOver2000 = len(data) > 2000
query = ' '.join(query) if type(query) is tuple else query
if(isOver2000):
# response = "Search query is too vague, there are too many results to show.\n" + str(len(gameNames)) + " games corresponds to your query, please retype the command with one of them : \n"
response = random.choice(tooVague).format(query)
response += " | ".join([name for name in gameNames])
if(len(gameNames) > 15):
response = "I found too many results for `{}` ! Please be more specific !".format(query)
return response
return data
async def react(message, reason, botAvatar):
percentage = 2 if reason == "bad" else 5 if reason == "good" else 6 if reason == "horny" else 2
if random.randint(0, 9) < percentage:
gifs = badGifs if reason == "bad" else goodGifs if reason == "good" else hornyGifs
await message.reply(random.choice(gifs))
else:
badGuy = requests.get(message.author.avatar, stream=True).raw
botPfp = requests.get(botAvatar, stream=True).raw
botImg = badBot if reason == "bad" else goodBot if reason == "good" else hornyBot
memePath, memeInfo = random.choice(list(botImg.items()))
meme = Image.open('images/' + memePath + '.jpg').convert('RGB')
botImg = Image.open(botPfp)
botImg.thumbnail(memeInfo['size'], Image.ANTIALIAS)
badGuy = Image.open(badGuy)
badGuy.thumbnail(memeInfo['size'], Image.ANTIALIAS)
memeCopy = meme.copy()
memeCopy.paste(botImg, memeInfo['botPosition'])
memeCopy.paste(badGuy, memeInfo['badPosition'])
memeCopy.save('./temp.jpg', quality=95)
await message.reply(file=discord.File('temp.jpg'))
async def loadImagesFromHOF(msg, channel):
async with channel.typing():
epoch = re.findall(r"https:\/\/framedsc\.com\/HallOfFramed\/.*imageId=(\d*)", msg)
shotsDb = requests.get('https://raw.githubusercontent.com/originalnicodrgitbot/hall-of-framed-db/main/shotsdb.json')
assert shotsDb.status_code == 200, 'Wrong status code'
shotsDict = json.loads(shotsDb.content)
foundShot = []
for shot in shotsDict["_default"].values():
for epch in epoch:
if str(epch) == str(shot["epochTime"]):
foundShot.append(shot)
messageContent = ""
for fShot in foundShot:
messageContent += f"{fShot['shotUrl']}\n"
await channel.send(messageContent)
class BingoPoints:
def __init__(self, id, name) -> None:
self.id = id
self.name = name
# self.pointMap = pointMap
class EphemeralBingo(View):
def __init__(self, channelId, timeout = None):
super().__init__(timeout=timeout)
self.chanId = channelId
@discord.ui.button(label='Check', style=discord.ButtonStyle.blurple)
async def checkCompact(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
padawan = interaction.user.guild.get_role(PadawanRole)
except AttributeError:
await interaction.response.send_message("Sorry but you can only play bingo in the Framed server", ephemeral=True)
return
if padawan is None:
await interaction.response.send_message("Sorry but you can only play bingo in the Framed server", ephemeral=True)
else:
if padawan in interaction.user.roles:
await interaction.response.send_message("Sorry! Members with padawan role aren't currently eligible to play the bingo right now.", ephemeral=True)
else:
await interaction.response.send_message("Choose a box", view=BingoView(params={'compact': True, 'user': interaction.user, 'channel': self.chanId}), ephemeral=True)
class BingoView(View):
def __init__(self, params, timeout = None):
super().__init__(timeout=timeout)
if not params.get('compact'): params['compact'] = False
self.user = params['user']
self.channel = params['channel']
self.board = self.getScore()
for x in range(5):
for y in range(5):
if params['compact']: self.add_item(BingoViewButton(x, y, f"{x+1}-{y+1}", self.board, self.user.avatar))
if not params['compact']: self.add_item(BingoViewButton(x, y, bingoText[y][x], self.board, self.user.avatar))
def getScore(self):
# for bp in bingoPoints:
# if bp.id == self.user.id:
# return bp.pointMap
# bingoPoints.append(BingoPoints(self.user.id, self.user.name))
return emptyBingo
def setScore(self, x, y):
print(f"{self.user.name} checked the {x+1}-{y+1} case")
emptyBingo[x][y] = 1
for bp in bingoPoints:
if bp.id == self.user.id:
# bp.pointMap[x][y] = 1
return True
bingoPoints.append(BingoPoints(self.user.id, self.user.name))
def checkWinner(self):
for horizontal in self.board:
value = sum(horizontal)
if value == 5:
return self.user
for vertical in range(5):
value = self.board[0][vertical] + self.board[1][vertical] + self.board[2][vertical] + self.board[3][vertical] + self.board[4][vertical]
if value == 5:
return self.user
diagBLTR = self.board[0][4] + self.board[1][3] + self.board[2][2] + self.board[3][1] + self.board[4][0]
if diagBLTR == 5:
return self.user
diagTLBR = self.board[0][0] + self.board[1][1] + self.board[2][2] + self.board[3][3] + self.board[4][4]
if diagTLBR == 5:
return self.user
return None
# https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/examples/views/tic_tac_toe.py
class BingoViewButton(Button):
def __init__(self, x, y, label, board, avatar):
if board[x][y] == 1:
super().__init__(label=label, style=discord.ButtonStyle.success, disabled=True, row=y)
if board[x][y] == 0:
super().__init__(label=label, style=discord.ButtonStyle.secondary, row=y)
self.x = x
self.y = y
self.label = label if label != "3-3" else "Free"
self.avatar = avatar
async def callback(self, interaction: discord.Interaction):
assert self.view is not None
view = self.view
view.setScore(self.x, self.y)
userAvatar = self.avatar.with_size(256) if self.avatar != None else None
saveBingo()
crossBingo(self.x, self.y, False, userAvatar)
self.style = discord.ButtonStyle.success
self.disabled = True
for child in view.children:
child.disabled = True
await interaction.response.edit_message(view=view)
winner = view.checkWinner()
if winner is not None:
bot.dispatch("bingo_winner", view.user, view.channel)
def crossBingo(caseX, caseY, reset, avatar = None):
caseSize = 285
X, Y = (119, 260)
X += caseSize * caseX
Y += caseSize * caseY
if avatar == None:
botPfp = requests.get(bot.user.avatar if bot.user is not None else "https://cdn.discordapp.com/avatars/873628046194778123/af45db5ed0d8487690bf469d3b023590.webp?size=240", stream=True).raw
else:
botPfp = requests.get(avatar, stream=True).raw
bingo = Image.open('images/bingo.png') if reset == True else Image.open('./tempBingo.png')
botImg = Image.open(botPfp)
botMask = Image.new("L", botImg.size, 0)
draw = ImageDraw.Draw(botMask)
draw.ellipse((0, 0, 240, 240), fill=120)
botImg.putalpha(botMask)
bingoCopy = bingo.copy()
try:
bingoCopy.paste(botImg, (X, Y), botImg) # (119, 260)
except ValueError:
botPfp = requests.get(bot.user.avatar if bot.user is not None else "https://cdn.discordapp.com/avatars/873628046194778123/af45db5ed0d8487690bf469d3b023590.webp?size=240", stream=True).raw
botImg = Image.open(botPfp)
botMask = Image.new("L", botImg.size, 0)
draw = ImageDraw.Draw(botMask)
draw.ellipse((0, 0, 240, 240), fill=120)
botImg.putalpha(botMask)
bingoCopy.paste(botImg, (X, Y), botImg)
bingoCopy.save('./tempBingo.png', quality=95)
def recreateBingo(bingo):
for i in range(len(bingo)):
for j in range(len(bingo[i])):
if bingo[i][j] == 1:
crossBingo(i, j, False)
def resetBingoBoard():
bingoPoints.clear()
global emptyBingo
emptyBingo = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
crossBingo(-2, -1, True)
class Confirm(View):
def __init__(self, players: list[str], customEmoji1 = None, customEmoji2 = None):
super().__init__()
self.connect4 = [
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
]
self.players = players
self.emoji1 = customEmoji1
self.emoji2 = customEmoji2
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.players[1] is not None:
if interaction.user.id == self.players[1]:
await interaction.response.edit_message(content=toDiscordString(self.connect4, 3, self.players[1], 1, customEmoji1=self.emoji1, customEmoji2=self.emoji2), view=Connect4(self.connect4, players=self.players, customEmoji1=self.emoji1, customEmoji2=self.emoji2))
self.stop()
else:
await interaction.response.edit_message(content=f"<@{self.players[0]}> wants to play connect4 with you <@{self.players[1]}>, will you accept ? PS: Only the mentionned person can respond")
else:
self.players[1] = interaction.user.id
await interaction.response.edit_message(content=toDiscordString(self.connect4, 3, self.players[1], 1, customEmoji1=self.emoji1, customEmoji2=self.emoji2), view=Connect4(self.connect4, players=self.players, customEmoji1=self.emoji1, customEmoji2=self.emoji2))
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.players[1] is not None:
if interaction.user.id == self.players[1]:
button.disabled = True
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content='Sorry, but the offer got rejected', view=self)
self.stop()
else:
await interaction.response.edit_message(content=f"<@{self.players[0]}> wants to play connect4 with you <@{self.players[1]}>, will you accept ? PS: Only the mentionned person can respond")
else:
button.disabled = True
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content='Sorry, but the offer got rejected', view=self)
self.stop()
class Connect4(View):
def __init__(self, board, players: list[str], customEmoji1 = None, customEmoji2 = None):
super().__init__()
self.cursor = 3
self.c4Board = board
self.emoji1 = customEmoji1
self.emoji2 = customEmoji2
self.players = players
self.turns = 2
self.playerTurn = 1
self.blockedCol = False
self.replay = []
def addTurn(self):
self.playerTurn = self.turns % 2
self.turns += 1
def checkConnect4Winner(self, player):
for y in range(len(self.c4Board)):
for x in range(len(self.c4Board[y])):
# having an negative index doesn't give an indexError but check from the list's end, but an index superior to the list's length throw an exception, so first check is
# ifx or y superior to their max length and checking at the end if they're negative
try:
if x + 3 < 7 and self.c4Board[y][x] == player and self.c4Board[y][x + 1] == player and self.c4Board[y][x + 2] == player and self.c4Board[y][x + 3] == player:
self.markWinningBoard([[y, x], [y, x + 1], [y, x + 2], [y, x + 3]], player)
return True
if x + 3 < 7 and y + 3 < 6 and self.c4Board[y][x] == player and self.c4Board[y + 1][x + 1] == player and self.c4Board[y + 2][x + 2] == player and self.c4Board[y + 3][x + 3] == player:
self.markWinningBoard([[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]], player)
return True
if y + 3 < 6 and self.c4Board[y][x] == player and self.c4Board[y + 1][x] == player and self.c4Board[y + 2][x] == player and self.c4Board[y + 3][x] == player:
self.markWinningBoard([[y, x], [y + 1, x], [y + 2, x], [y + 3, x]], player)
return True
if y + 3 < 6 and self.c4Board[y][x] == player and self.c4Board[y + 1][x - 1] == player and self.c4Board[y + 2][x - 2] == player and self.c4Board[y + 3][x - 3] == player and x - 3 > -1:
self.markWinningBoard([[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]], player)
return True
if self.c4Board[y][x] == player and self.c4Board[y][x - 1] == player and self.c4Board[y][x - 2] == player and self.c4Board[y][x - 3] == player and x - 3 > -1:
self.markWinningBoard([[y, x], [y, x - 1], [y, x - 2], [y, x - 3]], player)
return True
if self.c4Board[y][x] == player and self.c4Board[y - 1][x - 1] == player and self.c4Board[y - 2][x - 2] == player and self.c4Board[y - 3][x - 3] == player and x - 3 > -1 and y - 3 > -1:
self.markWinningBoard([[y, x], [y - 1, x - 1], [y - 2, x - 2], [y - 3, x - 3]], player)
return True
if self.c4Board[y][x] == player and self.c4Board[y - 1][x] == player and self.c4Board[y - 2][x] == player and self.c4Board[y - 3][x] == player and y - 3 > -1:
self.markWinningBoard([[y, x], [y - 1, x], [y - 2, x], [y - 3, x]], player)
return True
if x + 3 < 7 and self.c4Board[y][x] == player and self.c4Board[y - 1][x + 1] == player and self.c4Board[y - 2][x + 2] == player and self.c4Board[y - 3][x + 3] == player and y - 3 > -1:
self.markWinningBoard([[y, x], [y - 1, x + 1], [y - 2, x + 2], [y - 3, x + 3]], player)
return True
except IndexError:
print("got an indexError on", x, y)
continue
return False
def checkTie(self):
for y in self.c4Board:
tie = all(dot != -1 for dot in y)
if not tie: return False
return tie
def markWinningBoard(self, dots: list[list], player):
for dot in dots:
self.c4Board[dot[0]][dot[1]] = 2 if player == 0 else 3
@discord.ui.button(label='', style=discord.ButtonStyle.gray, emoji="⏪")
async def maxLeft(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id == self.players[self.playerTurn]:
if self.children[2].disabled: self.children[2].disabled = False
self.cursor = 0
self.replay.append("maxLeft")
if self.c4Board[5][self.cursor] != -1:
self.children[2].disabled = True
await interaction.response.edit_message(content=toDiscordString(self.c4Board, self.cursor, self.players[self.playerTurn], self.playerTurn, customEmoji1=self.emoji1, customEmoji2=self.emoji2), view=self)
@discord.ui.button(label='', style=discord.ButtonStyle.gray, emoji="◀️")
async def left(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id == self.players[self.playerTurn]:
if self.children[2].disabled: self.children[2].disabled = False
self.cursor -= 1 if self.cursor > 0 else 0
self.replay.append("left")
if self.c4Board[5][self.cursor] != -1:
self.children[2].disabled = True
await interaction.response.edit_message(content=toDiscordString(self.c4Board, self.cursor, self.players[self.playerTurn], self.playerTurn, customEmoji1=self.emoji1, customEmoji2=self.emoji2), view=self)
@discord.ui.button(label='', style=discord.ButtonStyle.blurple, emoji="🔽")
async def add(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id == self.players[self.playerTurn]:
if self.children[2].disabled: self.children[2].disabled = False
self.addTurn()
self.c4Board = addToken(self.c4Board, self.cursor, self.playerTurn)
hasWin = self.checkConnect4Winner(self.playerTurn)
tie = self.checkTie()
if not hasWin and not tie:
if self.c4Board[5][self.cursor] != -1:
self.children[2].disabled = True
self.replay.append("add")
await interaction.response.edit_message(content=toDiscordString(self.c4Board, self.cursor, self.players[self.playerTurn], self.playerTurn, customEmoji1=self.emoji1, customEmoji2=self.emoji2), view=self)
else:
self.playerTurn = not self.playerTurn
for child in self.children:
child.disabled = True
self.replay.append("add")
await interaction.response.edit_message(content=toDiscordString(self.c4Board, self.cursor, self.players[self.playerTurn], self.playerTurn, customEmoji1=self.emoji1, customEmoji2=self.emoji2, hasWon=hasWin, hasTied=tie, replay=self.replay), view=self)
self.stop()
@discord.ui.button(label='', style=discord.ButtonStyle.gray, emoji="▶️")
async def right(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id == self.players[self.playerTurn]: