async def git(self, ctx, pull_push, *, message=None):
        """
        Executes git statements in the system shell.
        This uses the system shell as defined in $SHELL, or `/bin/bash` otherwise.
        Execution can be cancelled by closing the paginator.
        """
        message = message if message is not None else "Updated files."

        if pull_push == "push":
            shellcmd = f'sudo git add .&&sudo git commit -m "{message}"&&sudo git push'
        elif pull_push == "pull":
            shellcmd = 'sudo git pull'
        else:
            return await ctx.send("Invalid option given")

        async with ReplResponseReactor(ctx.message):
            paginator = WrappedPaginator(prefix="```sh", max_size=1985)
            paginator.add_line(f"$ git {pull_push}\n")

            interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
            self.bot.loop.create_task(interface.send_to(ctx))

            with ShellReader(shellcmd) as reader:
                async for line in reader:
                    if interface.closed:
                        return
                    await interface.add_line(line)
示例#2
0
	async def mcsteams(self, ctx):
		async with aiohttp.ClientSession() as s:
			async with s.get(f'https://minecraftsaturdays.net/api/roster/{self.season}/{self.week}') as r:
				p = await r.text()
				p = json.loads(p)
				teams = p['teams']
		t = []
		for team in teams:
			team["score"] = 0
			for x in team["players"]:
				team["score"] += x["score"]
			players = [f'[{x["name"]}]({x.get("link", "https://minecraftsaturdays.net/")})\nтнР Points: {x["score"]}' for x in team["players"]]
			players = "\n".join(players)
			t.append({
				'text': f'**Team {teams.index(team) + 1}:**\n{players}\n\nЁЯПЕ Wins: {team["players"][0]["wins"]}\nтнР Total Points: {team["score"]}\n',
				'score': team["score"]
			})
		t = sorted(t, key=lambda t: t["score"])
		t.reverse()
		paginator = WrappedPaginator(prefix='**Minecraft Saturdays Teams**', suffix='', max_size=650)
		for team in t:
			paginator.add_line(team["text"])
		embed = discord.Embed(colour=ctx.author.color, timestamp=datetime.datetime.utcnow())
		footer = {'text': 'https://minecraftsaturdays.net/', 'icon_url': 'https://cdn.discordapp.com/icons/618826436299456533/6dfe2d224d8d919cac6bd71dcf7b0955.png'}
		interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed, _footer=footer)
		await interface.send_to(ctx)
示例#3
0
 async def lyrics(self, ctx, *, query: str = None):
     lyrics = None
     if not query:
         return await ctx.error('Missing search query')
     else:
         lyrics = await self.bot.ksoft.lyrics_search(query)
     if not lyrics or len(lyrics.results) < 1:
         return await ctx.error('No lyrics found')
     lyrics = lyrics.results[0]
     paginator = WrappedPaginator(prefix='', suffix='', max_size=1000)
     for line in lyrics.lyrics.split('\n'):
         paginator.add_line(line)
     embed = discord.Embed(color=ctx.author.color,
                           title=f'{lyrics.name} by {lyrics.artist}',
                           url=lyrics.url)
     embed.set_thumbnail(url=lyrics.album_art)
     footer = {
         'text': 'Powered by KSoft.Si API',
         'icon_url': 'https://cdn.ksoft.si/images/Logo128.png'
     }
     interface = PaginatorEmbedInterface(ctx.bot,
                                         paginator,
                                         owner=ctx.author,
                                         _embed=embed,
                                         _footer=footer)
     await interface.send_to(ctx)
示例#4
0
    async def git(self, ctx: commands.Context, pull_push, *, commit_msg=None):
        """
        Executes git statements in the system shell.

        This uses the system shell as defined in $SHELL, or `/bin/bash` otherwise.
        Execution can be cancelled by closing the paginator.
        """
        if pull_push == "push":
            shellcmd = f'sudo git add .&&sudo git commit -m "{commit_msg}"&&sudo git push'
        if pull_push == "pull":
            shellcmd = 'sudo git pull'
        if pull_push not in ['pull', 'push']: 
            return await ctx.send("Invalid option given")

        async with ReplResponseReactor(ctx.message):
            paginator = WrappedPaginator(prefix="```sh", max_size=1985)
            paginator.add_line(f"$ git {pull_push}\n")

            interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
            self.bot.loop.create_task(interface.send_to(ctx))

            if commit_msg is None:
                commit_msg = "File changes"

            with ShellReader(shellcmd) as reader:
                async for line in reader:
                    if interface.closed:
                        return
                    await interface.add_line(line)
