예제 #1
0
    async def add(self, ctx: Context, emoji: str, option_name: str,
                  role: Role):
        """Add role to reaction role embed"""
        if ctx.message.reference is None:
            raise errors.UserInputError(
                'You must reply to a reaction role embed to use this command')

        msg = await ctx.fetch_message(ctx.message.reference.message_id)

        if msg.author.id != self.bot.user.id:
            raise errors.UserInputError(
                '`rr add` can only be used on messages sent by ZedUtils')

        embed = msg.embeds[0]

        if embed.description:
            if str(emoji) in embed.description:
                parts = embed.description.split('\n')
                description = ''
                for part in parts:
                    if not part.startswith(str(emoji)):
                        description += part
                embed.description = description

            embed.description += f'\n{emoji} {option_name}'
        else:
            embed.description = f'\n{emoji} {option_name}'

        await msg.edit(embed=embed)
        await msg.add_reaction(emoji)

        await ctx.message.delete()

        settings['reaction_roles'][str(msg.id)].append([emoji, role.id])
        await settings.save()
예제 #2
0
    async def test_handle_input_error_handler_errors(self):
        """Should handle each error probably."""
        test_cases = ({
            "error": errors.MissingRequiredArgument(MagicMock()),
            "call_prepared": True
        }, {
            "error": errors.TooManyArguments(),
            "call_prepared": True
        }, {
            "error": errors.BadArgument(),
            "call_prepared": True
        }, {
            "error":
            errors.BadUnionArgument(MagicMock(), MagicMock(), MagicMock()),
            "call_prepared":
            True
        }, {
            "error": errors.ArgumentParsingError(),
            "call_prepared": False
        }, {
            "error": errors.UserInputError(),
            "call_prepared": True
        })

        for case in test_cases:
            with self.subTest(error=case["error"],
                              call_prepared=case["call_prepared"]):
                self.ctx.reset_mock()
                self.assertIsNone(await self.cog.handle_user_input_error(
                    self.ctx, case["error"]))
                self.ctx.send.assert_awaited_once()
                if case["call_prepared"]:
                    self.ctx.send_help.assert_awaited_once()
                else:
                    self.ctx.send_help.assert_not_awaited()
예제 #3
0
    async def color(self, ctx: Context, color: Color):
        if ctx.message.reference is None:
            raise errors.UserInputError(
                'You must reply to a reaction role embed to use this command')

        msg = await ctx.fetch_message(ctx.message.reference.message_id)

        if msg.author.id != self.bot.user.id:
            raise errors.UserInputError(
                '`rr add` can only be used on messages sent by ZedUtils')

        embed = msg.embeds[0]
        embed.color = color

        await msg.edit(embed=embed)
        await ctx.message.delete()
예제 #4
0
    async def coin_flip(self, ctx, wager: int):
        """Take a 50-50 chance to win or lose a wager"""
        wager = abs(wager)

        if str(ctx.author.id) not in economy:
            economy[str(ctx.author.id)] = economy['default_economy']

        stats = economy[str(ctx.author.id)]

        if wager > stats['coins']:
            raise errors.UserInputError(
                'Your wager is larger than your coin amount')

        if random.choice([True, False]):
            economy[str(ctx.author.id)]['coins'] += wager

            embed = Embed(
                title="You won!",
                description=
                f"{ctx.author} now has {economy[str(ctx.author.id)]['coins']} coins",
                color=Color.green())
            await ctx.send(embed=embed)
        else:
            economy[str(ctx.author.id)]['coins'] -= wager

            embed = Embed(
                title="You lost!",
                description=
                f"{ctx.author} now has {economy[str(ctx.author.id)]['coins']} coins",
                color=Color.red())
            await ctx.send(embed=embed)
예제 #5
0
 async def test_error_handler_user_input_error(self):
     """Should await `ErrorHandler.handle_user_input_error` when error is `UserInputError`."""
     self.ctx.reset_mock()
     cog = ErrorHandler(self.bot)
     cog.handle_user_input_error = AsyncMock()
     error = errors.UserInputError()
     self.assertIsNone(await cog.on_command_error(self.ctx, error))
     cog.handle_user_input_error.assert_awaited_once_with(self.ctx, error)
