Пример #1
0
    def __init__(self):
        tse_blocks = [
            tse.MathBlock(),
            tse.RandomBlock(),
            tse.RangeBlock(),
            tse.AnyBlock(),
            tse.IfBlock(),
            tse.AllBlock(),
            tse.BreakBlock(),
            tse.StrfBlock(),
            tse.StopBlock(),
            tse.AssignmentBlock(),
            tse.FiftyFiftyBlock(),
            tse.LooseVariableGetterBlock(),
            tse.SubstringBlock(),
            tse.EmbedBlock(),
            tse.ReplaceBlock(),
            tse.PythonBlock(),
            tse.RequireBlock(),
            tse.BlacklistBlock(),
            tse.URLEncodeBlock(),
            tse.CommandBlock(),
            tse.RedirectBlock(),
        ]
        slash_blocks = [HideBlock()]
        self.engine = tse.Interpreter(tse_blocks + slash_blocks)

        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()
        super().__init__()
Пример #2
0
    async def convert(self, ctx: commands.Context, arg: str) -> discord.Role:
        admin = ctx.command.cog.bot.get_cog("Admin")
        if admin is None:
            raise commands.BadArgument("The Admin cog is not loaded.")

        selfroles = await admin.config.guild(ctx.guild).selfroles()
        role_converter = commands.RoleConverter()

        pool = []
        for rid in selfroles:
            role = ctx.guild.get_role(rid)
            if role is None:
                continue
            if role.name.lower() == arg.lower():
                pool.append(role)
        if len(pool) == 0:
            role = await role_converter.convert(ctx, arg)

        else:
            if len(pool) > 1:
                await ctx.send("This selfrole has more than one capitalization"
                               "possibilities.  Please inform a moderator.")
            role = pool[0]

        if role.id not in selfroles:
            raise commands.BadArgument(
                "The provided role is not a valid selfrole.")
        return role
Пример #3
0
    def __init__(self, bot: Red) -> None:
        self.bot = bot
        self.config = Config.get_conf(
            self,
            identifier=567234895692346562369,
            force_registration=True,
        )
        default_guild = {"tags": {}}
        self.config.register_guild(**default_guild)

        blocks = stable_blocks + [
            block.MathBlock(),
            block.RandomBlock(),
            block.RangeBlock(),
            block.AnyBlock(),
            block.IfBlock(),
            block.AllBlock(),
            block.BreakBlock(),
            block.StrfBlock(),
            block.StopBlock(),
            block.AssignmentBlock(),
            block.FiftyFiftyBlock(),
            block.ShortCutRedirectBlock("args"),
            block.LooseVariableGetterBlock(),
            block.SubstringBlock(),
        ]
        self.engine = Interpreter(blocks)
        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()

        self.guild_tag_cache = defaultdict(dict)
        self.task = asyncio.create_task(self.cache_tags())
Пример #4
0
    def __init__(self):
        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()

        self.bot.add_dev_env_value("tse", lambda ctx: tse)
        super().__init__()
Пример #5
0
    def __init__(self, bot: Red) -> None:
        self.bot = bot
        self.config = Config.get_conf(
            self,
            identifier=567234895692346562369,
            force_registration=True,
        )
        default_guild = {"tags": {}}
        default_global = {"tags": {}}
        self.config.register_guild(**default_guild)
        self.config.register_global(**default_global)

        tse_blocks = [
            tse.MathBlock(),
            tse.RandomBlock(),
            tse.RangeBlock(),
            tse.AnyBlock(),
            tse.IfBlock(),
            tse.AllBlock(),
            tse.BreakBlock(),
            tse.StrfBlock(),
            tse.StopBlock(),
            tse.AssignmentBlock(),
            tse.FiftyFiftyBlock(),
            tse.ShortCutRedirectBlock("args"),
            tse.LooseVariableGetterBlock(),
            tse.SubstringBlock(),
            tse.EmbedBlock(),
            tse.ReplaceBlock(),
            tse.PythonBlock(),
            tse.URLEncodeBlock(),
            tse.RequireBlock(),
            tse.BlacklistBlock(),
            tse.CommandBlock(),
            tse.OverrideBlock(),
        ]
        tag_blocks = [
            DeleteBlock(),
            SilentBlock(),
            ReactBlock(),
            RedirectBlock(),
            ReactUBlock(),
        ]
        self.engine = tse.Interpreter(tse_blocks + tag_blocks)
        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()

        self.guild_tag_cache = defaultdict(dict)
        self.global_tag_cache = {}
        self.cache_task = asyncio.create_task(self.cache_tags())

        self.session = aiohttp.ClientSession()
        self.docs: list = []

        super().__init__()
        bot.add_dev_env_value("tags", lambda ctx: self)