示例#5
0
文件: cog.py 项目: Minion3665/jishaku
    async def jsk_source(self, ctx: commands.Context, *, command_name: str):
        """
        Displays the source code for a command.
        """

        command = self.bot.get_command(command_name)
        if not command:
            return await ctx.send(f"Couldn't find command `{command_name}`.")

        try:
            source_lines, _ = inspect.getsourcelines(command.callback)
        except (TypeError, OSError):
            return await ctx.send(
                f"Was unable to retrieve the source for `{command}` for some reason. Is it saved?"
            )

        # getsourcelines for some reason returns WITH line endings
        source_lines = ''.join(source_lines).split('\n')

        paginator = WrappedPaginator(prefix='```py',
                                     suffix='```',
                                     max_size=1985)
        for line in source_lines:
            line = (line.replace('`', '\u200B`').replace(
                '*', '\u200B*').replace('|', '\u200B|').replace(
                    '>', '\u200B>').replace('_', '\u200B_'))
            paginator.add_line(line)

        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
        await interface.send_to(ctx)
示例#6
0
    async def source(self, ctx, *, command_name: str):
        """
        Displays the source code for a command.
        """

        command = self.bot.get_command(command_name)
        if not command:
            return await ctx.send(f"Couldn't find command `{command_name}`.")

        try:
            source_lines, _ = inspect.getsourcelines(command.callback)
        except (TypeError, OSError):
            return await ctx.send(
                f"Was unable to retrieve the source for `{command}` for some reason."
            )

        # getsourcelines for some reason returns WITH line endings
        source_lines = ''.join(source_lines).split('\n')

        paginator = WrappedPaginator(prefix='```py',
                                     suffix='```',
                                     max_size=1985)
        for num, line in enumerate(source_lines, start=1):
            paginator.add_line(str(num) + escape(line))

        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
        await interface.send_to(ctx)
示例#7
0
 async def listguilds(self, ctx):
     if not self.bot.isadmin(ctx.author):
         return await ctx.error('no')
     data = [['Name', 'ID', 'Members', 'Channels', 'Boosts', 'Shard']]
     for guild in sorted(self.bot.guilds,
                         key=lambda g: g.member_count,
                         reverse=True):
         data.append([
             shorten(guild.name),
             guild.id,
             format(guild.member_count, ',d'),
             len(guild.channels),
             guild.premium_subscription_count,
             guild.shard_id,
         ])
     table = AsciiTable(data)
     header = table.table.split('\n')[:3]
     paginator = WrappedPaginator(prefix='```\n' + '\n'.join(header),
                                  suffix='```',
                                  max_size=1950)
     for ln in table.table.split('\n'):
         if ln not in header:
             paginator.add_line(ln)
     interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
     return await interface.send_to(ctx)
示例#8
0
 async def lyrics(self, ctx, *, query: typing.Union[Member, str] = None):
     lyrics = None
     query = ctx.author if not query else query
     if type(query) == discord.Member:
         for activity in query.activities:
             if type(activity) == discord.Spotify:
                 lyrics = await self.bot.ksoft.lyrics_search(
                     f'{", ".join(activity.artists)} {activity.title}')
         if not lyrics:
             raise commands.BadArgument(
                 'That member isn\'t listening to Spotify!')
     elif type(query) == discord.User:
         raise commands.BadArgument('Missing search query')
     else:
         lyrics = await self.bot.ksoft.lyrics_search(query)
     if len(lyrics.results) < 1:
         return await ctx.send(
             '<a:fireFailed:603214400748257302> No lyrics found')
     lyrics: ksoftapi.LyricsSearchResp = lyrics.results[0]
     paginator = WrappedPaginator(prefix='', suffix='', max_size=1000)
     for line in lyrics.lyrics.split('\n'):
         paginator.add_line(line)
     embed = discord.Embed(color=ctx.author.color,
                           title=f'{lyrics.name} by {lyrics.artist}')
     footer = {
         'text': 'Powered by KSoft.Si API',
         'icon_url': 'https://cdn.ksoft.si/images/Logo128.png'
     }
     interface = PaginatorEmbedInterface(ctx.bot,
                                         paginator,
                                         owner=ctx.author,
                                         _embed=embed,
                                         _footer=footer)
     await interface.send_to(ctx)
