-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
695 lines (569 loc) · 21.6 KB
/
bot.py
File metadata and controls
695 lines (569 loc) · 21.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
"""D&D HP Calculator Bot
This is the entry point of the application.
"""
# pylint: disable=C0103, W0622, E0237, R0913
import asyncio
import math
import os
import re
import time
from typing import List, Tuple
import disnake
from disnake.ext import commands
from dotenv import load_dotenv
from utils import constants, helper
from utils.classes import DndClass, Flags
# Load environment variables
load_dotenv()
command_prefix = commands.when_mentioned
description = "A bot for calculating your D&D 5e character's average hit points."
intents = disnake.Intents.default()
bot = commands.Bot(
case_insensitive=True,
command_prefix=command_prefix,
description=description,
help_command=None,
intents=intents,
)
##################
## HELP COMMAND ##
##################
@bot.command()
async def help(ctx: commands.Context):
"""Show a guide on how to use Valron"""
embed = await build_help_embed()
await bot_typing(ctx, 1)
await ctx.send(embed=embed)
@bot.slash_command()
async def help(inter: disnake.CommandInteraction):
"""Show a guide on how to use Valron"""
embed = await build_help_embed()
await inter.send(embed=embed)
async def build_help_embed() -> disnake.Embed:
"""Build the embed for the `help` command"""
embed = helper.embed_builder(
bot.user.name,
"Hello, my friend! I am Valron. Below is a guide on "
+ "how I can help you compute for your AL D&D 5e character's hit points.",
)
embed.add_field(
name="Command",
value="`/hp <con_modifier> <classA#/classB#/etc> [hp_mod1/hp_mod2/etc]`",
inline=False,
)
embed.add_field(name="Single Class Example", value="`/hp 3 fighter1`", inline=False)
embed.add_field(
name="Multiclass Example", value="`/hp 3 fighter1/barb2/paladin1`", inline=False
)
embed.add_field(
name="Example with HP modifiers",
value="`/hp 3 fighter1/barb2/paladin1 tough/hilldwarf`",
inline=False,
)
embed.set_footer(
text="/options - to see the list of supported classes and HP modifiers\n"
+ "/links - to view some helpful links"
)
return embed
#####################
## OPTIONS COMMAND ##
#####################
@bot.command()
async def options(ctx: commands.Context):
"""Show list of supported classes and HP modifiers"""
embed = await build_options_embed()
await bot_typing(ctx, 1)
await ctx.send(embed=embed)
@bot.slash_command()
async def options(inter: disnake.CommandInteraction):
"""Show list of supported classes and HP modifiers"""
embed = await build_options_embed()
await inter.send(embed=embed)
async def build_options_embed() -> disnake.Embed:
"""Build the embed for the `options` command"""
embed = helper.embed_builder(
bot.user.name,
"Hello, my friend! I am Valron. Here are the supported "
+ "classes and HP modifiers for your reference",
)
embed.add_field(
name="List of supported classes",
value=helper.alias_builder(constants.DND_ALIASES()),
inline=False,
)
embed.add_field(
name="List of supported HP modifiers",
value=helper.alias_builder(constants.HP_MOD_ALIASES()),
inline=False,
)
embed.set_footer(
text="/help - main help command\n" + "/links - to view some helpful links"
)
return embed
###################
## LINKS COMMAND ##
###################
@bot.command()
async def links(ctx: commands.Context):
"""Show invite link and means to support Valron's development"""
embed = await build_links_embed()
await bot_typing(ctx, 1)
await ctx.send(embed=embed)
@bot.slash_command()
async def links(inter: disnake.CommandInteraction):
"""Show invite link and means to support Valron's development"""
embed = await build_links_embed()
await inter.send(embed=embed)
async def build_links_embed() -> disnake.Embed:
"""Build the embed for the `links` command"""
embed = helper.embed_builder(
bot.user.name,
"Hello, my friend! I am Valron. My wife has compiled a "
+ "list of helpful links for you.",
)
embed.add_field(
name="Invite me to your server with this link",
value=f"[Click me!]({constants.DISCORD_INVITE_LINK})",
inline=False,
)
embed.add_field(
name="Find out what's new with me from the support discord server",
value=f"[Click me!]({constants.SUPPORT_SERVER_LINK})",
inline=False,
)
embed.add_field(
name="See how I was made",
value=f"[Click me!]({constants.GITHUB_LINK})",
inline=False,
)
embed.add_field(
name="Want to support me and my wife?",
value=f"Click any of these: [PayPal]({constants.PAYPAL_LINK}) "
+ f"| [Ko-Fi]({constants.KOFI_LINK}) | [GCash]({constants.GCASH_QR_CODE})",
inline=False,
)
embed.set_footer(
text="/help - main help command\n"
+ "/options - to see the list of supported classes and HP modifiers"
)
return embed
################
## HP COMMAND ##
################
@bot.command()
async def hp(
ctx: commands.Context,
con_modifier: int,
input_classes_and_levels: str,
input_hp_mods: str = None,
):
"""Calculate my character's HP"""
bot_reply = await build_hp_embed(
con_modifier, input_classes_and_levels, input_hp_mods, ctx=ctx
)
if bot_reply is not None:
await bot_typing(ctx, 1)
await ctx.send(bot_reply)
@bot.slash_command()
async def hp(
inter: disnake.CommandInteraction,
con_modifier: int = commands.Param(
name="constitution-modifier",
description="Your character's constitution modifier",
),
input_classes_and_levels: str = commands.Param(
name="classes-and-levels",
description="Your character's classes and levels (use `/help` for more info)",
),
input_hp_mods: str = commands.Param(
name="hp-modifiers",
description="Your character's HP modifiers (use `/help` for more info)",
default=None,
),
):
"""Calculate my character's HP"""
bot_reply = await build_hp_embed(
con_modifier, input_classes_and_levels, input_hp_mods, inter=inter
)
if bot_reply is not None:
await inter.send(bot_reply)
async def build_hp_embed(
con_modifier: int,
input_classes_and_levels: str,
input_hp_mods: str = None,
ctx: commands.Context = None,
inter: disnake.CommandInteraction = None,
) -> disnake.Embed:
"""Build the embed for the `hp` command"""
tic = time.perf_counter()
# Parse input
(classes_and_levels, flags) = await parse_input(
input_classes_and_levels, input_hp_mods, ctx=ctx, inter=inter
)
# Get base HP
(partial_hp, total_level) = calculate_base_hp(classes_and_levels, con_modifier)
# Apply HP modifiers
final_hp = apply_hp_mods(partial_hp, total_level, flags)
toc = time.perf_counter()
if constants.SHOW_PERF:
print(f"Performance: {toc - tic:0.4f} seconds")
# Send bot reply
if flags.no_error:
bot_reply = bot_reply_builder(
con_modifier,
classes_and_levels,
total_level,
final_hp,
flags,
ctx=ctx,
inter=inter,
)
# embed = helper.embed_builder(bot.user.name, bot_reply, show_thumbnail=False)
# embed.set_footer(
# text="?help - main help command\n"
# "?options - to see the list of supported classes and HP modifiers\n"
# "?links - to view some helpful links"
# )
return bot_reply
async def parse_input(
input_classes_and_levels: str,
input_hp_mods: str,
ctx: commands.Context = None,
inter: disnake.CommandInteraction = None,
):
"""Parses the input_classes_and_levels and input_hp_mods.
Args:
input_classes_and_levels (str): The input classes and levels.
input_hp_mods (str): The input HP modifiers.
ctx (disnake.ext.commands.Context): The context in which a command is being invoked under.
See [this](https://docs.disnake.dev/en/latest/ext/commands/api/context.html#disnake.ext.commands.Context) for more info.
Returns:
(list(Class, int), Flags): The first one is a list of tuples
wherein each element is the Class and level. The second
is the collection of HP modifier flags.
"""
flags = await parse_input_hp_mods(input_hp_mods, ctx=ctx, inter=inter)
return await parse_input_classes_and_levels(
input_classes_and_levels, flags, ctx=ctx, inter=inter
)
async def parse_input_hp_mods(
input_hp_mods: str,
ctx: commands.Context = None,
inter: disnake.CommandInteraction = None,
) -> Flags:
"""Parses the input_hp_mods into the Flags class.
Parameters
----------
input_hp_mods : str
The input HP modifiers.
ctx : commands.Context, optional
The context in which a command is being invoked under, by default None.
See [this](https://docs.disnake.dev/en/latest/ext/commands/api/context.html#disnake.ext.commands.Context) for more info.
inter : disnake.CommandInteraction, optional
The slash command interaction, by default None.
See [this](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.ApplicationCommandInteraction) for more info.
Returns
-------
Flags
The collection of HP modifier flags.
"""
flags = Flags(True, False, False, False)
# If there are input_hp_mods
if input_hp_mods:
input_hp_mods = input_hp_mods.lower()
char_hp_mods = input_hp_mods.split("/")
# For each char_hp_mod
for char_hp_mod in char_hp_mods:
# Check if valid char_hp_mod
if char_hp_mod in constants.HP_MODS():
if char_hp_mod in constants.HILLDWARF_MODS():
flags.is_hilldwarf = True
elif char_hp_mod in constants.BERSERKER_AXE_MODS():
flags.axe_attuned = True
elif char_hp_mod in constants.TOUGH_MODS():
flags.is_tough = True
# If not valid char_hp_mod
else:
unknown = f"`{char_hp_mod}` HP modifier"
if ctx:
await ctx.send((helper.valron_doesnt_know(unknown, ctx=ctx)))
if inter:
await inter.send((helper.valron_doesnt_know(unknown, inter=inter)))
flags.no_error = False
break
return flags
async def parse_input_classes_and_levels(
input_classes_and_levels: str,
flags: Flags,
ctx: commands.Context = None,
inter: disnake.CommandInteraction = None,
) -> Tuple[List[Tuple[DndClass, int]], Flags]:
"""Parses the input_classes_and_levels.
Parameters
----------
input_classes_and_levels : str
The input classes and levels.
flags : Flags
The collection of HP modifier flags.
ctx : commands.Context, optional
The context in which a command is being invoked under, by default None.
See [this](https://docs.disnake.dev/en/latest/ext/commands/api/context.html#disnake.ext.commands.Context) for more info.
inter : disnake.CommandInteraction, optional
The slash command interaction, by default None.
See [this](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.ApplicationCommandInteraction) for more info.
Returns
-------
Tuple[List[Tuple[DndClass, int]], Flags]
A tuple containing:
- (1) a list of tuples wherein each element is the DndClass and level
- (2) the collection of HP modifier flags
Raises
------
commands.MissingRequiredArgument
If there are no parsed_classes_and_levels.
"""
classes_and_levels = []
# List of word##
parsed_classes_and_levels = input_classes_and_levels.lower().split("/")
# If there are parsed_classes_and_levels
if parsed_classes_and_levels:
# For each parsed_class_and_level, get class and level
for parsed_class_and_level in parsed_classes_and_levels:
class_and_level = parsed_class_and_level.strip()
# If it follows word## pattern
regex = re.compile("([a-zA-Z]+)([0-9]+)")
if re.match(regex, class_and_level):
result = re.split(regex, class_and_level)
matched_dnd_class = result[1]
matched_level = int(result[2])
# If matched_dnd_class exists in list of supported D&D classes
dnd_class = helper.get_class(matched_dnd_class)
if dnd_class:
# Track class name and level
classes_and_levels.append((dnd_class, matched_level))
else:
unknown = f"`{matched_dnd_class}` class"
if ctx:
await ctx.send((helper.valron_doesnt_know(unknown, ctx=ctx)))
if inter:
await inter.send(
(helper.valron_doesnt_know(unknown, inter=inter))
)
flags.no_error = False
break
# If it does not follow word## pattern
else:
if ctx:
await ctx.send(
f"Oof! {ctx.author.mention}, my friend, "
+ "kindly check your classes and levels! "
+ f"You sent `{input_classes_and_levels}`. "
+ "It must look something like this `barb1/wizard2`. "
+ "My wife says to use `/help` for more information."
)
if inter:
await inter.send(
f"Oof! {inter.author.mention}, my friend, "
+ "kindly check your classes and levels! "
+ f"You sent `{input_classes_and_levels}`. "
+ "It must look something like this `barb1/wizard2`. "
+ "My wife says to use `/help` for more information."
)
flags.no_error = False
break
# If there are no parsed_classes_and_levels
else:
raise commands.MissingRequiredArgument
return (classes_and_levels, flags)
async def bot_typing(ctx: commands.Context, time: int):
"""Triggers 'Valron is typing...' in Discord.
Parameters
----------
ctx : commands.Context
The context in which a command is being invoked under.
See [this](https://docs.disnake.dev/en/latest/ext/commands/api/context.html#disnake.ext.commands.Context) for more info.
time : int
Number of seconds to wait.
"""
await ctx.trigger_typing()
await asyncio.sleep(time)
def calculate_base_hp(
classes_and_levels: List[Tuple[DndClass, int]], con_modifier: int
) -> Tuple[int, int]:
"""Calculates the base hit points given the classes, levels, and constitution modifier.
Parameters
----------
classes_and_levels : List[Tuple[DndClass, int]]
A list of tuples wherein each element is the class and corresponding level.
con_modifier : int
The constitution modifer.
Returns
-------
Tuple[int, int]
A tuple of the partial_hp and total character level.
"""
is_level_1 = True
current_hp = 0
total_level = 0
for class_and_level in classes_and_levels:
dnd_class = class_and_level[0]
level = class_and_level[1]
avg_hit_dice = math.floor(dnd_class.hit_die / 2) + 1
# For the base class
if is_level_1:
# On 1st level: max_hit_die + con_modifier
current_hp = current_hp + dnd_class.hit_die + con_modifier
# On every level above 1st: avg_hit_dice + con_modifier
current_hp = current_hp + ((avg_hit_dice + con_modifier) * (level - 1))
is_level_1 = False
# On every level above 1st: avg_hit_dice + con_modifier
else:
current_hp = current_hp + ((avg_hit_dice + con_modifier) * level)
# If matched_dnd_class is a Draconic Sorcerer
if dnd_class.name == "Draconic Sorcerer":
current_hp = current_hp + level
total_level = total_level + level
return (current_hp, total_level)
def apply_hp_mods(partial_hp: int, total_level: int, flags: Flags) -> int:
"""Calculates the hit points with the HP modifiers.
Parameters
----------
partial_hp : int
The base hit points.
total_level : int
The total character level.
flags : Flags
The collection of HP modifier flags.
Returns
-------
int
The hit points with the HP modifiers.
"""
if flags.is_hilldwarf:
partial_hp = partial_hp + total_level
if flags.axe_attuned:
partial_hp = partial_hp + total_level
if flags.is_tough:
partial_hp = partial_hp + (total_level * 2)
return partial_hp
def bot_reply_builder(
con_modifier: int,
classes_and_levels: List[Tuple[DndClass, int]],
total_level: int,
final_hp: int,
flags: Flags,
ctx: commands.Context = None,
inter: disnake.CommandInteraction = None,
) -> str:
"""Returns the formatted reply of the bot.
Parameters
----------
con_modifier : int
The constitution modifer.
classes_and_levels : List[Tuple[DndClass, int]]
A list of tuples wherein each element is the class and corresponding level.
total_level : int
The total character level.
final_hp : int
The calculated hit points.
flags : Flags
The collection of HP modifier flags.
ctx : commands.Context, optional
The context in which a command is being invoked under, by default None.
See [this](https://docs.disnake.dev/en/latest/ext/commands/api/context.html#disnake.ext.commands.Context) for more info.
inter : disnake.CommandInteraction, optional
The slash command interaction, by default None.
See [this](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.ApplicationCommandInteraction) for more info.
Returns
-------
str
Formatted reply of the bot.
"""
name = ""
if ctx:
name = ctx.author.mention
if inter:
name = inter.author.mention
if total_level > 20:
bot_reply = (
f"Oof! {name}, my friend, you have a level "
+ f"`{total_level}` character? My wife says to double check its "
+ "levels! But if you really want to know, a "
)
else:
bot_reply = f"{name}, my friend, a "
if flags.is_hilldwarf:
bot_reply = bot_reply + "`Hill Dwarf` "
bot_reply = (
bot_reply
+ f"`{helper.classes_and_levels_builder(classes_and_levels)}` character "
)
if flags.axe_attuned:
bot_reply = bot_reply + "`attuned to a Berserker Axe` "
bot_reply = bot_reply + f"with a Constitution modifier of `{con_modifier}` "
if flags.is_tough:
bot_reply = bot_reply + "and `Tough feat` "
bot_reply = bot_reply + f"has `{final_hp}` hit points."
# from disnake.errors import HTTPException
# guilds = os.getenv("GUILDS")
# member = os.getenv("MEMBER1")
# if guilds:
# if (str(ctx.guild.id) in guilds) and (con_modifier < 0):
# try:
# summon = await ctx.guild.fetch_member(int(member))
# if summon:
# bot_reply = (
# bot_reply
# + "\n\nOof! You have a negative Constitution modifier! "
# + f"My wife tells me that I should summon {summon.mention}!"
# )
# except HTTPException:
# pass
return bot_reply
########################
## DISCORD BOT EVENTS ##
########################
@bot.event
async def on_connect():
"""See https://discordpy.readthedocs.io/en/latest/api.html#event-reference"""
print(f"{bot.user.name} has connected to Discord!")
print(f"Connected to {len(bot.guilds)} Discord servers!")
await bot.change_presence(activity=helper.update_guild_counter(len(bot.guilds)))
@bot.event
async def on_ready():
"""See https://discordpy.readthedocs.io/en/latest/api.html#event-reference"""
print(f"{bot.user.name} is ready to serve!")
# print('Connected to the following Discord servers: ')
# for guild in bot.guilds:
# print(f' >> {guild.name}')
@bot.event
async def on_guild_join(guild):
"""See https://discordpy.readthedocs.io/en/latest/api.html#event-reference"""
# print(f"Joined {guild.name}!")
await bot.change_presence(activity=helper.update_guild_counter(len(bot.guilds)))
@bot.event
async def on_guild_remove(guild):
"""See https://discordpy.readthedocs.io/en/latest/api.html#event-reference"""
# print(f"Left {guild.name}...")
await bot.change_presence(activity=helper.update_guild_counter(len(bot.guilds)))
@bot.event
async def on_command_error(ctx, error):
"""See https://discordpy.readthedocs.io/en/latest/api.html#event-reference"""
if isinstance(error, commands.errors.MissingRequiredArgument):
await bot_typing(ctx, 1)
await ctx.send(
f"Oof! {ctx.author.mention}, my friend, something is missing! "
"My wife says to use `?help` for more information."
)
if isinstance(error, commands.errors.BadArgument):
await bot_typing(ctx, 1)
await ctx.send(
f"Oof! {ctx.author.mention}, my friend, what is the constitution modifier?"
"My wife says to use `?help` for more information."
)
#######################
## DISCORD BOT START ##
#######################
if __name__ == "__main__":
token = os.getenv("DISCORD_TOKEN")
bot.run(token)