示例#1
0
    def __init__(self,
                 *,
                 p1: discord.Member,
                 p2: discord.Member,
                 aligned_amount: int = 4,
                 column_amount: int = 7,
                 row_amount: int = 6):

        super().__init__(timeout=30, clear_reactions_after=True, check_embeds=True)

        self.emojis = ('⬛', '🟢', '🔴')  # ids : (0, 1, -1)

        self.aligned_amount = aligned_amount
        self.is_timeout_win = True

        self.players = [Player(p1.id, p1.mention, 1), Player(p2.id, p2.mention, -1)]
        self.cycle_players = itertools.cycle((lambda x: [random.shuffle(x), x][1])(self.players))  # type: ignore
        self.current_player: Player = next(self.cycle_players)

        self.grid = grid = [[0 for _ in range(column_amount)] for _ in range(row_amount)]

        self.backup_grid = [[0 for _ in range(column_amount)] for _ in range(row_amount)]  # less painful than deepcopy

        title = f'Connect {self.aligned_amount} using {row_amount} rows and {column_amount} columns'
        self.embed_template = formatters.BetterEmbed(title=title)

        self.max_offset = max(len(grid), len(grid[0]))

        self.keycaps = [str(n) + '\N{variation selector-16}\N{combining enclosing keycap}' for n in range(column_amount)]

        self.f_keycaps = self.spacing_column.join(self.keycaps)
示例#2
0
    async def _dice(self, ctx: NewCtx, dice: str = "1d6"):
        """Generates dice with the supplied format `NdN`"""

        dice_list = dice.lower().split("d")
        if not (1 <= int(dice_list[0]) <= 25) and not (1 <= int(dice_list[1]) <= 100):
            return await ctx.send("Go away chr1s")
        try:
            d_count, d_value = int(dice_list[0]), int(dice_list[1])
        except ValueError:
            raise commands.BadArgument(
                "The entered format was incorrect, `NdN` only currently"
            )

        counter = []
        crit_s, crit_f = 0, 0
        if d_count < 0 or d_value < 0:
            raise commands.BadArgument("You cannot have negative values")
        for dice_num in range(d_count):
            randomnum = random.randint(1, d_value)
            if randomnum == d_value:
                crit_s += 1
            if randomnum == 1:
                crit_f += 1
            counter.append(randomnum)

        total = sum(counter)

        embed = formatters.BetterEmbed()
        embed.description = f"{dice} gave {', '.join([str(die) for die in counter])} = {total} with {crit_s} crit successes and {crit_f} fails"

        embed.add_field(name="Critical Successes; ", value=str(crit_s), inline=True)
        embed.add_field(name="Critical Failures; ", value=str(crit_f), inline=True)

        await ctx.send(embed=embed)
示例#3
0
    async def sixdigits(self, ctx: main.NewCtx):
        """Provides you a magical six digits number"""
        url, digits = await self._get_random_nhentai()

        if ctx.channel.is_nsfw():
            return await ctx.send(embed=formatters.BetterEmbed(title=digits, url=url))

        await ctx.send(digits)
示例#4
0
 def prepare_embed(
         self, message: discord.Message
 ) -> typing.Tuple[str, formatters.BetterEmbed]:
     ret = formatters.BetterEmbed(title="Catpost detected.")
     ret.add_field(
         name="Catpost;",
         value=f"[Jump!]({message.jump_url})",
         inline=False,
     )
     return "A cat post was detected, come have a look", ret
示例#5
0
    async def _rand_num(
        self, ctx: NewCtx, start: Union[int, float] = 0, stop: Union[int, float] = 100
    ):
        """Generates a random number from start to stop inclusive, if either is a float, number will be float"""

        if isinstance(start, float) or isinstance(stop, float):
            number = random.uniform(start, stop)
        else:
            number = random.randint(start, stop)

        embed = formatters.BetterEmbed()
        embed.description = f"Number between **{start}** and **{stop}**\n{number}"

        await ctx.send(embed=embed)