示例#9
0
    async def jsk_python_inspect(self, ctx: commands.Context, *, argument: codeblock_converter):
        """
        Evaluation of Python code with inspect information.
        """

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    executor = AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict)
                    async for send, result in AsyncSender(executor):
                        self.last_result = result

                        header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)

                        for name, res in all_inspections(result):
                            paginator.add_line(f"{name:16.16} :: {res}")

                        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                        send(await interface.send_to(ctx))
        finally:
            scope.clear_intersection(arg_dict)
示例#10
0
文件: utils.py 项目: TAG-Epic/bot
	async def role(self, ctx, *, role: Role = None):
		if not role:
			role = ctx.author.top_role
		embed = discord.Embed(colour=role.color if role.color != discord.Color.default() else ctx.author.color, timestamp=datetime.datetime.utcnow())
		embed.add_field(name="» Name", value=role.name, inline=False)
		embed.add_field(name="» ID", value=role.id, inline=False)
		embed.add_field(name="» Mention", value=f'`{role.mention}`', inline=False)
		rgbcolor = role.color.to_rgb()
		hexcolor = rgb2hex(role.color.r, role.color.g, role.color.b).replace('##', '#')
		embed.add_field(name="» Hoisted?", value='Yes' if role.hoist else 'No')
		embed.add_field(name="» Mentionable?", value='Yes' if role.mentionable else 'No')
		embed.add_field(name="» Color", value=f'RGB: {rgbcolor}\nHEX: {hexcolor}')
		perms = []
		if not role.permissions.administrator:
			for perm, value in role.permissions:
				if value and perm in permissions:
					perms.append(permissions[perm])
			if perms:
				embed.add_field(name="» Key Permissions", value=', '.join(perms), inline=False)
		else:
			embed.add_field(name="» Permissions", value='Administrator', inline=False)
		await ctx.send(embed=embed)
		if role.members:
			paginator = WrappedPaginator(prefix='', suffix='', max_size=250)
			for member in role.members:
				paginator.add_line(member.mention)
			membed = discord.Embed(
				colour=role.color if role.color != discord.Color.default() else ctx.author.color,
				timestamp=datetime.datetime.utcnow(),
				title=f'Members [{len(role.members)}]'
			)
			interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=membed)
			await interface.send_to(ctx)
示例#11
0
    async def jsk_shell(self, ctx: commands.Context, *, argument: codeblock_converter):
        """
        Executes statements in the system shell.

        This uses the system shell as defined in $SHELL, or `/bin/bash` otherwise.
        Execution can be cancelled by closing the paginator.
        """

        async with ReplResponseReactor(ctx.message):
            with self.submit(ctx):
                with ShellReader(argument.content) as reader:
                    prefix = "```" + reader.highlight

                    paginator = WrappedPaginator(prefix=prefix, max_size=1975)
                    paginator.add_line(f"{reader.ps1} {argument.content}\n")

                    interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                    self.bot.loop.create_task(interface.send_to(ctx))

                    async for line in reader:
                        if interface.closed:
                            return
                        await interface.add_line(line)

                await interface.add_line(f"\n[status] Return code {reader.close_code}")
示例#12
0
 async def nmcnames(self, ctx, name: str):
     async with aiohttp.ClientSession() as s:
         async with s.get(f'https://namemc.com/{name}') as r:
             content = await r.text()
     namecount, names, dates = await getnames(content, name)
     if type(namecount) == dict:
         data = namecount
         embed = discord.Embed(title=f'Name information for {name}',
                               color=ctx.author.color,
                               timestamp=datetime.datetime.utcnow())
         if 'when' in data:
             embed.add_field(name='Availability Status',
                             value=data['when'],
                             inline=False)
         if 'searches' in data:
             embed.add_field(name='Searches',
                             value=data['searches'],
                             inline=False)
         if 'toa' in data and data['toa'] != 'tomorrow':
             date = dateutil.parser.parse(data['toa'])
             date = datetime.datetime.strftime(date,
                                               '%d/%m/%Y @ %I:%M:%S %p')
             embed.add_field(name='Time of Availability',
                             value=date,
                             inline=False)
         if 'remain' in data and data['remain'] != 'an eternity':
             embed.add_field(name='Time Remaining',
                             value=data['remain'],
                             inline=False)
         await ctx.send(embed=embed)
     if namecount and names and dates:
         yeet = True
     else:
         raise commands.CommandError(
             'I was unable to parse the list of names for that user')
     namelist = []
     reqname = name
     paginator = WrappedPaginator(prefix='', suffix='', max_size=2000)
     for i, v in enumerate(namecount):
         count = namecount[i]
         namemd = names[i]
         name = discord.utils.escape_markdown(names[i])
         name = f"[{name}](https://namemc.com/name/{name} 'Click here to go to the NameMC page for {namemd}')"
         try:
             date = dateutil.parser.parse(dates[i])
             date = datetime.datetime.strftime(date,
                                               '%d/%m/%Y @ %I:%M:%S %p')
         except IndexError:
             date = 'First Name'
         paginator.add_line(f'**{count}** {name}   {date}')
     embed = discord.Embed(title=f'Name history for {reqname}',
                           color=ctx.author.color,
                           timestamp=datetime.datetime.utcnow())
     interface = PaginatorEmbedInterface(ctx.bot,
                                         paginator,
                                         owner=ctx.author,
                                         _embed=embed)
     await interface.send_to(ctx)