예제 #6
0
    async def help(self, ctx, cog: str = None):
        """Show this message"""
        if not cog:
            help_embed = discord.Embed(
                title='ZedUtil Cog Listings',
                description='Use `>help [cog]` to find out more about them!',
                color=Color.darker_gray())

            help_embed.set_author(
                name=f'{ctx.message.content}',
                icon_url=ctx.author.avatar_url,
                url="https://github.com/foxnerdsaysmoo/zedutils#features")

            cogs_desc = ''
            for x in self.bot.cogs:
                if not hasattr(self.bot.cogs[x], 'hidden'):
                    cogs_desc += '[{}]({})'.format(
                        x, "https://github.com/foxnerdsaysmoo/zedutils#" +
                        self.bot.cogs[x].__doc__) + '\n'
            help_embed.add_field(name='Cogs',
                                 value=cogs_desc[0:len(cogs_desc) - 1],
                                 inline=False)

            await ctx.send(embed=help_embed)
        else:
            found = False
            for x, i in self.bot.cogs.items():
                if x.lower() == cog.lower():
                    if not hasattr(self.bot.cogs[x], 'hidden'):
                        url = "https://github.com/foxnerdsaysmoo/zedutils#" + self.bot.cogs[
                            x].__doc__
                        help_embed = discord.Embed(title=f'{x} help',
                                                   url=url,
                                                   color=Color.darker_gray())
                        help_embed.set_author(name=f'{ctx.message.content}',
                                              icon_url=ctx.author.avatar_url,
                                              url=url)
                    else:
                        help_embed = discord.Embed(
                            title=f'{x}',
                            description=self.bot.cogs[x].__doc__,
                            color=Color.darker_gray())
                    commands_ = ''
                    for c in i.get_commands():
                        if not c.hidden:
                            commands_ += f'**{c.name}** - {c.help}\n'

                    help_embed.add_field(name='Commands', value=commands_)

                    found = True

            if not found:
                raise errors.UserInputError('Invalid cog name')

            await ctx.send(embed=help_embed)
예제 #7
0
    async def set_status(self, ctx, act_type: str, *, name: str):
        """Set status of ZedUtils"""
        if ctx.author.id not in self.owners:
            raise errors.NotOwner

        try:
            activity = getattr(discord.ActivityType, act_type.lower())
        except AttributeError:
            raise errors.UserInputError(f"Invalid activity tye: {act_type}")

        await self.bot.change_presence(
            activity=discord.Activity(type=activity, name=name))
        await ctx.send(':white_check_mark: Successfully changed status!')
예제 #8
0
    async def add(self, ctx, *, prefix: str = None):
        if prefix is None:
            raise errors.UserInputError(
                f'Please include a prefix with your command')

        await prefix_base(ctx)

        gid = str(ctx.guild.id)
        settings[gid]['prefixes'].append(prefix)
        settings[gid]['prefixes'] = list(
            dict.fromkeys(settings[gid]['prefixes']))
        await settings.save()
        await ctx.send(
            f':white_check_mark: Added `{prefix}` as a new ZedUtils prefix')
예제 #9
0
    async def rate_cmd(self, ctx, rate: int = None):
        """
        View or modify voice rate
        """
        if rate is None:
            rate = self.rate
            if str(ctx.guild.id) in settings:
                if 'rate' in settings[str(ctx.guild.id)]:
                    rate = settings[str(ctx.guild.id)]['rate']
            await ctx.send(f'Current voice rate is {rate} wpm')
            return

        if not 80 < rate < 300:
            raise errors.UserInputError(f'Invalid rate of {rate}!')

        gid = str(ctx.guild.id)
        if gid not in settings:
            settings[gid] = {'rate': rate}
        else:
            settings[gid]['rate'] = rate
        settings.save()
        await ctx.send(f':white_check_mark: Voice rate changed to {rate} wpm')