You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.5 KiB

import time
import discord
from discord.ext import commands
from discord.ext.commands import Cog
import random
import re
class Roll:
_roll_regex = None
def __init__(self, roll_definition):
matches = self.roll_regex().match(roll_definition)
if matches is None:
raise ValueError
_, name, _, times, die, modifier = matches.groups()
self.name = name
self.times = int(times) if times is not None else 1
self.modifier = int(modifier) if modifier is not None else 0
if die is None:
raise ValueError
self.die = int(die)
@classmethod
def roll_regex(cls):
if cls._roll_regex is None:
cls._roll_regex = re.compile(r"((.*):)?((\d+)?d)?(\d+)([+-]\d+)?")
return cls._roll_regex
def execute(self):
if self.times != 1:
result = ""
total = 0
for i in range(self.times):
value = random.randint(1, self.die) + self.modifier
result += f"{value}, "
total += value
return f"{result[0:-2]} (Total: {total})"
else:
return str(random.randint(1, self.die) + self.modifier)
class Basic(Cog):
def __init__(self, bot):
self.bot = bot
@commands.guild_only()
@commands.command()
async def membercount(self, ctx):
"""Prints the member count of the server."""
await ctx.send(f"{ctx.guild.name} has " f"{ctx.guild.member_count} members!")
@commands.guild_only()
@commands.command(aliases=["p"])
async def ping(self, ctx):
"""Shows ping values to discord.
RTT = Round-trip time, time taken to send a message to discord
GW = Gateway Ping"""
before = time.monotonic()
tmp = await ctx.send("Calculating ping...")
after = time.monotonic()
rtt_ms = (after - before) * 1000
gw_ms = self.bot.latency * 1000
message_text = (
f":ping_pong:\n" f"rtt: `{rtt_ms:.1f}ms`\n" f"gw: `{gw_ms:.1f}ms`"
)
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 is None:
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))