示例#13
0
    async def jsk_python_inspect(self, ctx: commands.Context, *,
                                 argument: codeblock_converter):
        """
        Evaluation of Python code with inspect information.
        """

        arg_dict = get_var_dict_from_ctx(ctx, Flags.SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    executor = AsyncCodeExecutor(argument.content,
                                                 scope,
                                                 arg_dict=arg_dict)
                    async for send, result in AsyncSender(executor):
                        self.last_result = result

                        header = repr(result).replace("``",
                                                      "`\u200b`").replace(
                                                          self.bot.http.token,
                                                          "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        lines = [f"=== {header} ===", ""]

                        for name, res in all_inspections(result):
                            lines.append(f"{name:16.16} :: {res}")

                        docstring = (inspect.getdoc(result) or '').strip()

                        if docstring:
                            lines.append(f"\n=== Help ===\n\n{docstring}")

                        text = "\n".join(lines)

                        if use_file_check(ctx, len(
                                text)):  # File "full content" preview limit
                            send(await ctx.send(file=discord.File(
                                filename="inspection.prolog",
                                fp=io.BytesIO(text.encode('utf-8')))))
                        else:
                            paginator = WrappedPaginator(prefix="```prolog",
                                                         max_size=1985)

                            paginator.add_line(text)

                            interface = PaginatorInterface(ctx.bot,
                                                           paginator,
                                                           owner=ctx.author)
                            send(await interface.send_to(ctx))
        finally:
            scope.clear_intersection(arg_dict)
示例#14
0
    async def _eval(self, ctx: commands.Context, *,
                    argument: codeblock_converter):
        """
        Direct evaluation of Python code.
        """
        if ctx.author.id in ownerid:

            arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
            arg_dict["_"] = self.last_result

            scope = self.scope

            try:
                async with ReplResponseReactor(ctx.message):
                    with self.submit(ctx):
                        executor = AsyncCodeExecutor(argument.content,
                                                     scope,
                                                     arg_dict=arg_dict)
                        async for send, result in AsyncSender(executor):
                            if result is None:
                                continue

                            self.last_result = result

                            if isinstance(result, discord.File):
                                send(await ctx.send(file=result))
                            elif isinstance(result, discord.Embed):
                                send(await ctx.send(embed=result))
                            elif isinstance(result, PaginatorInterface):
                                send(await result.send_to(ctx))
                            else:
                                if not isinstance(result, str):
                                    # repr all non-strings
                                    result = repr(result)

                                if len(result) > 2000:
                                    # inconsistency here, results get wrapped in codeblocks when they are too large
                                    #  but don't if they're not. probably not that bad, but noting for later review
                                    paginator = WrappedPaginator(
                                        prefix='```py',
                                        suffix='```',
                                        max_size=1985)

                                    paginator.add_line(result)

                                    interface = PaginatorInterface(
                                        ctx.bot, paginator, owner=ctx.author)
                                    send(await interface.send_to(ctx))
                                else:
                                    if result.strip() == '':
                                        result = "\u200b"

                                    send(await ctx.send(
                                        result.replace(self.bot.http.token,
                                                       "[token omitted]")))
            finally:
                scope.clear_intersection(arg_dict)
示例#15
0
 async def paginate(self, *words, destination=None):
     embed = discord.Embed(color=discord.Colour.blurple())
     pg = WrappedPaginator(prefix="", suffix="", max_size=2048)
     for line in words:
         pg.add_line(line)
     inf = PaginatorEmbedInterface(self.bot,
                                   pg,
                                   owner=self.author,
                                   embed=embed)
     await inf.send_to(destination or self)
示例#16
0
文件: utils.py 项目: csharpisez/bot
	async def reminders(self, ctx):
		mine = sorted(self.reminders.get(ctx.author.id, []), key=lambda r: r['for'])
		if not mine:
			return await ctx.error('You have no reminders.')
		paginator = WrappedPaginator(prefix='', suffix='', max_size=1980)
		for i, r in enumerate(mine):
			forwhen = datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc).strftime('%b %-d %Y @ %I:%M %p')
			delta = humanfriendly.format_timespan(datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc) - datetime.datetime.now(datetime.timezone.utc), max_units=2)
			paginator.add_line(f'[{i + 1}] {r["reminder"]} - {forwhen} ({delta})')
		interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author)
		return await interface.send_to(ctx)
