Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
jishaku
https://jishaku.readthedocs.io/en/latest/
Admin
jishaku is a debugging and utility extension for discord.py bots.
Tokens:
39,485
Snippets:
341
Trust Score:
9.6
Update:
1 month ago
Context
Chat
Benchmark
37.58
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### AsyncSender usage example and its output Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/functools.html Demonstrates how to use the AsyncSender class to iterate over an async generator while sending values back into it. The example shows the expected output sequence, illustrating the send and receive flow. ```python3 async def foo(): print("foo yielding 1") x = yield 1 print(f"foo received {x}") yield 3 async for send, result in AsyncSender(foo()): print(f"asyncsender received {result}") send(2) ``` ```text foo yielding 1 asyncsender received 1 foo received 2 asyncsender received 3 ``` -------------------------------- ### Initialize MinimalPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_sources/api.rst.txt Example of using the MinimalPaginatorHelp class to customize the help command for a discord.py bot. ```python3 from discord.ext import commands from jishaku.help_command import MinimalPaginatorHelp bot = commands.Bot('?', help_command=MinimalPaginatorHelp()) ``` -------------------------------- ### PaginatorInterface class with usage example Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/paginators.html A message and reaction based interface for paginators. The docstring includes an example of using it with a standard Paginator. ```python class PaginatorInterface(ui.View): # pylint: disable=too-many-instance-attributes, too-many-public-methods """ A message and reaction based interface for paginators. This allows users to interactively navigate the pages of a Paginator, and supports live output. An example of how to use this with a standard Paginator: .. code:: python3 from discord.ext import commands from jishaku.paginators import PaginatorInterface # In a command somewhere... # Paginators need to have a reduced max_size to accommodate the extra text added by the interface. paginator = commands.Paginator(max_size=1900) # Populate the paginator with some information for line in range(100): paginator.add_line(f"Line {line + 1}") # Create and send the interface. # The 'owner' field determines who can interact with this interface. If it's None, anyone can use it. interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author) await interface.send_to(ctx) # send_to creates a task and returns control flow. # It will raise if the interface can't be created, e.g., if there's no reaction permission in the channel. # Once the interface has been sent, line additions have to be done asynchronously, so the interface can be updated. await interface.add_line("My, the Earth sure is full of things!") # You can also check if it's closed using the 'closed' property. if not interface.closed: await interface.add_line("I'm still here!") """ def __init__( self, bot: BotT, paginator: commands.Paginator, additional_buttons: typing.Optional[typing.List[ui.Button[typing.Self]]] = None, **kwargs: typing.Any ): if not isinstance(paginator, commands.Paginator): # type: ignore raise TypeError('paginator must be a commands.Paginator instance') self._display_page = 0 self.bot = bot self.message = None self.paginator = paginator ``` -------------------------------- ### ShellReader usage example Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/shell.html Example from the ShellReader docstring showing how to use the class in a with statement and iterate over its output asynchronously. It prints 'one', then 'two' after 5 seconds. ```python3 # reader should be in a with statement to ensure it is properly closed with ShellReader('echo one; sleep 5; echo two') as reader: # prints 'one', then 'two' after 5 seconds async for x in reader: print(x) ``` -------------------------------- ### Scope class usage examples Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/scope.html Shows three ways to create a Scope: empty, imitating the current real scope, and with a pre-existing global key. These are documented in the class docstring. ```python scope = Scope() # an empty Scope scope = Scope(globals(), locals()) # a Scope imitating the current, real scope. scope = Scope({'a': 3}) # a Scope with a pre-existing global scope key, and an empty local scope. ``` -------------------------------- ### Python evaluation command syntax Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Examples of using the jsk py command with single-line expressions or multi-line code blocks. ```markdown ?jsk py 3 + 4 ?jsk py ```py return 3 + 4 ``` ``` -------------------------------- ### executor_function decorator example with PIL and discord.py Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/functools.html Shows how to use the executor_function decorator to wrap a synchronous function that processes an image with PIL, making it awaitable in an async context. The example includes a discord.py bot command that uses the wrapped function to send a generated image. ```python3 from io import BytesIO from PIL import Image from jishaku.functools import executor_function @executor_function def color_processing(color: discord.Color): with Image.new('RGB', (64, 64), color.to_rgb()) as im: buff = BytesIO() im.save(buff, 'png') buff.seek(0) return buff @bot.command() async def color(ctx: commands.Context, color: discord.Color=None): color = color or ctx.author.color buff = await color_processing(color=color) await ctx.send(file=discord.File(fp=buff, filename='color.png')) ``` -------------------------------- ### Using contextual variables in Python evaluation Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Example of using the _bot and _author contextual variables to interact with Discord. ```markdown ?jsk py ```py channel = _bot.get_channel(123456789012345678) await channel.send(_author.avatar_url_as(format='png')) ``` ``` -------------------------------- ### Yielding results in Python evaluation Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Example of using yield within a code block to receive results during execution. ```markdown ?jsk py ```py for x in range(5): yield x ``` ``` -------------------------------- ### jishaku.help_command source: DefaultPaginatorHelp, DefaultEmbedPaginatorHelp, MinimalPaginatorHelp, MinimalEmbedPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/help_command.html The full source of jishaku.help_command defines four HelpCommand subclasses that use paginator interfaces. DefaultPaginatorHelp and MinimalPaginatorHelp override __init__ to set a paginator with max_size=1980, while all classes override send_pages to send pages via PaginatorInterface or PaginatorEmbedInterface. Requires discord.ext.commands and jishaku.paginators. ```python # -*- coding: utf-8 -*- """ jishaku.help_command ~~~~~~~~~~~~~~~~~~~~ HelpCommand subclasses with jishaku features :copyright: (c) 2021 Devon (scarletcafe) R :license: MIT, see LICENSE for more details. """ import typing from discord.ext import commands from jishaku.paginators import PaginatorEmbedInterface, PaginatorInterface [docs] class DefaultPaginatorHelp(commands.DefaultHelpCommand): """ A subclass of :class:`commands.DefaultHelpCommand` that uses a PaginatorInterface for pages. """ def __init__(self, **options: typing.Any): paginator = options.pop('paginator', commands.Paginator(max_size=1980)) super().__init__(paginator=paginator, **options) [docs] async def send_pages(self): destination = self.get_destination() interface = PaginatorInterface(self.context.bot, self.paginator, owner=self.context.author) await interface.send_to(destination) [docs] class DefaultEmbedPaginatorHelp(commands.DefaultHelpCommand): """ A subclass of :class:`commands.DefaultHelpCommand` that uses a PaginatorEmbedInterface for pages. """ [docs] async def send_pages(self): destination = self.get_destination() interface = PaginatorEmbedInterface(self.context.bot, self.paginator, owner=self.context.author) await interface.send_to(destination) [docs] class MinimalPaginatorHelp(commands.MinimalHelpCommand): """ A subclass of :class:`commands.MinimalHelpCommand` that uses a PaginatorInterface for pages. """ def __init__(self, **options: typing.Any): paginator = options.pop('paginator', commands.Paginator(prefix=None, suffix=None, max_size=1980)) super().__init__(paginator=paginator, **options) [docs] async def send_pages(self): destination = self.get_destination() interface = PaginatorInterface(self.context.bot, self.paginator, owner=self.context.author) await interface.send_to(destination) [docs] class MinimalEmbedPaginatorHelp(commands.MinimalHelpCommand): """ A subclass of :class:`commands.MinimalHelpCommand` that uses a PaginatorEmbedInterface for pages. """ [docs] async def send_pages(self): destination = self.get_destination() interface = PaginatorEmbedInterface(self.context.bot, self.paginator, owner=self.context.author) await interface.send_to(destination) ``` -------------------------------- ### jishaku.repl.scope.get_parent_var Source: https://jishaku.readthedocs.io/en/latest/api.html Directly gets a variable from a parent frame-scope. ```APIDOC ## jishaku.repl.scope.get_parent_var ### Description Directly gets a variable from a parent frame-scope. ### Parameters - `_name` (str) - The variable name to get. - `_global_ok` (bool) - Optional - Whether to allow global scope. - `_default` (Any) - Optional - Default value if not found. - `_skip_frames` (int) - Optional - Number of frames to skip. ### Returns - The content of the variable found by the given name, or None. ### Return type - Any ``` -------------------------------- ### Implement PaginatorInterface for interactive navigation Source: https://jishaku.readthedocs.io/en/latest/api.html Create a PaginatorInterface to allow users to navigate through paginated content. Ensure the paginator's max_size is reduced to account for interface text. ```python from discord.ext import commands from jishaku.paginators import PaginatorInterface # In a command somewhere... # Paginators need to have a reduced max_size to accommodate the extra text added by the interface. paginator = commands.Paginator(max_size=1900) # Populate the paginator with some information for line in range(100): paginator.add_line(f"Line {line + 1}") # Create and send the interface. # The 'owner' field determines who can interact with this interface. If it's None, anyone can use it. interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author) await interface.send_to(ctx) # send_to creates a task and returns control flow. # It will raise if the interface can't be created, e.g., if there's no reaction permission in the channel. # Once the interface has been sent, line additions have to be done asynchronously, so the interface can be updated. await interface.add_line("My, the Earth sure is full of things!") # You can also check if it's closed using the 'closed' property. if not interface.closed: await interface.add_line("I'm still here!") ``` -------------------------------- ### MinimalPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_sources/api.rst.txt A minimal help command class that uses a paginator. It is part of the jishaku.help_command module. ```APIDOC ## MinimalPaginatorHelp ### Description A minimal help command class that uses a paginator. It is part of the jishaku.help_command module. ### Module jishaku.help_command ### Members - (Autogenerated members are not listed here; refer to the source documentation.) ``` -------------------------------- ### MinimalEmbedPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_sources/api.rst.txt A minimal help command class that uses an embed paginator. It is part of the jishaku.help_command module. ```APIDOC ## MinimalEmbedPaginatorHelp ### Description A minimal help command class that uses an embed paginator. It is part of the jishaku.help_command module. ### Module jishaku.help_command ### Members - (Autogenerated members are not listed here; refer to the source documentation.) ``` -------------------------------- ### MinimalPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/api.html A subclass of commands.MinimalHelpCommand that uses a PaginatorInterface for pages. It provides an asynchronous send_pages() method to send the page output from the paginator to the destination. ```APIDOC ## class jishaku.help_command.MinimalPaginatorHelp(*args: Any, **kwargs: Any) ### Description A subclass of commands.MinimalHelpCommand that uses a PaginatorInterface for pages. ### Method await send_pages() ### Description This function is a coroutine. A helper utility to send the page output from paginator to the destination. ### Usage Example ```python from discord.ext import commands from jishaku.help_command import MinimalPaginatorHelp bot = commands.Bot('?', help_command=MinimalPaginatorHelp()) ``` ``` -------------------------------- ### get_parent_var Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/scope.html Directly gets a variable from a parent frame-scope. Returns the content of the variable found by the given name, or the default value if not found. ```APIDOC ## get_parent_var ### Description Directly gets a variable from a parent frame-scope. Returns the content of the variable found by the given name, or the default value if not found. ### Method get_parent_var(name, global_ok=False, default=None, skip_frames=0) ### Parameters #### name - **type**: str - Required - The variable name to search for. #### global_ok - **type**: bool - Optional - Whether to also check the global scope of frames. Defaults to False. #### default - **type**: Any - Optional - The default value to return if the variable is not found. Defaults to None. #### skip_frames - **type**: int - Optional - Number of frames to skip from the top of the stack. Defaults to 0. ### Returns Any - The content of the variable found by the given name, or the default value. ``` -------------------------------- ### Load Jishaku cog manually (not recommended) Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Creates a custom extension that adds the Jishaku cog directly. The source explicitly recommends against this approach. ```python3 from jishaku.cog import Jishaku def setup(bot: commands.Bot): # I don't recommend doing this! bot.add_cog(Jishaku(bot=bot)) ``` -------------------------------- ### Scope.__init__ Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/scope.html Initializes a new Scope instance with optional global and local dictionaries. If not provided, empty dictionaries are used. ```APIDOC ## Scope.__init__ ### Description Initializes a new Scope instance with optional global and local dictionaries. If not provided, empty dictionaries are used. ### Method Constructor ### Parameters #### globals_ - **type**: Optional[Dict[str, Any]] - Optional - The global scope dictionary. #### locals_ - **type**: Optional[Dict[str, Any]] - Optional - The local scope dictionary. ### Returns None ``` -------------------------------- ### DefaultPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_sources/api.rst.txt A help command class that uses a paginator. It is part of the jishaku.help_command module. ```APIDOC ## DefaultPaginatorHelp ### Description A help command class that uses a paginator. It is part of the jishaku.help_command module. ### Module jishaku.help_command ### Members - (Autogenerated members are not listed here; refer to the source documentation.) ``` -------------------------------- ### DefaultEmbedPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/_sources/api.rst.txt A help command class that uses an embed paginator. It is part of the jishaku.help_command module. ```APIDOC ## DefaultEmbedPaginatorHelp ### Description A help command class that uses an embed paginator. It is part of the jishaku.help_command module. ### Module jishaku.help_command ### Members - (Autogenerated members are not listed here; refer to the source documentation.) ``` -------------------------------- ### MinimalEmbedPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/api.html A subclass of commands.MinimalHelpCommand that uses a PaginatorEmbedInterface for pages. It provides an asynchronous send_pages() method to send the page output from the paginator to the destination. ```APIDOC ## class jishaku.help_command.MinimalEmbedPaginatorHelp(*args: Any, **kwargs: Any) ### Description A subclass of commands.MinimalHelpCommand that uses a PaginatorEmbedInterface for pages. ### Method await send_pages() ### Description This function is a coroutine. A helper utility to send the page output from paginator to the destination. ### Usage Example ```python from discord.ext import commands from jishaku.help_command import MinimalEmbedPaginatorHelp bot = commands.Bot('?', help_command=MinimalEmbedPaginatorHelp()) ``` ``` -------------------------------- ### Create a custom cog with STANDARD_FEATURES and OPTIONAL_FEATURES Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Creates a cog that includes both standard and optional features, resulting in an almost identical cog to the standard Jishaku. ```python3 from discord.ext import commands from jishaku.cog import STANDARD_FEATURES, OPTIONAL_FEATURES class CustomDebugCog(*OPTIONAL_FEATURES, *STANDARD_FEATURES): pass def setup(bot: commands.Bot): bot.add_cog(CustomDebugCog(bot=bot)) ``` -------------------------------- ### Create line cache for tracebacks Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/compilation.html Populates the line cache with the current source so that tracebacks show correct source lines. Returns the list of lines. ```python lines = [line + '\n' for line in self.source.splitlines()] linecache.cache['<repl>'] = ( len(self.source), # Source length None, # Time modified (None bypasses expunge) lines, # Line list '<repl>' # 'True' filename ) return lines ``` -------------------------------- ### DefaultPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/api.html A subclass of commands.DefaultHelpCommand that uses a PaginatorInterface for pages. It provides an asynchronous send_pages() method to send the page output from the paginator to the destination. ```APIDOC ## class jishaku.help_command.DefaultPaginatorHelp(*args: Any, **kwargs: Any) ### Description A subclass of commands.DefaultHelpCommand that uses a PaginatorInterface for pages. ### Method await send_pages() ### Description This function is a coroutine. A helper utility to send the page output from paginator to the destination. ### Usage Example ```python from discord.ext import commands from jishaku.help_command import DefaultPaginatorHelp bot = commands.Bot('?', help_command=DefaultPaginatorHelp()) ``` ``` -------------------------------- ### jsk [load|reload] [extensions...] Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Loads or reloads a number of extensions. Supports wildcards and brace expansion. Reloading '~' reloads all loaded extensions. ```APIDOC ## jsk [load|reload] [extensions...] ### Description Loads or reloads a number of extensions. Extension names are delimited by spaces. Supports wildcards like 'cogs.*' and brace expansion like 'foo.bar.cogs.{baz,quux,garply}'. 'jsk reload ~' reloads every loaded extension. ### Method Command ### Endpoint jsk [load|reload] [extensions...] ### Parameters #### Arguments - **extensions** (str) - Optional - Extension names to load/reload. If omitted, no action? (Source does not specify behavior without arguments.) ### Response #### Success Response - Confirmation of loaded/reloaded extensions. #### Error Response - Traceback if loading fails. ``` -------------------------------- ### Load jishaku as an extension Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Loads the jishaku cog using the standard extension loading method. Both synchronous and asynchronous forms are shown. ```python3 bot.load_extension('jishaku') # or await bot.load_extension("jishaku") ``` -------------------------------- ### Create a custom cog with STANDARD_FEATURES Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Creates a cog using only the standard features guaranteed by jishaku, excluding optional features. ```python3 from discord.ext import commands from jishaku.cog import STANDARD_FEATURES class CustomDebugCog(*STANDARD_FEATURES): pass def setup(bot: commands.Bot): bot.add_cog(CustomDebugCog(bot=bot)) ``` -------------------------------- ### DefaultEmbedPaginatorHelp Source: https://jishaku.readthedocs.io/en/latest/api.html A subclass of commands.DefaultHelpCommand that uses a PaginatorEmbedInterface for pages. It provides an asynchronous send_pages() method to send the page output from the paginator to the destination. ```APIDOC ## class jishaku.help_command.DefaultEmbedPaginatorHelp(*args: Any, **kwargs: Any) ### Description A subclass of commands.DefaultHelpCommand that uses a PaginatorEmbedInterface for pages. ### Method await send_pages() ### Description This function is a coroutine. A helper utility to send the page output from paginator to the destination. ### Usage Example ```python from discord.ext import commands from jishaku.help_command import DefaultEmbedPaginatorHelp bot = commands.Bot('?', help_command=DefaultEmbedPaginatorHelp()) ``` ``` -------------------------------- ### Paginator initialization with buttons and validation Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/paginators.html Constructor of the paginator class. It sets owner, emojis, timeout, delete_message, and creates dynamic buttons. Raises ValueError if page_size exceeds max_page_size (2000). Override button_definitions() to customize buttons. ```python self.owner = kwargs.pop('owner', None) self.emojis = kwargs.pop('emoji', EMOJI_DEFAULT) self.timeout_length = kwargs.pop('timeout', 7200) self.delete_message = kwargs.pop('delete_message', False) self.sent_page_reactions = False self.task: typing.Optional[asyncio.Task[None]] = None self.send_lock: asyncio.Event = asyncio.Event() self.close_exception: typing.Optional[BaseException] = None if self.page_size > self.max_page_size: raise ValueError( f'Paginator passed has too large of a page size for this interface. ' f'({self.page_size} > {self.max_page_size})' ) super().__init__(timeout=self.timeout_length) self.button_start: DynamicButton[typing.Self] = DynamicButton( self.button_start_callback, self.button_start_label, style=discord.ButtonStyle.secondary ) self.button_previous: DynamicButton[typing.Self] = DynamicButton( self.button_previous_callback, self.button_previous_label, style=discord.ButtonStyle.secondary ) self.button_current: DynamicButton[typing.Self] = DynamicButton( self.button_current_callback, self.button_current_label, style=discord.ButtonStyle.primary ) self.button_next: DynamicButton[typing.Self] = DynamicButton( self.button_next_callback, self.button_next_label, style=discord.ButtonStyle.secondary ) self.button_last: DynamicButton[typing.Self] = DynamicButton( self.button_last_callback, self.button_last_label, style=discord.ButtonStyle.secondary ) self.button_goto: DynamicButton[typing.Self] = DynamicButton( self.button_goto_callback, self.button_goto_label, style=discord.ButtonStyle.primary ) self.button_close: DynamicButton[typing.Self] = DynamicButton( self.button_close_callback, self.button_close_label, style=discord.ButtonStyle.danger ) self.additional_buttons = additional_buttons or [] self.buttons: typing.List[ui.Button[typing.Self]] = self.button_definitions() for button in self.buttons: self.add_item(button) ``` -------------------------------- ### jsk [disassemble|dis] <argument: str> (AST) Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Compiles Python code into its Abstract Syntax Tree and formats it into a visual ASCII tree with ANSI support if usable. Output is sent as a file on desktop, otherwise as a PaginatorInterface. ```APIDOC ## jsk [disassemble|dis] <argument: str> (AST) ### Description Compiles Python code into its Abstract Syntax Tree using ast.compile and formats it into a visual ASCII tree with ANSI support if usable. Output is sent as a file on desktop, otherwise as a PaginatorInterface. ### Method Command ### Endpoint jsk [disassemble|dis] <argument: str> ### Parameters #### Arguments - **argument** (str) - Required - The Python code to compile into an AST. ### Response #### Success Response - The formatted AST tree, sent as a file or PaginatorInterface. ``` -------------------------------- ### jsk [disassemble|dis] <argument: str> Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Compiles Python code in an asynchronous context and returns the disassembly. The output is sent as a file if the sender is on desktop, otherwise as a PaginatorInterface. ```APIDOC ## jsk [disassemble|dis] <argument: str> ### Description Compiles Python code in an asynchronous context and returns the disassembly. The output is sent as a file if the sender is on desktop, otherwise as a PaginatorInterface. ### Method Command ### Endpoint jsk [disassemble|dis] <argument: str> ### Parameters #### Arguments - **argument** (str) - Required - The Python code to disassemble. ### Response #### Success Response - The disassembly output, sent as a file or PaginatorInterface. ``` -------------------------------- ### Full module source code Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/scope.html The complete source code for jishaku.repl.scope, including the Scope class and the get_parent_scope_from_var and get_parent_var functions. ```python # -*- coding: utf-8 -*- """ jishaku.repl.scope ~~~~~~~~~~~~~~~~~~ The Scope class and functions relating to it. :copyright: (c) 2021 Devon (scarletcafe) R :license: MIT, see LICENSE for more details. """ import inspect import typing [docs] class Scope: """ Class that represents a global and local scope for both scope inspection and creation. Many REPL functions expect or return this class. .. code:: python3 scope = Scope() # an empty Scope scope = Scope(globals(), locals()) # a Scope imitating the current, real scope. scope = Scope({'a': 3}) # a Scope with a pre-existing global scope key, and an empty local scope. """ __slots__ = ('globals', 'locals') def __init__( self, globals_: typing.Optional[typing.Dict[str, typing.Any]] = None, locals_: typing.Optional[typing.Dict[str, typing.Any]] = None ): self.globals: typing.Dict[str, typing.Any] = globals_ or {} self.locals: typing.Dict[str, typing.Any] = locals_ or {} [docs] def clear_intersection(self, other_dict: typing.Dict[str, typing.Any]): """ Clears out locals and globals from this scope where the key-value pair matches with other_dict. This allows cleanup of temporary variables that may have washed up into this Scope. Parameters ----------- other_dict: :class:`dict` The dictionary to be used to determine scope clearance. If a key from this dict matches an entry in the globals or locals of this scope, and the value is identical, it is removed from the scope. Returns ------- Scope The updated scope (self). """ for key, value in other_dict.items(): if key in self.globals and self.globals[key] is value: del self.globals[key] if key in self.locals and self.locals[key] is value: del self.locals[key] return self [docs] def update(self, other: 'Scope'): """ Updates this scope with the content of another scope. Parameters --------- other: :class:`Scope` The scope to overlay onto this one. Returns ------- Scope The updated scope (self). """ self.globals.update(other.globals) self.locals.update(other.locals) return self [docs] def update_globals(self, other: typing.Dict[str, typing.Any]): """ Updates this scope's globals with a dict. Parameters ----------- other: :class:`dict` The dictionary to be merged into this scope. Returns ------- Scope The updated scope (self). """ self.globals.update(other) return self [docs] def update_locals(self, other: typing.Dict[str, typing.Any]): """ Updates this scope's locals with a dict. Parameters ----------- other: :class:`dict` The dictionary to be merged into this scope. Returns ------- Scope The updated scope (self). """ self.locals.update(other) return self [docs] def get_parent_scope_from_var( name: str, global_ok: bool = False, skip_frames: int = 0 ) -> typing.Optional[Scope]: """ Iterates up the frame stack looking for a frame-scope containing the given variable name. Returns -------- Optional[Scope] The relevant :class:`Scope` or None """ stack = inspect.stack() try: for frame_info in stack[skip_frames + 1:]: frame = None try: frame = frame_info.frame if name in frame.f_locals or (global_ok and name in frame.f_globals): return Scope(globals_=frame.f_globals, locals_=frame.f_locals) finally: del frame finally: del stack return None [docs] def get_parent_var( name: str, global_ok: bool = False, default: typing.Any = None, skip_frames: int = 0 ) -> typing.Any: """ Directly gets a variable from a parent frame-scope. Returns -------- Any The content of the variable found by the given name, or None. """ scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_frames=skip_frames + 1) if not scope: return default if name in scope.locals: return scope.locals.get(name, default) return scope.globals.get(name, default) ``` -------------------------------- ### jsk permtrace <channel> [targets...] Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Traces permissions for a channel and optional targets. The source text is incomplete, but this command is documented as a user-callable command. ```APIDOC ## jsk permtrace <channel> [targets...] ### Description Traces permissions for a channel and optional targets. The source text is incomplete, but this command is documented as a user-callable command. ### Method Command ### Endpoint jsk permtrace <channel> [targets...] ### Parameters #### Arguments - **channel** (channel) - Required - The channel to trace permissions for. - **targets** (target) - Optional - Additional targets to trace permissions for. ### Response #### Success Response - Permission trace information. ``` -------------------------------- ### PaginatorInterface Source: https://jishaku.readthedocs.io/en/latest/api.html A message and reaction based interface for paginators. This allows users to interactively navigate the pages of a Paginator, and supports live output. ```APIDOC ## PaginatorInterface ### Description A message and reaction based interface for paginators. This allows users to interactively navigate the pages of a Paginator, and supports live output. ### Constructor jishaku.paginators.PaginatorInterface(_bot : Bot | AutoShardedBot_, _paginator : Paginator_, _additional_buttons : List[Button[Self]] | None = None_, _** kwargs: Any_) ### Parameters - **bot** (Bot | AutoShardedBot) - Required - The bot instance. - **paginator** (Paginator) - Required - The paginator to interface with. - **additional_buttons** (List[Button[Self]] | None) - Optional - Additional buttons to add to the interface. - **kwargs** (Any) - Optional - Additional keyword arguments. ### Methods #### add_line await add_line(_* args: Any_, _** kwargs: Any_) A proxy function that allows this PaginatorInterface to remain locked to the last page if it is already on it. #### button_close_callback await button_close_callback(_interaction : Interaction_) Button to close the interface. #### button_close_label button_close_label(__button : Button[Self]_) → str Label for closing the paginator (constant). #### button_current_callback await button_current_callback(_interaction : Interaction_) Button to refresh the interface. #### button_current_label button_current_label(__button : Button[Self]_) → str Current page label (changes on page updates). #### button_definitions button_definitions() → List[Button[Self]] This is an overridable function you can use to remove buttons or customize their order. If you only need to add buttons, consider passing additional_buttons to the constructor. #### button_goto_callback await button_goto_callback(_interaction : Interaction_) Button to jump directly to a page. #### button_goto_label button_goto_label(__button : Button[Self]_) → str Label for selecting a page (constant). #### button_last_callback await button_last_callback(_interaction : Interaction_) Button to send interface to last page. #### button_last_label button_last_label(__button : Button[Self]_) → str Endstop label for going to the last page (changes on page count). #### button_next_callback await button_next_callback(_interaction : Interaction_) Button to send interface to next page. #### button_next_label button_next_label(__button : Button[Self]_) → str Right arrow label for going to the next page (constant). #### button_previous_callback await button_previous_callback(_interaction : Interaction_) Button to send interface to previous page. #### button_previous_label button_previous_label(__button : Button[Self]_) → str Left arrow label for going to the previous page (constant). #### button_start_callback await button_start_callback(_interaction : Interaction_) Button to send interface to first page. #### button_start_label button_start_label(__button : Button[Self]_) → str Label for returning to the first page (constant). ### Properties #### closed property closed Is this interface closed? ### Example ```python from discord.ext import commands from jishaku.paginators import PaginatorInterface # In a command somewhere... # Paginators need to have a reduced max_size to accommodate the extra text added by the interface. paginator = commands.Paginator(max_size=1900) # Populate the paginator with some information for line in range(100): paginator.add_line(f"Line {line + 1}") # Create and send the interface. # The 'owner' field determines who can interact with this interface. If it's None, anyone can use it. interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author) await interface.send_to(ctx) # send_to creates a task and returns control flow. # It will raise if the interface can't be created, e.g., if there's no reaction permission in the channel. # Once the interface has been sent, line additions have to be done asynchronously, so the interface can be updated. await interface.add_line("My, the Earth sure is full of things!") # You can also check if it's closed using the 'closed' property. if not interface.closed: await interface.add_line("I'm still here!") ``` ``` -------------------------------- ### FilePaginator Source: https://jishaku.readthedocs.io/en/latest/api.html A paginator of syntax-highlighted codeblocks, read from a file-like. ```APIDOC ## Class: FilePaginator ### Description A paginator of syntax-highlighted codeblocks, read from a file-like. ### Constructor FilePaginator(fp: BinaryIO, line_span: Tuple[int, int] | None = None, language_hints: Tuple[str, ...] = (), **kwargs: Any) ### Parameters - fp (BinaryIO) - Required - A file-like (implements fp.read) to read the data for this paginator from. - line_span (Optional[Tuple[int, int]]) - Optional - A linespan to read from the file. If None, reads the whole file. - language_hints (Tuple[str, ...]) - Optional - A tuple of strings that may hint to the language of this file. This could include filenames, MIME types, or shebangs. A shebang present in the actual file will always be prioritized over this. ``` -------------------------------- ### AsyncCodeExecutor usage Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/repl/compilation.html Demonstrates how to use AsyncCodeExecutor to execute code that yields values, which can then be iterated over using an async for loop. ```python3 total = 0 # prints 1, 2 and 3 async for x in AsyncCodeExecutor('yield 1; yield 2; yield 3'): total += x print(x) # prints 6 print(total) ``` -------------------------------- ### use_file_check function Source: https://jishaku.readthedocs.io/en/latest/_modules/jishaku/paginators.html Determines if uploading a file and relying on Discord's file preview is acceptable over a PaginatorInterface. Checks size, FORCE_PAGINATOR flag, and mobile status. ```python def use_file_check( ctx: ContextA, size: int ) -> bool: """ A check to determine if uploading a file and relying on Discord's file preview is acceptable over a PaginatorInterface. """ return all([ size < 50_000, # Check the text is below the Discord cutoff point; not Flags.FORCE_PAGINATOR, # Check the user hasn't explicitly disabled this; ( # Ensure the user isn't on mobile not ctx.author.is_on_mobile() if ctx.guild and ctx.bot.intents.presences and isinstance(ctx.author, discord.Member) else True ) ]) ``` -------------------------------- ### PaginatorInterface.wait_loop Source: https://jishaku.readthedocs.io/en/latest/api.html Waits on a loop for updates to the interface. This should not be called manually - it is handled by send_to. ```APIDOC ## Method: wait_loop ### Description Waits on a loop for updates to the interface. This should not be called manually - it is handled by send_to. ### Signature await wait_loop() ``` -------------------------------- ### jsk unload [extensions...] Source: https://jishaku.readthedocs.io/en/latest/_sources/cog.rst.txt Unloads a number of extensions. Supports same matching rules as load. 'jsk unload ~' unloads all extensions including jishaku. ```APIDOC ## jsk unload [extensions...] ### Description Unloads a number of extensions. Extension names are delimited by spaces. Matching rules are the same as 'jsk load'. 'jsk unload ~' unloads every extension on your bot, including jishaku. ### Method Command ### Endpoint jsk unload [extensions...] ### Parameters #### Arguments - **extensions** (str) - Optional - Extension names to unload. ### Response #### Success Response - Confirmation of unloaded extensions. #### Error Response - Traceback if unloading fails. ```