コード例 #1
0
ファイル: processor.py プロジェクト: EnythNet/phen-cogs
    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 newcontributors_interactive(self, ctx: GuildContext) -> None:
        """Interactively add contributors.

        Integrates with Red.
        """
        member_converter = commands.MemberConverter()
        pending_contributors = await self.__config.pending_contributors()
        new_added_contributors = {}

        early_exit = False
        for user_id, author_data in pending_contributors.items():
            discord_user_id_line = (
                f"**Discord user ID:** {discord_user_id}\n"
                if (discord_user_id := author_data.get('discord_user_id')) is not None
                else ""
            )
            bot_msg = await ctx.send(
                f"**GitHub Username:** {author_data['username']}\n"
                f"**Commit author name:** {author_data['name']}\n"
                f"**Commit author email:** {author_data['email']}\n"
                f"{discord_user_id_line}"
                "Use Red's `?assign` command or send user ID to add contributor."
                " Type `exit` to finish, use `skip` to skip the contributor."
            )

            while not early_exit:
                user_msg = await self.bot.wait_for(
                    "message_without_command", check=MessagePredicate.same_context(ctx)
                )
                content = user_msg.content

                if content == "exit":
                    early_exit = True
                    continue
                if content == "skip":
                    break

                if user_msg.content.startswith("?assign "):
                    view = StringView(user_msg.content)
                    view.skip_string("?assign ")
                    content = view.get_quoted_word()

                try:
                    member = await member_converter.convert(ctx, content)
                except commands.BadArgument as e:
                    await ctx.send(
                        f"{e}. Please try passing user ID"
                        " or using `?assign` command again."
                    )
                    continue

                author_data["discord_user_id"] = member.id
                new_added_contributors[user_id] = author_data
                break
            else:
                # early-exit by breaking out of for loop
                await safe_delete_message(bot_msg)
                break

            await safe_delete_message(bot_msg)
コード例 #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
    async def bs_brawlers(self, ctx: SlashContext, target:str=None):
        await ctx.defer()

        fake_message = FakeMessage(
            content= "...",
            channel= ctx.channel,
            author=ctx.author,
            id=int(ctx.interaction_id),
            state=self.bot._connection
        )
        context = await self.bot.get_context(fake_message)

        user = None
        if target is None:
            user = ctx.author
        else:
            try:
                member_converter = commands.MemberConverter()
                user = await member_converter.convert(context, target)
            except commands.MemberNotFound:
                user = target

        embeds = await player_stats.get_brawlers_embeds(self.bot, context, user)
        ctx.me = context.guild.get_member(self.bot.user.id)
        ctx.bot = self.bot
        await menu(ctx=ctx, pages=embeds, controls={"⬅": prev_page, "➡": next_page}, timeout=300)
コード例 #5
0
ファイル: faCheckIn.py プロジェクト: mattmiller87/RSCBot
    async def checkAvailability(self,
                                ctx,
                                tier_name: str,
                                match_day: str = None):
        if match_day is None:
            match_day = await self.match_cog._match_day(ctx)
        tier = await self.team_manager_cog._match_tier_name(ctx, tier_name)
        if tier is None:
            await ctx.send("No tier with name: `{0}`".format(tier_name))
            return

        tier_list = await self._tier_data(ctx, match_day, tier)
        perm_fa_role = self.team_manager_cog._find_role_by_name(
            ctx, self.team_manager_cog.PERM_FA_ROLE)

        message = "```Availability for {0} tier on match day {1}:".format(
            tier, match_day)
        for user in tier_list:
            member = commands.MemberConverter(ctx, user).convert()
            if member in ctx.message.guild.members:
                if await self._find_tier_from_fa_role(ctx, member) is not None:
                    message += "\n\t{0}".format(member.nick)
                    if perm_fa_role is not None and perm_fa_role in member.roles:
                        message += " (Permanent FA)"
        message += "```"
        await ctx.send(message)
コード例 #6
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__()
コード例 #7
0
ファイル: core.py プロジェクト: Shadow-poop/phen-cogs
    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)
コード例 #8
0
ファイル: converters.py プロジェクト: thomasjosif/079COGS
 async def convert(self, ctx: commands.Context, arg: str) -> discord.Member:
     member_converter = commands.MemberConverter()
     try:
         member = await member_converter.convert(ctx, arg)
     except commands.BadArgument:
         if arg.strip() != "":
             raise
         else:
             member = ctx.author
     return member