示例#17
0
    async def jsk_python_result_handling(self, ctx: commands.Context, result):  # pylint: disable=too-many-return-statements
        """
        Determines what is done with a result when it comes out of jsk py.
        This allows you to override how this is done without having to rewrite the command itself.
        What you return is what gets stored in the temporary _ variable.
        """

        if isinstance(result, discord.Message):
            return await ctx.send(f"<Message <{result.jump_url}>>")

        if isinstance(result, discord.File):
            return await ctx.send(file=result)

        if isinstance(result, discord.Embed):
            return await ctx.send(embed=result)

        if isinstance(result, PaginatorInterface):
            return await result.send_to(ctx)

        if not isinstance(result, str):
            # repr all non-strings
            result = repr(result)

        # Eventually the below handling should probably be put somewhere else
        if len(result) <= 2000:
            if result.strip() == '':
                result = "\u200b"

            return await ctx.send(
                result.replace(self.bot.http.token, "[token omitted]"),
                allowed_mentions=discord.AllowedMentions.none())

        if use_file_check(ctx,
                          len(result)):  # File "full content" preview limit
            # Discord's desktop and web client now supports an interactive file content
            #  display for files encoded in UTF-8.
            # Since this avoids escape issues and is more intuitive than pagination for
            #  long results, it will now be prioritized over PaginatorInterface if the
            #  resultant content is below the filesize threshold
            return await ctx.send(file=discord.File(
                filename="output.py", fp=io.BytesIO(result.encode('utf-8'))))

        # inconsistency here, results get wrapped in codeblocks when they are too large
        #  but don't if they're not. probably not that bad, but noting for later review
        paginator = WrappedPaginator(prefix='```py',
                                     suffix='```',
                                     max_size=1985)

        paginator.add_line(result)

        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
        return await interface.send_to(ctx)
示例#18
0
 async def info(self, ctx, video: str):
     if findvideo(video):
         video = findvideo(video)
     videoinfo = await self.loop.run_in_executor(None,
                                                 func=functools.partial(
                                                     self.video_info,
                                                     video))
     try:
         videoinfo = videoinfo['items'][0]
     except (KeyError, IndexError):
         return await ctx.error(
             f'Couldn\'t find a video. Please provide a valid YouTube video URL'
         )
     title = videoinfo['snippet']['title']
     vid = videoinfo['id']
     author = videoinfo['snippet']['channelTitle']
     authorid = videoinfo['snippet']['channelId']
     published = videoinfo['snippet']['publishedAt'].replace(
         'T', ' ').split('.')[0]
     duration = videoinfo['contentDetails']['duration'].replace(
         'PT', '').replace('H',
                           ' Hrs ').replace('M',
                                            ' Mins ').replace('S', 'Secs')
     description = videoinfo['snippet']['description']
     paginator = WrappedPaginator(
         prefix='```\nDescription (Use controls to change page)\n',
         suffix='```',
         max_size=1895)
     for line in description.split('\n'):
         paginator.add_line(line)
     views = format(
         int(videoinfo.get('statistics', {}).get('viewCount', 0)), ',d')
     likes = format(
         int(videoinfo.get('statistics', {}).get('likeCount', 0)), ',d')
     dislikes = format(
         int(videoinfo.get('statistics', {}).get('dislikeCount', 0)), ',d')
     comments = format(
         int(videoinfo.get('statistics', {}).get('commentCount', 0)), ',d')
     embed = discord.Embed(title=f"Video info for {video}",
                           color=ctx.author.color,
                           timestamp=datetime.datetime.utcnow())
     embed.add_field(
         name=videoinfo["snippet"]["title"],
         value=
         f"» Link: [{title}](https://youtu.be/{vid} 'Click here to watch the video')\n» Author: [{author}](https://youtube.com/channel/{authorid} 'Click here to checkout {author} channel')\n» Published: {published}\n» Views: {views}\n» Likes: {likes}\n» Dislikes: {dislikes}\n» Comments: {comments}",
         inline=False)
     interface = PaginatorEmbedInterface(ctx.bot,
                                         paginator,
                                         owner=ctx.author,
                                         _embed=embed)
     return await interface.send_to(ctx)