Пример #6
0
    def __init__(self, bot: Red) -> None:
        self.bot = bot
        self.application_id = None
        self.eval_command = None
        self.http = SlashHTTP(self)
        self.config = Config.get_conf(
            self,
            identifier=70342502093747959723475890,
            force_registration=True,
        )
        default_guild = {"tags": {}}
        default_global = {"application_id": None, "eval_command": None}
        self.config.register_guild(**default_guild)
        self.config.register_global(**default_global)

        tse_blocks = [
            tse.MathBlock(),
            tse.RandomBlock(),
            tse.RangeBlock(),
            tse.AnyBlock(),
            tse.IfBlock(),
            tse.AllBlock(),
            tse.BreakBlock(),
            tse.StrfBlock(),
            tse.StopBlock(),
            tse.AssignmentBlock(),
            tse.FiftyFiftyBlock(),
            tse.LooseVariableGetterBlock(),
            tse.SubstringBlock(),
            tse.EmbedBlock(),
            tse.ReplaceBlock(),
            tse.PythonBlock(),
            tse.RequireBlock(),
            tse.BlacklistBlock(),
            tse.URLEncodeBlock(),
            tse.CommandBlock(),
        ]
        slash_blocks = [HideBlock()]
        self.engine = tse.Interpreter(tse_blocks + slash_blocks)
        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()

        self.command_cache = {}
        self.guild_tag_cache: Dict[int, Dict[int,
                                             SlashTag]] = defaultdict(dict)
        self.global_tag_cache = {}

        self.load_task = self.create_task(self.initialize_task())

        bot.add_dev_env_value("st", lambda ctx: self)
Пример #7
0
    async def convert(self, ctx: commands.Context, arg: str) -> discord.Role:
        admin = ctx.command.cog
        if admin is None:
            raise commands.BadArgument(_("The Admin cog is not loaded."))

        role_converter = commands.RoleConverter()
        role = await role_converter.convert(ctx, arg)

        conf = admin.conf
        selfroles = await conf.guild(ctx.guild).selfroles()

        if role.id not in selfroles:
            raise commands.BadArgument(_("The provided role is not a valid selfrole."))
        return role
Пример #8
0
    async def convert(self, ctx: commands.Context, arg: str) -> discord.Role:
        """Convert an arg to a SelfRole."""
        admin = ctx.bot.get_cog("Admin")
        if admin is None:
            raise commands.BadArgument("Admin is not loaded.")

        selfroles = await admin.config.guild(ctx.guild).selfroles()

        role_converter = commands.RoleConverter()
        role = await role_converter.convert(ctx, arg)

        if role.id not in selfroles:
            raise commands.BadArgument("The provided role is not a valid selfrole.")
        return role
Пример #9
0
    async def convert(self, ctx: commands.Context, arg: str) -> discord.Role:
        admin = ctx.command.cog
        if admin is None:
            raise commands.BadArgument(_("The Admin cog is not loaded."))

        role_converter = commands.RoleConverter()
        role = await role_converter.convert(ctx, arg)

        selfroles = await admin.config.guild(ctx.guild).selfroles()

        if role.id not in selfroles:
            raise commands.BadArgument(
                _('The role "{role_name}" is not a valid selfrole.').format(
                    role_name=role.name))
        return role