コード例 #9
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)
コード例 #10
0
 async def clean_input(ctx, text: str) -> str:
     """Removes characters that confuse bots
     Parameters
     ----------
     text: str
         Text to be clean.
     Returns
     -------
     str
         The cleaned text.
     """
     words = list()
     converter = commands.MemberConverter()
     for word in text.split():
         try:
             member = await converter.convert(ctx, word)
             words.append("-".join(member.display_name.split()))
         except discord.ext.commands.errors.BadArgument:
             words.append(word)
     text = " ".join(words)
     return text
コード例 #11
0
ファイル: processor.py プロジェクト: RDJBTG/playcogs
    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__()
コード例 #12
0
    async def bs_profile(self, ctx: SlashContext, target:str=None):
        await ctx.defer()

        fake_message = FakeMessage(
            content= "...",
            channel= ctx.channel,
            author=ctx.author,
            id=int(ctx.interaction_id),
            state=self.bot._connection
        )
        context = await self.bot.get_context(fake_message)

        user = None
        if target is None:
            user = ctx.author
        else:
            try:
                member_converter = commands.MemberConverter()
                user = await member_converter.convert(context, target)
            except commands.MemberNotFound:
                user = target

        embed = await player_stats.get_profile_embed(self.bot, context, user)
        await ctx.send(embed=embed)
コード例 #13
0
    async def wordcloud(self, ctx, *argv):
        """Generate a wordcloud. Optional arguments are channel, user, and
        message limit (capped at 10,000)."""

        author = ctx.author
        channel = ctx.channel
        user = None
        limit = 10000

        # a bit clunky, see if Red has already implemented converters
        channel_converter = commands.TextChannelConverter()
        member_converter = commands.MemberConverter()

        for arg in argv:
            try:
                channel = await channel_converter.convert(ctx, arg)
                continue
            except discord.ext.commands.BadArgument:
                pass

            try:
                user = await member_converter.convert(ctx, arg)
                continue
            except discord.ext.commands.BadArgument:
                pass

            if arg.isdecimal() and int(arg) <= 10000:
                limit = int(arg)

        guild = channel.guild

        # Verify that wordcloud requester is not being a sneaky snek
        if not channel.permissions_for(
                author).read_messages or guild != ctx.guild:
            await ctx.send("\N{SMIRKING FACE} Nice try.")
            return

        # Default settings
        mask = None
        coloring = None
        width = 800
        height = 600
        mode = "RGB"
        bg_color = await self.conf.guild(guild).bgcolor()
        if bg_color == "clear":
            mode += "A"
            bg_color = None
        max_words = await self.conf.guild(guild).maxwords()
        if max_words == 0:
            max_words = 200
        excluded = await self.conf.guild(guild).excluded()
        if not excluded:
            excluded = None

        mask_name = await self.conf.guild(guild).mask()
        if mask_name is not None:
            mask_file = f"{self.mask_folder}/{mask_name}"
            try:
                mask = np.array(Image.open(mask_file))
            except FileNotFoundError:
                await ctx.send("I could not load your mask file. It may "
                               "have been deleted. `{}wcset clearmask` "
                               "may resolve this.".format(ctx.prefix))
                return
            if await self.conf.guild(guild).colormask():
                coloring = ImageColorGenerator(mask)

        kwargs = {
            "mask": mask,
            "color_func": coloring,
            "mode": mode,
            "background_color": bg_color,
            "max_words": max_words,
            "stopwords": excluded,
            "width": width,
            "height": height,
        }

        msg = "Generating wordcloud for **" + guild.name + "/" + channel.name
        if user is not None:
            msg += "/" + user.display_name
        msg += "** using the last {} messages. (this might take a while)".format(
            limit)

        await ctx.send(msg)

        text = ""
        try:
            async for message in channel.history(limit=limit):
                if not message.author.bot:
                    if user is None or user == message.author:
                        text += message.clean_content + " "
        except discord.errors.Forbidden:
            await ctx.send(
                "Wordcloud creation failed. I can't see that channel!")
            return

        if not text or text.isspace():
            await ctx.send("Wordcloud creation failed. I couldn't find "
                           "any words. You may have entered a very small "
                           "message limit, or I may not have permission "
                           "to view message history in that channel.")
            return

        task = functools.partial(self.generate, text, **kwargs)
        task = self.bot.loop.run_in_executor(None, task)
        try:
            image = await asyncio.wait_for(task, timeout=45)
        except asyncio.TimeoutError:
            await ctx.send("Wordcloud creation timed out.")
            return
        await ctx.send(file=discord.File(image))