示例#19
0
 async def eval(self, ctx, *, code: str):
     env = {
         "ctx":
         ctx,
         "author":
         ctx.author,
         "message":
         ctx.message,
         "guild":
         ctx.guild,
         "bot":
         self.bot,
         "reference":
         ctx.message.reference,
         "resolved":
         ctx.message.reference.resolved if ctx.message.reference else None,
     }
     env.update(globals())
     imports = "import asyncio\n"
     "import discord\nfrom discord.ext import commands\nimport aiohttp\n"
     body = "async def func():\n" + textwrap.indent(imports + code, "    ")
     try:
         import_expression.exec(body, env, locals())
     except Exception as e:
         etype = type(e)
         trace = e.__traceback__
         lines = traceback.format_exception(etype, e, trace)
         paginator = WrappedPaginator(max_size=500,
                                      prefix="A weird error occured```py",
                                      suffix="```")
         paginator.add_line("".join(lines))
         interface = PaginatorInterface(ctx.bot,
                                        paginator,
                                        owner=ctx.author)
         return await interface.send_to(ctx)
     try:
         maybe_coro = locals()["func"]()
         if inspect.isasyncgen(maybe_coro):
             async for i in maybe_coro:
                 await ctx.send(i)
             return
         thing = await maybe_coro
         if thing:
             if isinstance(thing, discord.Embed):
                 return await ctx.send(embed=thing)
             if isinstance(thing, discord.File):
                 return await ctx.send(file=thing)
             else:
                 await ctx.send(thing)
     except Exception as e:
         await ctx.send(e)
示例#20
0
async def auto_paginate(ctx,
                        text,
                        prefix='```',
                        suffix='```',
                        max_size=2000,
                        wrap_at=(' ', '\n')):
    paginator = WrappedPaginator(prefix=prefix,
                                 suffix=suffix,
                                 max_size=max_size,
                                 wrap_on=wrap_at)
    paginator.add_line(text)
    interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
    await interface.send_to(ctx)
    return interface.message
示例#21
0
    async def jsk_disassemble(self, ctx: commands.Context, *, argument: codeblock_converter):
        """
        Disassemble Python code into bytecode.
        """

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)

        async with ReplResponseReactor(ctx.message):
            paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)

            for line in disassemble(argument.content, arg_dict=arg_dict):
                paginator.add_line(line)

            interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
            await interface.send_to(ctx)
示例#22
0
def test_wrapped_paginator():
    paginator = WrappedPaginator(max_size=200)
    paginator.add_line("abcde " * 50)
    assert len(paginator.pages) == 2

    paginator = WrappedPaginator(max_size=200, include_wrapped=False)
    paginator.add_line("abcde " * 50)
    assert len(paginator.pages) == 2
示例#23
0
 async def config(self, ctx, option: str = None):
     if not option:
         paginator = WrappedPaginator(prefix='```ini', suffix='```', max_size=800)
         gconf = self.bot.configs[ctx.guild.id]
         for opt, data in gconf.options.items():
             current = gconf.get(opt)
             if isinstance(current, list):
                 current = ', '.join(str(current))
             accepted = data["accepts"]
             if isinstance(accepted, list):
                 accepted = f'List of {accepted[0].__name__}'
             else:
                 accepted = accepted.__name__
             paginator.add_line(f'[{opt}]\n{data["description"].split(" | ")[-1]}\nDefault: {data["default"]}\nCurrent: {gconf.get(opt)}\nAccepts: {accepted}\n')
         interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
         return await interface.send_to(ctx)