Пример #10
0
    def __init__(self):
        tse_blocks = [
            tse.MathBlock(),
            tse.RandomBlock(),
            tse.RangeBlock(),
            tse.AnyBlock(),
            tse.IfBlock(),
            tse.AllBlock(),
            tse.BreakBlock(),
            tse.StrfBlock(),
            tse.StopBlock(),
            tse.AssignmentBlock(),
            tse.FiftyFiftyBlock(),
            tse.ShortCutRedirectBlock("args"),
            tse.LooseVariableGetterBlock(),
            tse.SubstringBlock(),
            tse.EmbedBlock(),
            tse.ReplaceBlock(),
            tse.PythonBlock(),
            tse.URLEncodeBlock(),
            tse.RequireBlock(),
            tse.BlacklistBlock(),
            tse.CommandBlock(),
            tse.OverrideBlock(),
            tse.RedirectBlock(),
        ]
        tag_blocks = [
            DeleteBlock(),
            SilentBlock(),
            ReactBlock(),
            ReactUBlock(),
        ]
        self.engine = tse.Interpreter(tse_blocks + tag_blocks)
        self.role_converter = commands.RoleConverter()
        self.channel_converter = commands.TextChannelConverter()
        self.member_converter = commands.MemberConverter()
        self.emoji_converter = commands.EmojiConverter()

        self.bot.add_dev_env_value("tse", lambda ctx: tse)
        super().__init__()
Пример #11
0
    raise commands.BadArgument(
        f'"{arg}" is not a valid setting.'
        ' Valid settings are "true" or "false", or "default" to '
        "remove the setting")


class TriState:
    def __init__(self, state):
        self.state = state

    @classmethod
    async def convert(cls, ctx, arg):
        return cls(_tristate(arg))


_role_converter = commands.RoleConverter()


class NonEveryoneRole(discord.Role):
    @classmethod
    async def convert(cls, ctx: commands.Context, arg: str) -> discord.Role:
        role: discord.Role = await _role_converter.convert(ctx, arg)
        if role.is_default():
            raise commands.BadArgument(
                "You can't set this for the everyone role")
        return role


class FieldAndTerm(NamedTuple):
    field: str
    term: str
Пример #12
0
import discord
from redbot.core import commands

from . import modroles


_RoleConverter = commands.RoleConverter()


class AssignableRoleConverter(discord.Role):
    @classmethod
    async def convert(cls, ctx: commands.Context, argument: str) -> discord.Role:
        modroles_cog = ctx.cog
        # *I hope* this won't break with our reload system
        if modroles_cog is None or modroles_cog.__class__ is not modroles.ModRoles:
            raise commands.BadArgument(
                "Converter was unable to access ModRoles config."
            )

        # class check above is not enough for mypy
        assert isinstance(modroles_cog, modroles.ModRoles), "mypy"

        role = await _RoleConverter.convert(ctx, argument)
        assignable_roles = await modroles_cog.config.guild(ctx.guild).assignable_roles()

        if role.id not in assignable_roles:
            raise commands.BadArgument(
                f"The provided role is not a valid assignable role."
            )
        return role
