-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2034 lines (1710 loc) · 83.6 KB
/
Copy pathbot.py
File metadata and controls
2034 lines (1710 loc) · 83.6 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
"""
bot.py — Main entry point for Herald, the DM's right hand.
Slash command groups:
/campaign – Create, list, schedule, delete campaigns
/party – Add, remove, rename players; view stats
/session – Create, list, ping, cancel, complete sessions
/rsvp – Quick RSVP shorthand
/item – Create, edit, delete, inspect homebrew items
/inventory – Give, remove, transfer, equip items; view player bags
/translate – Translate text between D&D languages
/forge – AI-powered homebrew item generation (Claude API)
/lore – AI-powered world-building generation (Claude API)
"""
import os
import json
import discord
from discord import app_commands
from discord.ext import commands
from datetime import datetime
from zoneinfo import ZoneInfo
from dotenv import load_dotenv
import database as db
from scheduler import RSVPView, build_rsvp_embed, setup as setup_scheduler
from languages import translate, translate_to, translate_from, get_languages
import claude_api
import ai_backend
import pdf_parser
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
raise RuntimeError("DISCORD_TOKEN not set. Copy .env.example to .env and fill it in.")
# ─── Bot Setup ───────────────────────────────────────────────────────────────
intents = discord.Intents.default()
intents.members = True
intents.message_content = False
bot = commands.Bot(command_prefix="!", intents=intents)
async def resolve_campaign_id(interaction: discord.Interaction, campaign_id: int = None) -> int | None:
"""
Auto-resolve campaign_id. If None:
- In a server: use the only campaign in that guild, or prompt if multiple.
- In DMs: use the only campaign the user belongs to, or prompt if multiple.
Returns the resolved ID or None (with an error message sent to the user).
"""
if campaign_id is not None:
return campaign_id
# In a server — look up by guild
if interaction.guild_id:
campaigns = db.get_campaigns_for_guild(interaction.guild_id)
else:
# In DMs — look up by user (as DM or player)
campaigns = db.get_campaigns_for_user(interaction.user.id)
if len(campaigns) == 1:
return campaigns[0]["id"]
elif len(campaigns) == 0:
if interaction.guild_id:
await interaction.response.send_message(
"No campaigns found. Create one with `/campaign create`.", ephemeral=True
)
else:
await interaction.response.send_message(
"No campaigns found for your account. Use Herald in your server first to set up a campaign.",
ephemeral=True,
)
return None
else:
names = "\n".join(f"• **{c['name']}** (ID: {c['id']})" for c in campaigns)
await interaction.response.send_message(
f"Multiple campaigns found — please specify `campaign_id`:\n{names}",
ephemeral=True,
)
return None
@bot.event
async def on_ready():
db.init_db()
await setup_scheduler(bot)
sessions = db.get_all_upcoming_sessions()
for s in sessions:
bot.add_view(RSVPView(s["id"]))
synced = await bot.tree.sync()
print(f"✅ {bot.user} is online — synced {len(synced)} commands.")
# ═════════════════════════════════════════════════════════════════════════════
# CAMPAIGN COMMANDS
# ═════════════════════════════════════════════════════════════════════════════
campaign_group = app_commands.Group(name="campaign", description="Manage your D&D campaigns")
@campaign_group.command(name="create", description="Create a new campaign in this channel")
@app_commands.describe(name="Name of your campaign")
async def campaign_create(interaction: discord.Interaction, name: str):
campaign_id = db.create_campaign(
guild_id=interaction.guild_id,
channel_id=interaction.channel_id,
name=name,
dm_user_id=interaction.user.id,
)
await interaction.response.send_message(
f"🏰 **Campaign created!**\n\n"
f"**{name}** (ID: `{campaign_id}`)\n"
f"DM: {interaction.user.mention}\n"
f"Channel: {interaction.channel.mention}\n\n"
f"Next steps:\n"
f"• `/party add {campaign_id} @player`\n"
f"• `/campaign schedule {campaign_id} friday 19:00`"
)
@campaign_group.command(name="list", description="List all campaigns in this server")
async def campaign_list(interaction: discord.Interaction):
campaigns = db.get_campaigns_for_guild(interaction.guild_id)
if not campaigns:
await interaction.response.send_message("No campaigns yet. Create one with `/campaign create`!")
return
embed = discord.Embed(title="📜 Campaigns", color=0x7C3AED)
for c in campaigns:
players = db.get_players(c["id"])
schedule = "Not set"
if c["schedule_day"]:
freq = c.get("repeat_frequency", "weekly")
freq_label = {"weekly": "Weekly", "biweekly": "Biweekly", "monthly": "Monthly"}.get(freq, freq)
schedule = f"{freq_label} — {c['schedule_day'].title()}s at {c['schedule_time']} ({c['schedule_tz']})"
if c["auto_schedule"]:
ahead = c.get("sessions_ahead", 1)
schedule += f" 🔄 ({ahead} ahead)"
ping_info = (
f"Initial: {c['ping_days_before']}d before"
f" | Midweek: {'✅' if c['midweek_enabled'] else '❌'}"
f" | Follow-ups: {c['followup_count']}x every {c['followup_interval_hours']}h"
f" | Final: {c['reminder_hours']}h before"
)
embed.add_field(
name=f"{c['name']} (ID: {c['id']})",
value=(
f"DM: <@{c['dm_user_id']}>\n"
f"Players: {len(players)}\n"
f"Schedule: {schedule}\n"
f"Pings: {ping_info}"
),
inline=False,
)
await interaction.response.send_message(embed=embed)
@campaign_group.command(name="schedule", description="Set the recurring game schedule and ping timing")
@app_commands.describe(
campaign_id="Campaign ID",
day="Day of the week (e.g., friday)",
time="Time in 24h format (e.g., 19:00)",
timezone="Timezone (default: America/Denver)",
repeat="How often sessions repeat (default: weekly)",
sessions_ahead="How many future sessions to auto-create (default: 1)",
start_date="First session date to anchor the schedule (e.g., 2026-04-24)",
ping_days="Days before session to send first ping (default: 3)",
midweek="Send a midweek status check-in (default: True)",
followup_count="Number of follow-up pings to non-responders (default: 1)",
followup_interval="Hours between follow-up pings (default: 24)",
reminder_hours="Hours before session to send final reminder (default: 4)",
auto="Automatically create sessions (default: True)",
)
@app_commands.choices(
day=[
app_commands.Choice(name=d.title(), value=d)
for d in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
],
repeat=[
app_commands.Choice(name="Weekly", value="weekly"),
app_commands.Choice(name="Biweekly (every 2 weeks)", value="biweekly"),
app_commands.Choice(name="Monthly (same weekday each month)", value="monthly"),
],
)
async def campaign_schedule(
interaction: discord.Interaction,
campaign_id: int,
day: str,
time: str,
timezone: str = "America/Denver",
repeat: str = "weekly",
sessions_ahead: int = 1,
start_date: str = None,
ping_days: int = 3,
midweek: bool = True,
followup_count: int = 1,
followup_interval: int = 24,
reminder_hours: int = 4,
auto: bool = True,
):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can change the schedule.", ephemeral=True)
return
try:
ZoneInfo(timezone)
except Exception:
await interaction.response.send_message(f"Invalid timezone: `{timezone}`", ephemeral=True)
return
sessions_ahead = max(1, min(sessions_ahead, 8)) # Clamp to 1-8
# Validate and parse start_date if provided
parsed_start = None
if start_date:
try:
tz_obj = ZoneInfo(timezone)
parsed_start = datetime.strptime(start_date, "%Y-%m-%d").replace(
hour=int(time.split(":")[0]),
minute=int(time.split(":")[1]),
tzinfo=tz_obj,
)
start_date_iso = parsed_start.isoformat()
except ValueError:
await interaction.response.send_message(
"Invalid start date format. Use `YYYY-MM-DD` (e.g., `2026-04-24`).",
ephemeral=True,
)
return
else:
start_date_iso = None
db.update_campaign_schedule(
campaign_id, day, time, timezone,
ping_days, midweek, followup_count, followup_interval, reminder_hours, auto,
repeat, sessions_ahead, start_date_iso,
)
freq_labels = {"weekly": "Every week", "biweekly": "Every 2 weeks", "monthly": "Monthly"}
embed = discord.Embed(
title=f"📅 Schedule Updated — {campaign['name']}",
color=0x7C3AED,
)
embed.add_field(name="Game Day", value=f"**{day.title()}** at **{time}**", inline=True)
embed.add_field(name="Repeat", value=freq_labels.get(repeat, repeat.title()), inline=True)
embed.add_field(name="Timezone", value=timezone, inline=True)
if parsed_start:
unix_ts = int(parsed_start.timestamp())
embed.add_field(name="Starting", value=f"<t:{unix_ts}:D>", inline=True)
embed.add_field(name="Sessions Ahead", value=str(sessions_ahead), inline=True)
embed.add_field(name="Auto-Schedule", value="🔄 Enabled" if auto else "Disabled", inline=True)
embed.add_field(name="Initial Ping", value=f"{ping_days} days before", inline=True)
embed.add_field(name="Midweek Check-in", value="✅ Enabled" if midweek else "❌ Disabled", inline=True)
embed.add_field(
name="Follow-up Pings",
value=f"{followup_count}x, every {followup_interval}h",
inline=True,
)
embed.add_field(name="Final Reminder", value=f"{reminder_hours} hours before", inline=True)
await interaction.response.send_message(embed=embed)
@campaign_group.command(name="delete", description="Delete a campaign permanently (DM only)")
@app_commands.describe(
campaign_id="Campaign ID to delete",
confirm="Type the campaign name to confirm deletion",
)
async def campaign_delete(interaction: discord.Interaction, campaign_id: int, confirm: str):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can delete a campaign.", ephemeral=True)
return
if confirm.strip() != campaign["name"]:
await interaction.response.send_message(
f"Confirmation didn't match. To delete this campaign, set `confirm` to the exact name: **{campaign['name']}**\n"
f"This action is permanent — all sessions, RSVPs, items, inventory, and character sheets will be lost.",
ephemeral=True,
)
return
db.delete_campaign(campaign_id)
await interaction.response.send_message(f"🗑️ Campaign **{campaign['name']}** has been deleted.")
@campaign_group.command(name="setting", description="Set your campaign's world/setting context for AI features")
@app_commands.describe(
campaign_id="Campaign ID",
setting="Describe your campaign world, themes, tone, house rules — anything the AI should know",
)
async def campaign_setting(interaction: discord.Interaction, campaign_id: int, setting: str):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can set the campaign context.", ephemeral=True)
return
db.update_campaign_setting(campaign_id, setting)
embed = discord.Embed(
title=f"🌍 Setting Updated — {campaign['name']}",
description=setting[:4000],
color=0x7C3AED,
)
embed.set_footer(text="This context will be included in all /forge and /lore AI generations.")
await interaction.response.send_message(embed=embed)
@campaign_group.command(name="setting_view", description="View the current campaign setting context")
@app_commands.describe(campaign_id="Campaign ID")
async def campaign_setting_view(interaction: discord.Interaction, campaign_id: int = None):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
setting = campaign.get("setting")
if not setting:
await interaction.response.send_message(
f"No setting configured for **{campaign['name']}** yet.\n"
f"Use `/campaign setting {campaign_id}` to add one.",
)
return
embed = discord.Embed(
title=f"🌍 Setting — {campaign['name']}",
description=setting[:4000],
color=0x7C3AED,
)
await interaction.response.send_message(embed=embed)
@campaign_group.command(name="backend", description="Set the default AI backend for this campaign")
@app_commands.describe(
campaign_id="Campaign ID (auto-detected if only one)",
backend="AI backend to use as the default for this campaign",
)
@app_commands.choices(backend=[
app_commands.Choice(name="☁️ Claude (cloud)", value="claude"),
app_commands.Choice(name="🖥️ LocalAI (self-hosted)", value="local"),
app_commands.Choice(name="System default", value="default"),
])
async def campaign_backend(interaction: discord.Interaction, backend: str, campaign_id: int = None):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can change the backend.", ephemeral=True)
return
# Validate the chosen backend is actually available
if backend == "claude" and not claude_api.API_KEY:
await interaction.response.send_message(
"Claude is not configured. Set `ANTHROPIC_API_KEY` in your `.env` file.",
ephemeral=True,
)
return
if backend == "local" and not ai_backend.local_api.is_configured():
await interaction.response.send_message(
"LocalAI is not configured. Set `LOCALAI_BASE_URL` and `LOCALAI_MODEL` in your `.env` file.",
ephemeral=True,
)
return
# "default" stores NULL — falls back to system priority logic
db_value = None if backend == "default" else backend
db.update_campaign_backend(campaign_id, db_value)
label = ai_backend.backend_label(backend) if backend != "default" else "System default"
await interaction.response.send_message(
f"🔧 AI backend for **{campaign['name']}** set to {label}.\n"
f"Individual commands can still override with the `backend` parameter."
)
bot.tree.add_command(campaign_group)
# ═════════════════════════════════════════════════════════════════════════════
# PARTY COMMANDS
# ═════════════════════════════════════════════════════════════════════════════
party_group = app_commands.Group(name="party", description="Manage campaign party members")
@party_group.command(name="add", description="Add a player to the campaign")
@app_commands.describe(
campaign_id="Campaign ID",
player="The player to add",
character_name="Their character's name (optional)",
)
async def party_add(
interaction: discord.Interaction,
campaign_id: int,
player: discord.Member,
character_name: str = None,
):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can manage the party.", ephemeral=True)
return
db.add_player(campaign_id, player.id, character_name)
char_text = f" as **{character_name}**" if character_name else ""
await interaction.response.send_message(
f"🗡️ {player.mention} has joined **{campaign['name']}**{char_text}!"
)
@party_group.command(name="remove", description="Remove a player from the campaign")
@app_commands.describe(campaign_id="Campaign ID", player="The player to remove")
async def party_remove(interaction: discord.Interaction, campaign_id: int, player: discord.Member):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can manage the party.", ephemeral=True)
return
db.remove_player(campaign_id, player.id)
await interaction.response.send_message(f"👋 {player.mention} has left **{campaign['name']}**.")
@party_group.command(name="rename", description="Set or change a player's character name")
@app_commands.describe(campaign_id="Campaign ID", player="The player", character_name="New character name")
async def party_rename(
interaction: discord.Interaction, campaign_id: int, player: discord.Member, character_name: str
):
db.update_character_name(campaign_id, player.id, character_name)
await interaction.response.send_message(f"📝 {player.mention} is now known as **{character_name}**.")
@party_group.command(name="list", description="Show all party members")
@app_commands.describe(campaign_id="Campaign ID")
async def party_list(interaction: discord.Interaction, campaign_id: int = None):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
players = db.get_players(campaign_id)
if not players:
await interaction.response.send_message("No players yet. Add some with `/party add`!")
return
embed = discord.Embed(
title=f"⚔️ Party — {campaign['name']}",
description=f"DM: <@{campaign['dm_user_id']}>",
color=0x7C3AED,
)
for i, p in enumerate(players, 1):
char = p["character_name"] or "No character set"
embed.add_field(name=f"{i}. <@{p['user_id']}>", value=char, inline=True)
await interaction.response.send_message(embed=embed)
@party_group.command(name="stats", description="View a player's attendance stats")
@app_commands.describe(campaign_id="Campaign ID", player="The player")
async def party_stats(interaction: discord.Interaction, campaign_id: int, player: discord.Member):
stats = db.get_player_stats(campaign_id, player.id)
total = stats.get("total_sessions", 0)
attended = stats.get("attended", 0) or 0
rate = f"{(attended / total * 100):.0f}%" if total > 0 else "N/A"
embed = discord.Embed(title=f"📊 {player.display_name} — Attendance", color=0x7C3AED)
embed.add_field(name="Sessions Played", value=str(total), inline=True)
embed.add_field(name="Attended", value=str(attended), inline=True)
embed.add_field(name="Attendance Rate", value=rate, inline=True)
embed.add_field(name="RSVP Yes", value=str(stats.get("rsvp_yes", 0) or 0), inline=True)
embed.add_field(name="RSVP No", value=str(stats.get("rsvp_no", 0) or 0), inline=True)
await interaction.response.send_message(embed=embed)
@party_group.command(name="sheet", description="Set character sheet details for AI context")
@app_commands.describe(
campaign_id="Campaign ID",
player="The player (DM can set for anyone, players can set their own)",
race="Character race (e.g., Half-Elf, Tiefling)",
char_class="Character class (e.g., Warlock 5 / Sorcerer 3)",
level="Character level",
background="Background (e.g., Sage, Criminal)",
backstory="Character backstory — as long as you want",
abilities="Key abilities, feats, and spells",
details="Anything else — personality traits, bonds, flaws, notable gear, etc.",
)
async def party_sheet(
interaction: discord.Interaction,
campaign_id: int,
player: discord.Member,
race: str = None,
char_class: str = None,
level: int = None,
background: str = None,
backstory: str = None,
abilities: str = None,
details: str = None,
):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
# Players can edit their own sheet; DM can edit anyone's
is_dm = campaign["dm_user_id"] == interaction.user.id
is_self = player.id == interaction.user.id
if not is_dm and not is_self:
await interaction.response.send_message(
"You can only edit your own character sheet. The DM can edit anyone's.",
ephemeral=True,
)
return
db.update_character_sheet(
campaign_id, player.id,
race=race, char_class=char_class, level=level,
background=background, backstory=backstory,
abilities=abilities, details=details,
)
# Count what was updated
updated = [k for k, v in {
"race": race, "class": char_class, "level": level,
"background": background, "backstory": backstory,
"abilities": abilities, "details": details,
}.items() if v is not None]
await interaction.response.send_message(
f"📝 Updated **{player.display_name}**'s character sheet: {', '.join(updated)}.\n"
f"This info will now be included in `/forge` and `/lore` AI generations."
)
@party_group.command(name="sheet_view", description="View a character's full sheet")
@app_commands.describe(campaign_id="Campaign ID", player="The player (defaults to yourself)")
async def party_sheet_view(
interaction: discord.Interaction,
player: discord.Member = None,
campaign_id: int = None,
):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
target = player or interaction.user
sheet = db.get_character_sheet(campaign_id, target.id)
if not sheet:
await interaction.response.send_message(
f"No character sheet found for {target.display_name} in this campaign.",
ephemeral=True,
)
return
campaign = db.get_campaign(campaign_id)
char_name = sheet.get("character_name") or "Unnamed"
embed = discord.Embed(
title=f"📋 {char_name} — Character Sheet",
description=f"Player: {target.mention} | Campaign: **{campaign['name']}**",
color=0x7C3AED,
)
if sheet.get("race"):
embed.add_field(name="Race", value=sheet["race"], inline=True)
if sheet.get("char_class"):
embed.add_field(name="Class", value=sheet["char_class"], inline=True)
if sheet.get("level"):
embed.add_field(name="Level", value=str(sheet["level"]), inline=True)
if sheet.get("background"):
embed.add_field(name="Background", value=sheet["background"], inline=True)
if sheet.get("backstory"):
embed.add_field(name="Backstory", value=sheet["backstory"][:1024], inline=False)
if sheet.get("abilities"):
embed.add_field(name="Abilities / Spells", value=sheet["abilities"][:1024], inline=False)
if sheet.get("details"):
embed.add_field(name="Additional Details", value=sheet["details"][:1024], inline=False)
# Show inventory summary
inventory = db.get_player_inventory(campaign_id, target.id)
if inventory:
inv_lines = []
for item in inventory[:10]:
emoji = RARITY_EMOJIS.get(item["rarity"], "⬜")
eq = " 🔧" if item["equipped"] else ""
qty = f" x{item['quantity']}" if item["quantity"] > 1 else ""
inv_lines.append(f"{emoji} {item['name']}{qty}{eq}")
if len(inventory) > 10:
inv_lines.append(f"*...and {len(inventory) - 10} more*")
embed.add_field(name="🎒 Inventory", value="\n".join(inv_lines), inline=False)
# Check completeness
fields = ["race", "char_class", "level", "background", "backstory", "abilities"]
filled = sum(1 for f in fields if sheet.get(f))
embed.set_footer(text=f"Sheet completeness: {filled}/{len(fields)} fields filled")
await interaction.response.send_message(embed=embed)
@party_group.command(name="import_sheet", description="Import a character sheet from a D&D Beyond PDF (URL or attachment)")
@app_commands.describe(
campaign_id="Campaign ID",
player="Player to import the sheet for",
url="D&D Beyond PDF URL (e.g., dndbeyond.com/sheet-pdfs/username_12345.pdf)",
attachment="Or attach the PDF file directly",
)
async def party_import(
interaction: discord.Interaction,
campaign_id: int,
player: discord.Member,
url: str = None,
attachment: discord.Attachment = None,
backend: str = None,
):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
# Permission check — DM can import for anyone, players can import their own
is_dm = campaign["dm_user_id"] == interaction.user.id
is_self = player.id == interaction.user.id
if not is_dm and not is_self:
await interaction.response.send_message(
"You can only import your own sheet. The DM can import for anyone.",
ephemeral=True,
)
return
if not url and not attachment:
await interaction.response.send_message(
"Provide either a `url` or attach a PDF file.\n"
"Example URL: `https://www.dndbeyond.com/sheet-pdfs/username_12345.pdf`",
ephemeral=True,
)
return
# Rate limit check
limit = claude_api.DM_RATE_LIMIT if is_dm else claude_api.PLAYER_RATE_LIMIT
allowed, wait = claude_api.rate_limiter.check(interaction.user.id, limit)
if not allowed:
await interaction.response.send_message(
f"⏳ Rate limit reached. Try again in ~{wait // 60} minutes.",
ephemeral=True,
)
return
await interaction.response.defer(thinking=True)
try:
# ── Step 1: Render PDF pages as images ──
if url:
page_images = await pdf_parser.pdf_to_images_from_url(url)
else:
if not attachment.filename.lower().endswith(".pdf"):
await interaction.followup.send("Attachment must be a PDF file.", ephemeral=True)
return
pdf_bytes = await attachment.read()
page_images = await pdf_parser.pdf_to_images_from_bytes(pdf_bytes)
if not page_images:
await interaction.followup.send(
"Couldn't render the PDF. Make sure it's a valid D&D Beyond character sheet export.",
ephemeral=True,
)
return
# ── Step 2: Send images to vision API for parsing ──
backend_choice = ai_backend.resolve_backend(campaign_id, backend)
result = await ai_backend.parse_character_pdf(page_images, backend=backend_choice)
claude_api.rate_limiter.record(interaction.user.id)
# ── Step 3: Save to database ──
char_name = result.get("character_name")
if char_name:
db.update_character_name(campaign_id, player.id, char_name)
db.update_character_sheet(
campaign_id, player.id,
character_name=result.get("character_name"),
race=result.get("race"),
char_class=result.get("char_class"),
level=result.get("level"),
background=result.get("background"),
backstory=result.get("backstory"),
abilities=result.get("abilities"),
details=result.get("details"),
)
# ── Step 4: Show confirmation ──
embed = discord.Embed(
title=f"📥 Sheet Imported — {result.get('character_name', 'Unknown')}",
color=0x7C3AED,
)
if result.get("race"):
embed.add_field(name="Race", value=result["race"], inline=True)
if result.get("char_class"):
embed.add_field(name="Class", value=result["char_class"], inline=True)
if result.get("level"):
embed.add_field(name="Level", value=str(result["level"]), inline=True)
if result.get("background"):
embed.add_field(name="Background", value=result["background"], inline=True)
if result.get("backstory"):
preview = result["backstory"][:300]
if len(result["backstory"]) > 300:
preview += "..."
embed.add_field(name="Backstory", value=preview, inline=False)
if result.get("abilities"):
preview = result["abilities"][:300]
if len(result["abilities"]) > 300:
preview += "..."
embed.add_field(name="Abilities", value=preview, inline=False)
if result.get("details"):
preview = result["details"][:300]
if len(result["details"]) > 300:
preview += "..."
embed.add_field(name="Details", value=preview, inline=False)
embed.set_footer(
text=f"Imported for {player.display_name} • Campaign: {campaign['name']} • "
f"Use /party sheet_view to see the full sheet"
)
await interaction.followup.send(
f"✅ **{result.get('character_name', 'Character')}** imported successfully!",
embed=embed,
)
except json.JSONDecodeError:
await interaction.followup.send(
"Claude couldn't parse the sheet into a clean format — try again or enter manually with `/party sheet`.",
ephemeral=True,
)
except ValueError as e:
await interaction.followup.send(f"PDF error: {str(e)[:300]}", ephemeral=True)
except Exception as e:
await interaction.followup.send(
f"Import failed: `{str(e)[:300]}`\n\nYou can still enter the sheet manually with `/party sheet`.",
ephemeral=True,
)
bot.tree.add_command(party_group)
# ═════════════════════════════════════════════════════════════════════════════
# SESSION COMMANDS
# ═════════════════════════════════════════════════════════════════════════════
session_group = app_commands.Group(name="session", description="Manage game sessions")
@session_group.command(name="create", description="Manually create an upcoming session")
@app_commands.describe(
campaign_id="Campaign ID",
date="Date and time (e.g., 2026-04-18 19:00)",
title="Optional title for this session",
)
async def session_create(
interaction: discord.Interaction, campaign_id: int, date: str, title: str = None
):
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
try:
tz = ZoneInfo(campaign["schedule_tz"] or "America/Denver")
dt = datetime.strptime(date, "%Y-%m-%d %H:%M").replace(tzinfo=tz)
except ValueError:
await interaction.response.send_message(
"Invalid date format. Use `YYYY-MM-DD HH:MM` (e.g., `2026-04-18 19:00`)",
ephemeral=True,
)
return
# Reject sessions in the past
if dt < datetime.now(tz):
await interaction.response.send_message(
f"That date is in the past. Please choose a future date.",
ephemeral=True,
)
return
session_id = db.create_session(campaign_id, dt.isoformat(), title)
unix_ts = int(dt.timestamp())
await interaction.response.send_message(
f"📅 **Session #{session_id} created!**\n"
f"Campaign: **{campaign['name']}**\n"
f"When: <t:{unix_ts}:F> (<t:{unix_ts}:R>)\n"
f"{f'Title: **{title}**' if title else ''}\n\n"
f"Use `/session ping {session_id}` to send the attendance check now."
)
@session_group.command(name="list", description="Show upcoming sessions")
@app_commands.describe(campaign_id="Campaign ID")
async def session_list(interaction: discord.Interaction, campaign_id: int = None):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
sessions = db.get_upcoming_sessions(campaign_id)
if not sessions:
await interaction.response.send_message("No upcoming sessions.")
return
embed = discord.Embed(title=f"📅 Upcoming — {campaign['name']}", color=0x7C3AED)
for s in sessions:
dt = datetime.fromisoformat(s["session_date"])
unix_ts = int(dt.timestamp())
rsvps = db.get_rsvps(s["id"])
confirmed = sum(1 for r in rsvps if r["response"] == "yes")
total = len(rsvps)
title_text = s["title"] or f"Session #{s['id']}"
ping_status = "📭 Not pinged"
if s["ping_sent"]:
ping_status = f"📬 Pinged (follow-ups: {s['reminders_sent']})"
if s["final_reminder_sent"]:
ping_status = "✅ All pings sent"
embed.add_field(
name=f"{title_text} (ID: {s['id']})",
value=f"<t:{unix_ts}:F>\n✅ {confirmed}/{total} confirmed | {ping_status}",
inline=False,
)
await interaction.response.send_message(embed=embed)
@session_group.command(name="ping", description="Manually ping for attendance (or re-ping non-responders)")
@app_commands.describe(session_id="Session ID")
async def session_ping(interaction: discord.Interaction, session_id: int):
session = db.get_session(session_id)
if not session:
await interaction.response.send_message("Session not found.", ephemeral=True)
return
campaign = db.get_campaign(session["campaign_id"])
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message(
"Only the DM can manually ping for attendance.", ephemeral=True,
)
return
rsvps = db.get_rsvps(session_id)
pending = db.get_pending_rsvps(session_id)
embed = build_rsvp_embed(session, rsvps, campaign["name"], interaction.client)
view = RSVPView(session_id)
if pending:
mentions = " ".join(f"<@{r['user_id']}>" for r in pending)
await interaction.response.send_message(
f"🎲 **Roll call, adventurers!** 🎲\n{mentions}\n\n"
f"Your presence is requested — respond below!",
embed=embed,
view=view,
)
else:
await interaction.response.send_message(
"Everyone has responded! Here's the current status:",
embed=embed,
view=view,
)
db.mark_ping_sent(session_id)
@session_group.command(name="status", description="Check RSVP status for a session")
@app_commands.describe(session_id="Session ID")
async def session_status(interaction: discord.Interaction, session_id: int):
session = db.get_session(session_id)
if not session:
await interaction.response.send_message("Session not found.", ephemeral=True)
return
campaign = db.get_campaign(session["campaign_id"])
rsvps = db.get_rsvps(session_id)
embed = build_rsvp_embed(session, rsvps, campaign["name"], interaction.client)
await interaction.response.send_message(embed=embed)
@session_group.command(name="cancel", description="Cancel a session")
@app_commands.describe(session_id="Session ID")
async def session_cancel(interaction: discord.Interaction, session_id: int):
session = db.get_session(session_id)
if not session:
await interaction.response.send_message("Session not found.", ephemeral=True)
return
campaign = db.get_campaign(session["campaign_id"])
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can cancel sessions.", ephemeral=True)
return
db.update_session_status(session_id, "cancelled")
players = db.get_players(session["campaign_id"])
mentions = " ".join(f"<@{p['user_id']}>" for p in players)
await interaction.response.send_message(
f"🚫 **Session #{session_id} has been cancelled.**\n{mentions}\n"
f"The quest is postponed, adventurers. Rest up!"
)
@session_group.command(name="complete", description="Mark a session as completed and log attendance")
@app_commands.describe(session_id="Session ID")
async def session_complete(interaction: discord.Interaction, session_id: int):
session = db.get_session(session_id)
if not session:
await interaction.response.send_message("Session not found.", ephemeral=True)
return
campaign = db.get_campaign(session["campaign_id"])
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can complete sessions.", ephemeral=True)
return
db.update_session_status(session_id, "completed")
rsvps = db.get_rsvps(session_id)
for r in rsvps:
db.log_attendance(session_id, r["user_id"], r["response"] == "yes")
await interaction.response.send_message(
f"✅ **Session #{session_id} marked as complete!**\n"
f"Attendance has been logged based on RSVPs. "
f"Use `/party stats` to view attendance records."
)
@session_group.command(name="clear", description="Delete all upcoming sessions and start fresh (DM only)")
@app_commands.describe(campaign_id="Campaign ID (auto-detected if only one)")
async def session_clear(interaction: discord.Interaction, campaign_id: int = None):
campaign_id = await resolve_campaign_id(interaction, campaign_id)
if campaign_id is None:
return
campaign = db.get_campaign(campaign_id)
if not campaign:
await interaction.response.send_message("Campaign not found.", ephemeral=True)
return
if campaign["dm_user_id"] != interaction.user.id:
await interaction.response.send_message("Only the DM can clear sessions.", ephemeral=True)
return
count = db.clear_sessions(campaign_id)
await interaction.response.send_message(
f"🗑️ Cleared **{count} upcoming session{'s' if count != 1 else ''}** from **{campaign['name']}**.\n"
f"The scheduler will create new ones based on your current schedule within 15 minutes."
)
bot.tree.add_command(session_group)
# ═════════════════════════════════════════════════════════════════════════════
# QUICK RSVP
# ═════════════════════════════════════════════════════════════════════════════
@bot.tree.command(name="rsvp", description="Quickly RSVP to a session")
@app_commands.describe(session_id="Session ID", response="Your response")