示例#24
0
	async def modlogs(self, ctx, user: UserWithFallback = None):
		"""PFXmodlogs <user>"""
		if not user:
			user = ctx.author
		try:
			if type(user) == discord.User or type(user) == discord.Member:
				mlogs = self.modlogs[ctx.guild.id][user.id]
			elif type(user) == int:
				mlogs = self.modlogs[ctx.guild.id][user]
		except KeyError:
			return await ctx.send(f'<a:fireFailed:603214400748257302> No logs found.')
		paginator = WrappedPaginator(prefix='', suffix='')
		for log in mlogs:
			paginator.add_line(f'**Case ID**: {log["caseid"]}\n**Type**: {log["type"].capitalize()}\n**User**: {user}\n**Reason**: {log["reason"]}\n**Date**: {log["date"]}\n**-----------------**')
		embed = discord.Embed(color=discord.Color(15105570), timestamp=datetime.datetime.utcnow())
		interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed)
		await interface.send_to(ctx)
示例#25
0
文件: mod.py 项目: TAG-Epic/bot
    async def skiermod(self, ctx, *, mod: str = None):
        if mod is None:
            return await ctx.error("You need to provide a mod name")
        route = Route(
            'GET',
            f'/mods'
        )
        try:
            mods = await self.bot.http.sk1er.request(route)
        except Exception:
            return await ctx.error(f'Failed to fetch mods')
        names = {}
        for m in mods:
            names[mods[m]['display'].lower()] = m
            for mod_id in mods[m]['mod_ids']:
                names[mod_id.lower()] = m
        if mod.lower() not in names:
            return await ctx.error(f'Unknown mod.')
        else:
            mod = mods[names[mod.lower()]]
        route = Route(
            'GET',
            f'/mods_analytics'
        )
        try:
            analytics = await self.bot.http.sk1er.request(route)
            analytics = analytics.get(mod['mod_ids'][0], {})
        except Exception:
            return await ctx.error(f'Failed to fetch mod analytics')
        embed = discord.Embed(
            title=mod['display'],
            colour=ctx.author.color,
            url=f"https://sk1er.club/mods/{mod['mod_ids'][0]}",
            description=mod['short'],
            timestamp=datetime.datetime.utcnow()
        )
        embed.add_field(name="Versions", value='\n'.join([f'**{k}**: {v}' for k, v in mod['latest'].items()]), inline=False)
        embed.add_field(name="Creator", value=f'''**__{mod['vendor']['name']}__**
[Website]({mod['vendor']['website']})
[Twitter]({mod['vendor']['twitter']})
[YouTube]({mod['vendor']['youtube']})
''', inline=False)
        if analytics:
            embed.add_field(name="Analytics", value=f"Total: {analytics['total']:,d}, Online: {analytics['online']:,d}, Last Day: {analytics['day']:,d}, Last Week: {analytics['week']:,d}", inline=False)
        await ctx.send(embed=embed)
        paginator = WrappedPaginator(prefix='', suffix='', max_size=490)
        for mcv in mod['changelog']:
            paginator.add_line(f'**__{mcv}__**')
            for v in mod['changelog'][mcv]:
                changelog = mod["changelog"][mcv][v][0]
                time = datetime.datetime.utcfromtimestamp(changelog["time"] / 1000).strftime('%d/%m/%Y @ %I:%M:%S %p')
                paginator.add_line(f'**{v}**: {changelog["text"]} ({time})')
            paginator.add_line('-----------------')
        embed = discord.Embed(color=ctx.author.color, title='Changelogs', timestamp=datetime.datetime.utcnow())
        interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed)
        await interface.send_to(ctx)
示例#26
0
    async def jsk_python_inspect(self, ctx: commands.Context, *, argument: codeblock_converter):  # pylint: disable=too-many-locals
        """
        Evaluation of Python code with inspect information.
        """

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    executor = AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict)
                    async for send, result in AsyncSender(executor):
                        self.last_result = result

                        header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        lines = [f"=== {header} ===", ""]

                        for name, res in all_inspections(result):
                            lines.append(f"{name:16.16} :: {res}")

                        text = "\n".join(lines)

                        # Guild's advertised limit minus 1KiB for the HTTP content
                        filesize_threshold = (ctx.guild.filesize_limit if ctx.guild else 8 * 1024 * 1024) - 1024

                        if len(text) < filesize_threshold:
                            send(await ctx.send(file=discord.File(
                                filename="inspection.prolog",
                                fp=io.BytesIO(text.encode('utf-8'))
                            )))
                        else:
                            paginator = WrappedPaginator(prefix="```prolog", max_size=1985)

                            paginator.add_line(text)

                            interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                            send(await interface.send_to(ctx))
        finally:
            scope.clear_intersection(arg_dict)
