Browse Source

Added rolling command.

main
Nichole Mattera 5 months ago
parent
commit
24327d8fe2
  1. 88
      cogs/basic.py

88
cogs/basic.py

@ -2,6 +2,60 @@ import time
import discord
from discord.ext import commands
from discord.ext.commands import Cog
import random
import re
class Roll:
def __init__(self, roll_definition):
# Parse the name of the roll if provided.
if ":" in roll_definition:
roll_definition_name_divide = roll_definition.split(":")
self.name = roll_definition_name_divide[0]
roll_definition = roll_definition_name_divide[1]
else:
self.name = ""
# Parse when the user just passes in a number. (Ex. "6", "20")
if roll_definition.isnumeric():
self.times = 1
self.die = int(roll_definition)
elif "d" in roll_definition:
roll_definition_components = roll_definition.split("d")
# Parse when the user passes in a number prefixed with a "d". (Ex. "d6", "d20")
if len(roll_definition_components) == 1:
self.times = 1
if roll_definition_components[0].isnumeric():
self.die = int(roll_definition_components[0])
else:
raise ValueError
# Parse when the user passes in a number prefixed with how many times followed by a "d". (Ex. "1d6", "2d20")
elif len(roll_definition_components) == 2:
if roll_definition_components[0].isnumeric():
self.times = int(roll_definition_components[0])
else:
self.times = 1
if roll_definition_components[1].isnumeric():
self.die = int(roll_definition_components[1])
else:
raise ValueError
else:
raise ValueError
def execute(self):
if self.times != 1:
result = ""
total = 0
for i in range(self.times):
value = random.randint(1, self.die)
result += f"{value}, "
total += value
return f"{result[0:-2]} (Total: {total})"
else:
return str(random.randint(1, self.die))
class Basic(Cog):
@ -33,6 +87,40 @@ class Basic(Cog):
self.bot.log.info(message_text)
await tmp.edit(content=message_text)
@commands.guild_only()
@commands.command()
async def roll(self, ctx, *, rolls):
"""Rolls a die"""
sanitized_rolls = re.sub(r"[, ]+", " ", rolls)
rollList = sanitized_rolls.split()
embed = discord.Embed(color=0x2196F3, title=f"{ctx.author.name} Rolls")
for index, roll in enumerate(rollList):
try:
rollObj = Roll(roll)
if rollObj.name == "":
embed.add_field(
name=f"Roll {index + 1}", value=rollObj.execute(), inline=False
)
else:
embed.add_field(
name=rollObj.name, value=rollObj.execute(), inline=False
)
except:
embed = discord.Embed(
color=0xF44336,
description="The following formats are supported: 'Name:4d2', '2d6', 'd20', '3'",
title="An incorrect format was passed into the roll command.",
)
embed.set_footer(
text="You can also pass more than one roll at a time by separating them with a space or comma."
)
await ctx.send(embed=embed)
return
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Basic(bot))
Loading…
Cancel
Save