示例#6
0
class Events(commands.Cog):
    """ Event handler cog. Mostly errors and stuff rn. """
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.webhook = self._webhook
        self.ignored = [
            commands.CommandNotFound,
        ]
        self.tracking = True

    @property
    def _webhook(self) -> discord.Webhook:
        wh_id, wh_token = config.WEBHOOK
        hook = discord.Webhook.partial(
            id=wh_id,
            token=wh_token,
            adapter=discord.AsyncWebhookAdapter(self.bot.session),
        )
        return hook

    @lru_cache(maxsize=15)
    def tracy_beaker_fmt(
        self, error: Exception
    ) -> typing.Tuple[str, str, typing.Tuple[str, str, str]]:
        full_exc = traceback.format_exception(type(error), error,
                                              error.__traceback__)
        listed_exc = full_exc[-2].split()
        filename = listed_exc[1].replace("/", "\\")
        filename = "\\".join(filename.split("\\")[-3:])[:-1]
        linenumber = str(listed_exc[3])[:-1]
        funcname = listed_exc[5]
        exc_info = (filename, linenumber, funcname)
        short_exc = full_exc[-1]
        full_exc = [line.replace("/home/moogs", "", 1) for line in full_exc]
        full_exc = [
            line.replace("C:\\Users\\aaron", "", 1) for line in full_exc
        ]
        output = "\n".join(full_exc)
        idx = 0
        while len(output) >= 1990:
            idx -= 1
            output = "\n".join(full_exc[:idx])
        output = f"```\n{output}```"
        return short_exc, output, exc_info

    @commands.command(name="toggle")
    @commands.has_permissions(administrator=True)
    async def _toggle_tracker(self, ctx: NewCtx):
        """Toggles watching events like `on_member_join/remove` for server info"""
        query = "UPDATE guild_config SET stats_enabled = True WHERE guild_id = $1;"
        await self.bot.pool.execute(query, ctx.guild.id)

    @commands.group(invoke_without_command=True, name="ignored", hidden=True)
    @commands.is_owner()
    async def _ignored(self, ctx: NewCtx) -> None:
        """
        Adds or removes an exception from the list of exceptions to ignore,
        if you want to add or remove commands.MissingRole,
        be sure to exclude the 'commands.'
        """
        await ctx.send(", ".join([exc.__name__ for exc in self.ignored]))

    @_ignored.command(hidden=True)
    @commands.is_owner()
    async def add(self, ctx: NewCtx, exc: str):
        """Adds an exception to the list of ignored exceptions"""
        self.ignored.append()

        if hasattr(commands, exc):
            if getattr(commands, exc) not in self.ignored:
                self.ignored.append(getattr(commands, exc))
            else:
                await ctx.webhook_send(
                    f"commands.{exc} is already in the ignored exceptions.",
                    webhook=self.webhook,
                )
        else:
            raise AttributeError(
                "commands module has no attribute {0}, command aborted".format(
                    exc))

    @_ignored.command(hidden=True)
    @commands.is_owner()
    async def remove(self, ctx: NewCtx, exc: str):
        """Removes an exception from the list of ingored exceptions"""
        if hasattr(commands, exc):
            try:
                self.ignored.pop(self.ignored.index(getattr(commands, exc)))
            except ValueError:
                await ctx.webhook_send(
                    "{0} not in the ignored list of exceptions".format(exc),
                    webhook=self.webhook,
                )
        else:
            raise AttributeError(
                "commands module has no attribute {0}, command aborted".format(
                    exc))

    @commands.Cog.listener()
    async def on_ready(self):
        """ On websocket ready. """

    @commands.Cog.listener()
    async def on_message(self, message: Message):
        """ F**k you umbra"""

    @commands.Cog.listener()
    async def on_command(self, ctx: NewCtx):
        """ On command invocation. """
        if "jishaku" in (qname := ctx.qname):
            return

        embed = formatters.BetterEmbed(
            title=f"Command launched : {qname}",
            description=f"{ctx.guild.name} / {ctx.channel.name} / {ctx.author}",
        )

        for key, value in itertools.zip_longest(
                ctx.command.clean_params.keys(), ctx.all_args):
            embed.add_field(name=key, value=value)

        await self.webhook.send(embed=embed)