Пример #13
0
    async def giveaway_quick(self, ctx):
        """Starts a quick giveaway which uses the set config values"""
        def message_check(message):
            if message.author.id != ctx.author.id:
                return False
            if message.channel != ctx.channel:
                return False
            if message.content.lower() == "cancel":
                raise GiveawayAborted()
            return True

        config = await self.db.guild(ctx.guild).config()

        await ctx.send(
            'You have initiated the giveaway interactive menu. '
            'You have 60 seconds to answer each question and you '
            'can cancel this anytime by replying with `cancel` to any '
            'question.\nWhat is the title of this giveaway(the item '
            'to be given away)?')
        item = await self.bot.wait_for('message',
                                       check=message_check,
                                       timeout=60)
        item = item.content

        if config['winners']:
            winners = config['winners']
        else:
            await ctx.send(f'Ok, so the giveaway will be for `{item}`\n'
                           'How many winners would there be?')
            winners = await self.bot.wait_for('message',
                                              check=message_check,
                                              timeout=60)
            winners = winners.content
            try:
                winners = int(winners)
            except ValueError:
                return await ctx.send('This input must be a number. Aborted!')

            if winners < 1:
                winners = 1
                await ctx.send(
                    'The number of winners could not be less than 1 '
                    'so it was set to 1')

        if config['ending_message']:
            ending_message = config['ending_message']
        else:
            file_threshold = await self.db.file_threshold()
            await ctx.send(
                'What should be the message that is sent at the end of the '
                'giveaway?\n\nNote: The winners will be mentioned in this '
                f'at the end if they are <{file_threshold} in number'
                ' otherwise a file with their names will be attached!')
            ending_message = await self.bot.wait_for('message',
                                                     check=message_check,
                                                     timeout=60)
            ending_message = ending_message.content

        if config['author_id']:
            author = self.bot.get_user(config['author_id'])
        else:
            await ctx.send("Who should be the author of this giveaway?")
            author = await self.bot.wait_for('message',
                                             check=message_check,
                                             timeout=60)
            author = await commands.UserConverter().convert(
                ctx, author.content)

        if config['roles']:
            roles = [ctx.guild.get_role(role) for role in config['roles']]
            roles = [role for role in roles if role]
        else:
            await ctx.send(
                "Do users require any roles to enter this giveaway?\n"
                "If yes, then send the roles separated by spaces. "
                "Otherwise send `None`\n\n"
                "Note: For roles with spaces in their name, either "
                "mention them or use their ID")
            roles = await self.bot.wait_for('message',
                                            check=message_check,
                                            timeout=60)
            roles = roles.content
            if roles.lower() == 'none':
                roles = None
            else:
                _roles = roles.split(' ')
                roles = []
                converter = commands.RoleConverter()
                for role in _roles:
                    role = await converter.convert(ctx, role)
                    roles.append(role)

        if config['join_days'] is None:
            await ctx.send(
                "How many days should the user have been in the server "
                "to enter this giveaway?\nIf  you don't want to set this "
                "requirement then just send `None`")
            join_days = await self.bot.wait_for('message',
                                                check=message_check,
                                                timeout=60)
            join_days = join_days.content
            if join_days.lower() == 'none':
                join_days = None
            else:
                try:
                    join_days = int(join_days)
                except ValueError:
                    return await ctx.send(
                        'This input must be a number. Aborted!')

                if join_days < 1:
                    join_days = None
                    await ctx.send(
                        'The number of join_days could not be less than 1 '
                        'so it was set to None')
        elif config['join_days'] == 0:
            join_days = None
        else:
            join_days = config['join_days']

        if config['channel_id']:
            channel = ctx.guild.get_channel(config['channel_id'])
        else:
            await ctx.send("In which channel do you want to run this giveaway?"
                           )
            channel = await self.bot.wait_for('message',
                                              check=message_check,
                                              timeout=60)
            channel = await commands.TextChannelConverter().convert(
                ctx, channel.content)

        text = '''When will the giveaway end?
The time can be any direct date (e.g. YYYY-MM-DD) or a human readable offset.
Examples:

- "next thursday at 3pm"
- "tomorrow"
- "in 3 days"
- "2d"

Times are in UTC.'''
        await ctx.send(text)
        end_time = await self.bot.wait_for('message',
                                           check=message_check,
                                           timeout=60)
        end_time = await UserFriendlyTime(commands.clean_content,
                                          default='\u2026').convert(
                                              ctx, end_time.content)
        # to compensate the computing loss, we add 15 seconds to the end time
        # This shouldn't affect long giveaways much but might be great for short
        # ones
        end_time = end_time.dt + datetime.timedelta(seconds=15)

        giveaway = await Giveaway.create(bot=self.bot,
                                         config=self.db,
                                         author=author,
                                         channel=channel,
                                         item=item,
                                         ending_message=ending_message,
                                         end_time=end_time,
                                         winners=winners,
                                         roles=roles,
                                         join_days=join_days)
        self.running_giveaways.append(giveaway)
        await ctx.send(f"Successfully created giveaway in {channel.mention}!")