Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
5040 lines (4563 loc) · 234 KB
/
Copy pathbot.py
File metadata and controls
5040 lines (4563 loc) · 234 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 discord
from discord import app_commands
from discord import Interaction
from discord.ext import commands
from discord.ui import View, Select, select, Button
import requests
import json
import os
import io
import asyncio
import aiohttp
from dotenv import load_dotenv
from discord import ui, TextChannel, Embed
from typing import Optional, List, Dict
import datetime
load_dotenv()
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
# --- SUPABASE CONFIG ---
SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY")
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_TABLE = "server_config"
ACTIVITY_LOGS_TABLE = "activity_logs"
AUTO_SHIFT_TABLE = "auto_shift"
SUPABASE_HEADERS = {
"apikey": SUPABASE_API_KEY,
"Authorization": f"Bearer {SUPABASE_API_KEY}",
"Content-Type": "application/json"
}
# Active host-shift guilds (only these guilds have auto-shift polling)
active_host_shift_guilds = set()
# --- redact secret ---
def redact_secret(value: str, show_start: int = 6, show_end: int = 4) -> str:
try:
if not value or not isinstance(value, str):
return "<redacted>"
if len(value) <= (show_start + show_end + 4):
return "<redacted>"
return f"{value[:show_start]}...{value[-show_end:]}"
except Exception:
return "<redacted>"
# --- Database Function ---
def init_db():
pass
def load_config(guild_id):
url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?guild_id=eq.{guild_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return None
data = resp.json()
if not data:
return None
row = data[0]
announce_roles = json.loads(row["announce_roles"]) if row.get("announce_roles") else []
config = {
"api_key": row.get("api_key"),
"announce_roles": announce_roles,
"updates_channel": row.get("updates_channel"),
"logs_channel": row.get("logs_channel"),
"ingame_perms": row.get("ingame_perms"),
"server_code": row.get("server_code"),
"session_ping": row.get("session_ping"),
"session_perms": row.get("session_perms"),
"session_channel": row.get("session_channel"),
"welcoming_channel": row.get("welcoming_channel"),
"welcome_text": row.get("welcome_text"),
"webhook_url": row.get("webhook_url"),
"premium_server": row.get("premium_server"),
"session_ssu_message": row.get("session_ssu_message"),
"session_ssu_color": row.get("session_ssu_color"),
"session_ssd_message": row.get("session_ssd_message"),
"session_ssd_color": row.get("session_ssd_color"),
"session_low_message": row.get("session_low_message"),
"session_low_color": row.get("session_low_color"),
"session_cancel_message": row.get("session_cancel_message"),
"session_cancel_color": row.get("session_cancel_color"),
"session_ssu_banner": row.get("session_ssu_banner"),
"session_ssd_banner": row.get("session_ssd_banner"),
"modmail_enabled": row.get("modmail_enabled"),
"modmail_category_id": row.get("modmail_category_id"),
"modmail_staff_role_ids": row.get("modmail_staff_role_ids"),
"modmail_log_channel_id": row.get("modmail_log_channel_id")
}
return config
def is_premium_server_config(guild_id: int) -> bool:
config = load_config(guild_id)
if not config:
return False
return str(config.get("premium_server", "No")).lower() == "yes"
# --- Reaction Roles Supabase helpers ---
REACT_TABLE = "reaction_roles"
def supabase_get_reaction_roles_by_guild(guild_id: int):
try:
url = f"{SUPABASE_URL}/rest/v1/{REACT_TABLE}?guild_id=eq.{guild_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return []
return resp.json()
except Exception:
return []
def supabase_get_reaction_roles_by_message(message_id: int):
try:
url = f"{SUPABASE_URL}/rest/v1/{REACT_TABLE}?message_id=eq.{message_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return []
return resp.json()
except Exception:
return []
def supabase_insert_reaction_role(payload: dict):
try:
url = f"{SUPABASE_URL}/rest/v1/{REACT_TABLE}"
resp = requests.post(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
return resp.status_code in (200, 201)
except Exception:
return False
def supabase_delete_reaction_role_by_id(row_id: int):
try:
url = f"{SUPABASE_URL}/rest/v1/{REACT_TABLE}?id=eq.{row_id}"
resp = requests.delete(url, headers=SUPABASE_HEADERS)
return resp.status_code in (200, 204)
except Exception:
return False
# --- Activity Logs Supabase helpers ---
def supabase_get_activity_logs(guild_id: int):
try:
url = f"{SUPABASE_URL}/rest/v1/{ACTIVITY_LOGS_TABLE}?guild_id=eq.{guild_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return None
data = resp.json()
return data[0] if data else None
except Exception:
return None
def supabase_insert_activity_logs(guild_id: int, logs_channel_id: int, weekly_report_day: str):
try:
payload = {
"guild_id": str(guild_id),
"logs_channel_id": str(logs_channel_id),
"weekly_report_day": weekly_report_day
}
url = f"{SUPABASE_URL}/rest/v1/{ACTIVITY_LOGS_TABLE}"
resp = requests.post(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
return resp.status_code in (200, 201)
except Exception:
return False
# --- Auto Shift Supabase helpers ---
def supabase_get_auto_shift(discord_id: int):
try:
url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}?discord_id=eq.{discord_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return None
data = resp.json()
return data[0] if data else None
except Exception:
return None
def supabase_insert_or_update_auto_shift(discord_id: int, roblox_id: int, guild_id: int):
existing = supabase_get_auto_shift(discord_id)
if existing:
# Update guild_ids and activities
guild_ids = existing.get("guild_ids", "").split(",") if existing.get("guild_ids") else []
activities = existing.get("activities", "").split(",") if existing.get("activities") else []
if str(guild_id) not in guild_ids:
guild_ids.append(str(guild_id))
activities.append("0") # Initialize activity to 0
payload = {
"guild_ids": ",".join(guild_ids),
"activities": ",".join(activities)
}
url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}?discord_id=eq.{discord_id}"
resp = requests.patch(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
return resp.status_code in (200, 204)
else:
# Insert new
payload = {
"discord_id": str(discord_id),
"roblox_id": str(roblox_id),
"guild_ids": str(guild_id),
"activities": "0"
}
url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}"
resp = requests.post(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
return resp.status_code in (200, 201)
def supabase_update_activity(discord_id: int, guild_id: int, additional_seconds: int):
existing = supabase_get_auto_shift(discord_id)
if not existing:
return False
guild_ids = existing.get("guild_ids", "").split(",")
activities = existing.get("activities", "").split(",")
try:
idx = guild_ids.index(str(guild_id))
activities[idx] = str(int(activities[idx]) + additional_seconds)
payload = {"activities": ",".join(activities)}
url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}?discord_id=eq.{discord_id}"
resp = requests.patch(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
return resp.status_code in (200, 204)
except (ValueError, IndexError):
return False
def supabase_reset_weekly_activities(guild_id: int):
# Get all users linked to this guild and reset their activity for this guild
try:
url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}?guild_ids=like.*{guild_id}*"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
return
data = resp.json()
for record in data:
guild_ids = record.get("guild_ids", "").split(",")
activities = record.get("activities", "").split(",")
try:
idx = guild_ids.index(str(guild_id))
activities[idx] = "0"
payload = {"activities": ",".join(activities)}
update_url = f"{SUPABASE_URL}/rest/v1/{AUTO_SHIFT_TABLE}?discord_id=eq.{record['discord_id']}"
requests.patch(update_url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
except (ValueError, IndexError):
pass
except Exception:
pass
async def save_config_to_db(interaction, session_id):
session = config_sessions.get(session_id)
if not session:
return
payload = {
"guild_id": session.guild_id,
"api_key": session.api_key,
"announce_roles": json.dumps([session.announce_role.id]) if session.announce_role else json.dumps([]),
"updates_channel": session.updates_channel.id if session.updates_channel else None,
"logs_channel": session.logs_channel.id if session.logs_channel else None,
"ingame_perms": session.ingame_perms,
"server_code": session.server_code,
"session_ping": session.session_ping,
"session_perms": session.session_perms,
"session_channel": session.session_channel,
"welcoming_channel": session.welcoming_channel,
"welcome_text": session.welcome_text
}
url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}"
requests.post(url, headers=SUPABASE_HEADERS, data=json.dumps(payload))
config_sessions.pop(session_id, None)
await interaction.response.send_message("✅ Configuration saved.", ephemeral=True)
import psutil
# Giveaway participants cache
import threading
giveaway_participants_cache = {} # {message_id: set(user_ids)}
def remove_giveaway_cache_later(message_id, delay=86400):
def remove():
giveaway_participants_cache.pop(message_id, None)
t = threading.Timer(delay, remove)
t.daemon = True
t.start()
# Active modmail sessions: {channel_id: {user_id, guild_id, claimed_by}}
modmail_sessions: Dict[int, Dict] = {}
# Users currently in the DM modmail flow (to avoid re-entrant on_message handling)
modmail_dm_in_progress = set()
# Maintenance mode flag
maintenance_mode = False
OWNER_ID = 1099013081683738676
# Auto-shift tracking
active_shifts = {} # {roblox_id: {guild_id: start_time}}
weekly_activities = {} # {guild_id: {discord_id: total_seconds}}
# Permission check: Create Events
def has_create_events():
async def predicate(interaction: discord.Interaction):
perms = interaction.user.guild_permissions
if not getattr(perms, 'create_events', False):
await interaction.response.send_message("You need the 'Create Events' permission to use this command.", ephemeral=True)
return False
return True
return app_commands.check(predicate)
def get_cpu_usage():
"""Returns the current CPU usage percentage."""
return psutil.cpu_percent(interval=1)
async def send_modlog_and_dm(user, embed, logs_channel_id, guild):
if not logs_channel_id:
channel = None
else:
try:
channel = guild.get_channel(int(logs_channel_id))
except (ValueError, TypeError):
channel = None
if channel:
try:
await channel.send(embed=embed)
except Exception:
pass
try:
await user.send(embed=embed)
except Exception:
pass
from functools import wraps
import requests
def has_premium_server():
def decorator(func):
@wraps(func)
async def wrapper(interaction: discord.Interaction, *args, **kwargs):
guild_id = str(interaction.guild_id)
url = f"{SUPABASE_URL}/rest/v1/server_config?guild_id=eq.{guild_id}&select=premium_server"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code != 200:
await interaction.response.send_message(
"⚠️ Unable to check premium status. Please try again later.",
ephemeral=True
)
return
data = resp.json()
if not data or data[0].get("premium_server", "No") != "Yes":
await interaction.response.send_message(
"❌ This is a **Premium Feature**.\nBuy Premium to gain access.",
ephemeral=True
)
return
return await func(interaction, *args, **kwargs)
return wrapper
return decorator
# /purge command
def has_delete_messages():
async def predicate(interaction: discord.Interaction):
member = interaction.user
if not isinstance(member, discord.Member):
member = await interaction.guild.fetch_member(interaction.user.id)
if not member.guild_permissions.manage_messages and not member.guild_permissions.administrator:
await interaction.response.send_message("You need the 'Manage Messages' permission to use this command.", ephemeral=True)
return False
return True
return app_commands.check(predicate)
# /giveaway
import discord
from discord.ext import commands
from discord import app_commands
import asyncio
import random
import re
def parse_duration(duration_str: str) -> int:
match = re.match(r"(\d+)([mhdw])", duration_str.lower())
if not match:
return None
value, unit = int(match.group(1)), match.group(2)
if unit == "m":
return value * 60
elif unit == "h":
return value * 60 * 60
elif unit == "d":
return value * 60 * 60 * 24
elif unit == "w":
return value * 60 * 60 * 24 * 7
return None
import time
from discord.ui import View, Button
class GiveawayView(View):
def __init__(self, duration_seconds, winners, prize, host):
super().__init__(timeout=duration_seconds)
self.participants = set()
self.winners = winners
self.prize = prize
self.host = host
self.button = Button(label="Join (0)", style=discord.ButtonStyle.primary, custom_id="giveaway_join")
self.button.callback = self.join_leave
self.add_item(self.button)
self.message = None
self.end_time = int(time.time()) + duration_seconds
self.message_id = None # Initialize message_id to None
async def join_leave(self, interaction: discord.Interaction):
user_id = interaction.user.id
if user_id in self.participants:
self.participants.remove(user_id)
await interaction.response.send_message("You left the giveaway!", ephemeral=True)
else:
self.participants.add(user_id)
await interaction.response.send_message("You joined the giveaway!", ephemeral=True)
# Aggiorna la cache ogni volta che cambia
if self.message_id is not None:
giveaway_participants_cache[self.message_id] = set(self.participants)
await self.update_button()
async def update_button(self):
self.button.label = f"Join ({len(self.participants)})"
if self.message:
await self.message.edit(view=self)
async def on_timeout(self):
if self.message:
await self.message.edit(view=None)
from discord.ui import Modal, TextInput
class EmbedBuilderView(View):
def __init__(self, author_id, premium=False, presets=None):
super().__init__(timeout=600)
self.embed = discord.Embed(title="Custom Embed", description="Use Buttons to change text.", color=discord.Color.blurple())
self.author_id = author_id
self.premium = premium
self.presets = presets or []
self.selected_preset = None
self.channel_to_send = None
# Only add the select if there are presets
if self.presets:
options = [discord.SelectOption(label=p['name'], value=str(p['id'])) for p in self.presets if 'name' in p and 'id' in p]
select = Select(placeholder="Load Preset", custom_id="load_preset", options=options)
async def callback(interaction, select=select):
await self.load_preset(interaction, select)
select.callback = callback
self.add_item(select)
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == self.author_id
@discord.ui.button(label="Title", style=discord.ButtonStyle.primary, custom_id="edit_title")
async def edit_title(self, interaction: discord.Interaction, button: Button):
class TitleModal(Modal):
def __init__(self, current_title, parent_view):
super().__init__(title="Edit Title")
self.parent_view = parent_view
self.title_input = TextInput(label="Title", max_length=256, default=current_title or "")
self.add_item(self.title_input)
async def on_submit(self, modal_interaction: discord.Interaction):
self.parent_view.embed.title = self.title_input.value
# Try to edit the visible builder message first
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
# Acknowledge the modal interaction so it doesn't fail
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = TitleModal(self.embed.title, self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Description", style=discord.ButtonStyle.primary, custom_id="edit_desc")
async def edit_desc(self, interaction: discord.Interaction, button: Button):
class DescModal(Modal):
def __init__(self, parent_view):
super().__init__(title="Edit Description")
self.parent_view = parent_view
self.desc = TextInput(label="Description", style=discord.TextStyle.paragraph, max_length=2048)
self.add_item(self.desc)
async def on_submit(self, modal_interaction: discord.Interaction):
self.parent_view.embed.description = self.desc.value
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = DescModal(self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Color", style=discord.ButtonStyle.secondary, custom_id="edit_color")
async def edit_color(self, interaction: discord.Interaction, button: Button):
class ColorModal(Modal):
def __init__(self, current_color, parent_view):
super().__init__(title="Edit Color (HEX)")
self.parent_view = parent_view
hex_val = f"#{current_color:06X}" if isinstance(current_color, int) else (str(current_color) if current_color else "#5865F2")
self.color_input = TextInput(label="HEX Color", placeholder="#5865F2", max_length=7, default=hex_val)
self.add_item(self.color_input)
async def on_submit(self, modal_interaction: discord.Interaction):
try:
self.parent_view.embed.color = discord.Color(int(self.color_input.value.replace('#', ''), 16))
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Color updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
except Exception:
try:
await modal_interaction.response.send_message("Invalid color! Use HEX format.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
current_color = self.embed.color.value if self.embed.color else None
modal = ColorModal(current_color, self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Author", style=discord.ButtonStyle.secondary, custom_id="edit_author")
async def edit_author(self, interaction: discord.Interaction, button: Button):
current_author = self.embed.author.name if self.embed.author else ""
current_icon = self.embed.author.icon_url if self.embed.author and self.embed.author.icon_url else ""
class AuthorModal(Modal):
def __init__(self, author, icon, parent_view):
super().__init__(title="Edit Author")
self.parent_view = parent_view
self.author_input = TextInput(label="Author", max_length=256, default=author or "")
self.icon_url_input = TextInput(label="Author Icon URL", required=False, default=icon or "")
self.add_item(self.author_input)
self.add_item(self.icon_url_input)
async def on_submit(self, modal_interaction: discord.Interaction):
icon_url = self.icon_url_input.value.strip()
if icon_url:
self.parent_view.embed.set_author(name=self.author_input.value, icon_url=icon_url)
else:
self.parent_view.embed.set_author(name=self.author_input.value)
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = AuthorModal(current_author, current_icon, self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Footer", style=discord.ButtonStyle.secondary, custom_id="edit_footer")
async def edit_footer(self, interaction: discord.Interaction, button: Button):
current_footer = self.embed.footer.text if self.embed.footer else ""
current_icon = self.embed.footer.icon_url if self.embed.footer and self.embed.footer.icon_url else ""
class FooterModal(Modal):
def __init__(self, footer, icon, parent_view):
super().__init__(title="Edit Footer")
self.parent_view = parent_view
self.footer_input = TextInput(label="Footer", max_length=2048, default=footer or "")
self.icon_url_input = TextInput(label="Footer Icon URL", required=False, default=icon or "")
self.add_item(self.footer_input)
self.add_item(self.icon_url_input)
async def on_submit(self, modal_interaction: discord.Interaction):
icon_url = self.icon_url_input.value.strip()
if icon_url:
self.parent_view.embed.set_footer(text=self.footer_input.value, icon_url=icon_url)
else:
self.parent_view.embed.set_footer(text=self.footer_input.value)
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = FooterModal(current_footer, current_icon, self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Image", style=discord.ButtonStyle.secondary, custom_id="edit_image")
async def edit_image(self, interaction: discord.Interaction, button: Button):
class ImageModal(Modal):
def __init__(self, parent_view):
super().__init__(title="Edit Image")
self.parent_view = parent_view
self.url = TextInput(label="Image URL", max_length=1024)
self.add_item(self.url)
async def on_submit(self, modal_interaction: discord.Interaction):
self.parent_view.embed.set_image(url=self.url.value)
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = ImageModal(self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Thumbnail", style=discord.ButtonStyle.secondary, custom_id="edit_thumbnail")
async def edit_thumbnail(self, interaction: discord.Interaction, button: Button):
class ThumbModal(Modal):
def __init__(self, parent_view):
super().__init__(title="Edit Thumbnail")
self.parent_view = parent_view
self.url = TextInput(label="Thumbnail URL", max_length=1024)
self.add_item(self.url)
async def on_submit(self, modal_interaction: discord.Interaction):
self.parent_view.embed.set_thumbnail(url=self.url.value)
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = ThumbModal(self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Add Field", style=discord.ButtonStyle.secondary, custom_id="add_field")
async def add_field(self, interaction: discord.Interaction, button: Button):
class FieldModal(Modal):
def __init__(self, parent_view):
super().__init__(title="Add Field")
self.parent_view = parent_view
self.name = TextInput(label="Field Name", max_length=256)
self.value = TextInput(label="Field Value", style=discord.TextStyle.paragraph, max_length=1024)
self.inline = TextInput(label="Inline? (yes/no)", max_length=3, required=False)
self.add_item(self.name)
self.add_item(self.value)
self.add_item(self.inline)
async def on_submit(self, modal_interaction: discord.Interaction):
inline_flag = (self.inline.value.lower() == "yes" if self.inline.value else False)
self.parent_view.embed.add_field(name=self.name.value, value=self.value.value, inline=inline_flag)
try:
if hasattr(self.parent_view, 'message') and self.parent_view.message:
await self.parent_view.message.edit(embed=self.parent_view.embed, view=self.parent_view)
except Exception:
pass
try:
await modal_interaction.response.send_message("Embed updated.", ephemeral=True)
except Exception:
try:
await modal_interaction.response.defer()
except Exception:
pass
modal = FieldModal(self)
await interaction.response.send_modal(modal)
@discord.ui.button(label="Save Preset", style=discord.ButtonStyle.success, custom_id="save_preset")
async def save_preset(self, interaction: discord.Interaction, button: Button):
if not self.premium:
await interaction.response.send_message("Only Premium users can save presets.", ephemeral=True)
return
# Save preset to Supabase
preset_name = self.embed.title or "Preset"
data = {
"user_id": str(interaction.user.id),
"guild_id": str(interaction.guild_id),
"name": preset_name,
"embed_json": json.dumps(self.embed.to_dict())
}
url = f"{SUPABASE_URL}/rest/v1/embed_presets"
resp = requests.post(url, headers=SUPABASE_HEADERS, data=json.dumps(data))
if resp.status_code == 201:
await interaction.response.send_message(f"Preset '{preset_name}' saved!", ephemeral=True)
else:
await interaction.response.send_message("Error saving preset.", ephemeral=True)
# The select for loading presets will be added dynamically in __init__ only if there are presets
async def load_preset(self, interaction: discord.Interaction, select: Select):
preset_id = select.values[0]
url = f"{SUPABASE_URL}/rest/v1/embed_presets?id=eq.{preset_id}"
resp = requests.get(url, headers=SUPABASE_HEADERS)
if resp.status_code == 200 and resp.json():
preset = resp.json()[0]
self.embed = discord.Embed.from_dict(json.loads(preset["embed_json"]))
await interaction.response.defer()
await interaction.edit_original_response(embed=self.embed, view=self)
else:
await interaction.response.send_message("Error loading preset.", ephemeral=True)
@discord.ui.button(label="Send", style=discord.ButtonStyle.success, custom_id="send_embed")
async def send_embed(self, interaction: discord.Interaction, button: Button):
# New flow: ask the user to reply with the channel link where the embed should be sent.
prompt_embed = discord.Embed(
title="Where should I send this embed?",
description=("Please reply in this channel with the channel link or mention where you want me to send the embed.\n"
"Example: `#general`\n"
"You have 2 minutes to reply."),
color=discord.Color.blurple()
)
# Respond to the button interaction with the prompt (visible). This is the interaction response.
try:
await interaction.response.send_message(embed=prompt_embed)
prompt_msg = await interaction.original_response()
except Exception:
# If we can't send the prompt via interaction, attempt a fallback send in the channel
try:
prompt_msg = await interaction.channel.send(embed=prompt_embed)
except Exception as e:
try:
await interaction.response.send_message(f"❌ Could not ask for channel: {e}", ephemeral=True)
except Exception:
pass
return
def check(m: discord.Message):
return m.author.id == interaction.user.id and m.channel.id == (prompt_msg.channel.id if prompt_msg else interaction.channel.id)
try:
reply = await bot.wait_for('message', check=check, timeout=120)
except asyncio.TimeoutError:
try:
await prompt_msg.delete()
except Exception:
pass
try:
await interaction.followup.send("⏰ Timeout. Send cancelled.", ephemeral=True)
except Exception:
pass
return
# Parse channel id from reply
content = reply.content.strip()
channel_id = None
# channel mention
m = re.search(r"<#(\d+)>", content)
if m:
channel_id = int(m.group(1))
else:
# discord channel link
m = re.search(r"/channels/\d+/(\d+)", content)
if m:
channel_id = int(m.group(1))
else:
# plain id
if content.isdigit():
channel_id = int(content)
if not channel_id:
try:
await interaction.followup.send("❌ Could not parse a channel from your reply. Please provide a channel mention or link.", ephemeral=True)
except Exception:
pass
return
target = bot.get_channel(channel_id) or (interaction.guild.get_channel(channel_id) if interaction.guild else None)
if not target or not isinstance(target, TextChannel):
try:
await interaction.followup.send("❌ The specified channel was not found or is not a text channel.", ephemeral=True)
except Exception:
pass
return
# Attempt to send the embed
try:
await target.send(embed=self.embed)
except Exception as e:
try:
await interaction.followup.send(f"❌ Failed to send embed: {e}", ephemeral=True)
except Exception:
pass
return
# Clean up: delete builder message, the prompt, and the user's reply
try:
if hasattr(self, 'message') and self.message:
await self.message.delete()
except Exception:
pass
try:
await prompt_msg.delete()
except Exception:
pass
try:
await reply.delete()
except Exception:
pass
try:
await interaction.followup.send(f"✅ Embed sent to <#{channel_id}>", ephemeral=True)
except Exception:
pass
from discord.ui import View, Select
class ModmailServerSelect(View):
def __init__(self, user, mutual_guilds):
super().__init__(timeout=60)
options = [
discord.SelectOption(
label=guild.name,
value=str(guild.id),
description=f"Send a modmail to {guild.name}"
)
for guild in mutual_guilds
]
self.select = Select(placeholder="Select a server...", options=options, min_values=1, max_values=1)
self.select.callback = self.select_callback
self.add_item(self.select)
self.selected_guild_id = None
self.user = user
async def select_callback(self, interaction: discord.Interaction):
self.selected_guild_id = int(self.select.values[0])
await interaction.response.defer()
self.stop()
@bot.event
async def on_message(message):
# Ignore bot messages
if message.author.bot:
return
# If message is in a modmail staff channel, forward to user
if message.guild is not None:
session = modmail_sessions.get(message.channel.id)
if session:
user_id = session.get("user_id")
try:
user = await bot.fetch_user(user_id)
embed = discord.Embed(
title=f"Reply from {message.author.display_name}",
description=message.content or "(embed/attachment)",
color=discord.Color.blue()
)
embed.set_footer(text=f"{message.author} • {message.author.id}")
# include attachments if any (first one)
if message.attachments:
embed.set_image(url=message.attachments[0].url)
await user.send(embed=embed)
try:
await message.add_reaction("✅")
except Exception:
pass
except Exception as e:
print(f"Failed to forward staff message to user {user_id}: {e}")
try:
await message.channel.send("❌ Failed to send DM to the user.")
except Exception:
pass
return
# Only handle DMs to the bot from users (not in guilds)
if message.guild is not None:
return
# If the user already has an open modmail session, forward the DM to the existing staff channel
existing_session = None
for s in modmail_sessions.values():
try:
if s.get("user_id") == message.author.id:
existing_session = s
break
except Exception:
continue
if existing_session:
chan = bot.get_channel(existing_session.get("channel_id"))
if chan:
try:
embed = discord.Embed(
title=f"Message from {message.author.display_name}",
description=message.content or "(embed/attachment)",
color=discord.Color.blue()
)
embed.set_footer(text=f"{message.author} • {message.author.id}")
if message.attachments:
embed.set_image(url=message.attachments[0].url)
staff_msg = await chan.send(embed=embed)
# react on the staff post to mark it forwarded, and react to the user's DM
try:
await staff_msg.add_reaction("✅")
except Exception:
pass
try:
await message.add_reaction("✅")
except Exception:
pass
except Exception as e:
print(f"Failed to forward user DM to staff channel: {e}")
# Do NOT send a confirmation message for every forwarded DM — users can chat freely while ticket is open.
return
# If the user is currently inside the DM flow (prompted), ignore this on_message to avoid re-entrancy
if message.author.id in modmail_dm_in_progress:
return
# Show a loading embed while we gather configured servers (avoids sending multiple messages)
loading_embed = discord.Embed(title="Loading...", description="Searching for servers configured for modmail...", color=discord.Color.gold())
loading_msg = await message.channel.send(embed=loading_embed)
# Build list of guilds where the bot is present and modmail is enabled
candidate_guilds = []
for guild in bot.guilds:
try:
cfg = load_config(guild.id)
if cfg and str(cfg.get("modmail_enabled")).lower() in ("true", "1", "yes"):
candidate_guilds.append(guild)
except Exception as e:
print(f"Error loading config for guild {guild.name}: {e}")
continue
if not candidate_guilds:
no_embed = discord.Embed(title="No servers found", description="No servers configured for modmail were found.", color=discord.Color.red())
try:
await message.channel.send(embed=no_embed)
finally:
modmail_dm_in_progress.discard(message.author.id)
return
# Mark user as in-progress so reply messages do not re-trigger the flow
modmail_dm_in_progress.add(message.author.id)
# Edit the loading message into the prompt for server name
prompt_embed = discord.Embed(
title="Contact Staff",
description=("Please type the server name where you want to contact staff (partial name is fine).\n"
"You can also type `list` to see available servers. You have 2 minutes."),
# cd: 23378
color=discord.Color.blurple()
)
await message.channel.send(embed=prompt_embed)
def check(m):
return m.author.id == message.author.id and m.channel.id == message.channel.id
try:
reply = await bot.wait_for('message', check=check, timeout=120)
query = reply.content.strip()
except asyncio.TimeoutError:
try:
await message.channel.send("⏰ Timeout. Modmail cancelled.")
finally:
modmail_dm_in_progress.discard(message.author.id)
return
# If user asked for list, show available candidate servers (edit the loading_msg)
if query.lower() == 'list':
lines = [f"- {g.name} (ID: {g.id})" for g in candidate_guilds]
chunk = "\n".join(lines)
list_embed = discord.Embed(title="Available servers", description=chunk, color=discord.Color.blue())