示例#27
0
    async def jsk_source(self, ctx: commands.Context, *, command_name: str):
        """
        Displays the source code for a command.
        """

        command = self.bot.get_command(command_name)
        if not command:
            return await ctx.send(f"Couldn't find command `{command_name}`.")

        try:
            source_lines, _ = inspect.getsourcelines(command.callback)
        except (TypeError, OSError):
            return await ctx.send(
                f"Was unable to retrieve the source for `{command}` for some reason."
            )

        filename = "source.py"

        try:
            filename = pathlib.Path(inspect.getfile(command.callback)).name
        except (TypeError, OSError):
            pass

        # getsourcelines for some reason returns WITH line endings
        source_text = ''.join(source_lines)

        # Guild's advertised limit minus 1KiB for the HTTP content
        filesize_threshold = (ctx.guild.filesize_limit if ctx.guild else 8 *
                              1024 * 1024) - 1024

        if len(source_text) < filesize_threshold:
            await ctx.send(file=discord.File(
                filename=filename, fp=io.BytesIO(source_text.encode('utf-8'))))
        else:
            paginator = WrappedPaginator(prefix='```py',
                                         suffix='```',
                                         max_size=1985)

            paginator.add_line(
                source_text.replace('```', '``\N{zero width space}`'))

            interface = PaginatorInterface(ctx.bot,
                                           paginator,
                                           owner=ctx.author)
            await interface.send_to(ctx)
示例#28
0
    def __init__(self, ctx, text, *, codeblocks=False, max_size=2000):
        if codeblocks:
            prefix = "```"
            suffix = "```"
        else:
            prefix = ""
            suffix = ""

        paginator = CommandPaginator(prefix=prefix,
                                     suffix=suffix,
                                     max_size=max_size - 200)
        for line in text.split('\n'):
            paginator.add_line(line)

        super().__init__(ctx,
                         entries=paginator.pages,
                         per_page=1,
                         show_entry_count=False)
示例#29
0
    async def jsk_source(self, ctx: commands.Context, *, command_name: str):
        """
        Displays the source code for a command.
        """

        command = self.bot.get_command(command_name) or self.get_slash_command(
            command_name)
        if not command:
            return await ctx.send(f"Couldn't find command `{command_name}`.")

        try:
            source_lines, _ = inspect.getsourcelines(command.callback)
        except (TypeError, OSError):
            return await ctx.send(
                f"Was unable to retrieve the source for `{command}` for some reason."
            )

        filename = "source.py"

        try:
            filename = pathlib.Path(inspect.getfile(command.callback)).name
        except (TypeError, OSError):
            pass

        # getsourcelines for some reason returns WITH line endings
        source_text = ''.join(source_lines)

        if use_file_check(
                ctx, len(source_text)):  # File "full content" preview limit
            await ctx.send(file=disnake.File(
                filename=filename, fp=io.BytesIO(source_text.encode('utf-8'))))
        else:
            paginator = WrappedPaginator(prefix='```py',
                                         suffix='```',
                                         max_size=1985)

            paginator.add_line(
                source_text.replace('```', '``\N{zero width space}`'))

            interface = PaginatorInterface(ctx.bot,
                                           paginator,
                                           owner=ctx.author)
            await interface.send_to(ctx)
示例#30
0
文件: fire.py 项目: fossabot/Fire
 async def listguilds(self, ctx):
     """PFXlistguilds"""
     if not isadmin(ctx):
         return
     paginator = WrappedPaginator(prefix='```vbs',
                                  suffix='```',
                                  max_size=1500)
     gcount = 1
     for guild in self.bot.guilds:
         if guild == ctx.guild:
             current = ' (HERE)'
         else:
             current = ''
         #paginator.add_line(f'[{gcount}] {guild.name}{current} || {guild.owner} || {guild.member_count} Members')
         paginator.add_line(
             f'[{gcount}] {guild.name}{current} || {guild.owner} || {guild.member_count} Members'
         )
         gcount = gcount + 1
     interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
     await interface.send_to(ctx)