### Running discord.py with asyncio.run() Source: https://discordpy.readthedocs.io/en/latest/migrating.html This example shows how to start the discord.py client using asyncio.run() for custom asynchronous setup before connecting to the gateway. It requires the discord library to be imported. ```Python import discord import asyncio TOKEN = "YOUR_BOT_TOKEN" client = discord.Client() async def main(): # do other async things await my_async_function() # Assuming my_async_function is defined elsewhere # start the client async with client: await client.start(TOKEN) asyncio.run(main()) ``` -------------------------------- ### Extension with Setup and Teardown Source: https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html An example extension demonstrating both `setup` for loading and `teardown` for unloading. Exceptions in `teardown` are ignored. ```python async def setup(bot): print('I am being loaded!') async def teardown(bot): print('I am being unloaded!') ``` -------------------------------- ### Example Extension: hello.py Source: https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html A basic extension that adds a 'hello' command to the bot. The `setup` function is a coroutine that takes the bot instance and adds the command. ```python from discord.ext import commands @commands.command() async def hello(ctx): await ctx.send(f'Hello {ctx.author.display_name}.') async def setup(bot): bot.add_command(hello) ``` -------------------------------- ### Using setup_hook() for asynchronous bot setup Source: https://discordpy.readthedocs.io/en/latest/migrating.html This example demonstrates subclassing discord.Client to define an asynchronous setup_hook() method. This hook is called after login and before connecting to the gateway, ideal for initializing bot features asynchronously. It requires the discord library and a TOKEN. ```Python import discord TOKEN = "YOUR_BOT_TOKEN" class MyClient(discord.Client): async def setup_hook(self): print('This is asynchronous!') client = MyClient() client.run(TOKEN) ``` -------------------------------- ### Migrating Extension Setup Function Source: https://discordpy.readthedocs.io/en/latest/migrating.html Converts a synchronous extension setup function to an asynchronous one. The `setup` function must now be a coroutine and `add_cog` must be awaited. ```Python # before def setup(bot): bot.add_cog(MyCog(bot)) # after async def setup(bot): await bot.add_cog(MyCog(bot)) ``` -------------------------------- ### Advanced Logging Setup with Rotating File Handler Source: https://discordpy.readthedocs.io/en/latest/logging.html Implement a custom, advanced logging setup using `logging.handlers.RotatingFileHandler` to manage log file size and rotation. This example also sets different log levels for the 'discord' and 'discord.http' loggers. ```python import discord import logging import logging.handlers logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) logging.getLogger('discord.http').setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( filename='discord.log', encoding='utf-8', maxBytes=32 * 1024 * 1024, # 32 MiB backupCount=5, # Rotate through 5 files ) dt_fmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{') handler.setFormatter(formatter) logger.addHandler(handler) # Assume client refers to a discord.Client subclass... # Suppress the default configuration since we have our own client.run(token, log_handler=None) ``` -------------------------------- ### Install discord.py Source: https://discordpy.readthedocs.io/en/latest/intro.html Install the discord.py library using pip. This command is for general use. ```bash python3 -m pip install -U discord.py ``` -------------------------------- ### _setup_hook() Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html A coroutine to be called to setup the bot. This is called once in login() before any events are dispatched. ```APIDOC ## _setup_hook() ### Description A coroutine to be called to setup the bot, by default this is blank. To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine. This is only called once, in `login()`, and will be called before any events are dispatched, making it a better solution than doing such setup in the `on_ready()` event. **Warning**: Since this is called _before_ the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like `wait_for()` and `wait_until_ready()`. ### Type coroutine ``` -------------------------------- ### User Install Command Decorator Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Indicates that a command should be installed for users. This is a server-side hint and does not function as a check for subcommands. ```Python import discord from discord import app_commands @app_commands.command() @app_commands.user_install() async def my_user_install_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in users by default!') ``` -------------------------------- ### Install discord.py with voice support Source: https://discordpy.readthedocs.io/en/latest/intro.html Install discord.py with voice support enabled using pip. ```bash python3 -m pip install -U discord.py[voice] ``` -------------------------------- ### Command Autocomplete Example Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html An example of how to implement autocomplete for a command's parameter, returning a list of choices based on user input. ```APIDOC ## Command Autocomplete ### Description Provides a way to generate choices for command parameters dynamically, often used for user input suggestions. ### Parameters - **current** (str) - The current input string from the user. ### Returns - List[app_commands.Choice] - A list of choices for the autocomplete suggestion. ``` -------------------------------- ### on_message Event Example Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html An example of how to handle the on_message event, including waiting for a specific reaction to a message. ```APIDOC ## on_message Event ### Description Handles incoming messages and can be used to trigger actions based on message content or reactions. ### Method Event Listener ### Endpoint N/A (Event-driven) ### Parameters #### Event Parameters - **message** (discord.Message) - The message object that triggered the event. ### Request Example ```python @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that πŸ‘ reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == 'πŸ‘' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('πŸ‘Ž') else: await channel.send('πŸ‘') ``` ### Response N/A (Event-driven) ``` -------------------------------- ### Install discord.py on Windows Source: https://discordpy.readthedocs.io/en/latest/intro.html Install the discord.py library using pip on Windows. Use 'py -3' for Python 3. ```bash py -3 -m pip install -U discord.py ``` -------------------------------- ### Allowed Installs Decorator Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Specifies the contexts (guilds, users) where a command can be installed. This is server-side verified and has limitations with subcommands. ```Python import discord from discord import app_commands @app_commands.command() @app_commands.allowed_installs(guilds=False, users=True) async def my_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in users by default!') ``` -------------------------------- ### ChannelSelect Example Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html An example demonstrating how to use a ChannelSelect within a discord.ui.LayoutView to allow users to select channels and display their mentions. ```APIDOC ## select_channels ChannelSelect ### Description Allows users to select channels from a predefined list and sends a message with the mention of the first selected channel. ### Method POST (Implicit via Interaction) ### Endpoint Interaction Callback ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Implicitly handled by discord.py interaction framework) ### Request Example ```python class MyView(discord.ui.LayoutView): action_row = discord.ui.ActionRow() @action_row.select(cls=ChannelSelect, channel_types=[discord.ChannelType.text]) async def select_channels(self, interaction: discord.Interaction, select: ChannelSelect): return await interaction.response.send_message(f'You selected {select.values[0].mention}') ``` ### Response #### Success Response (200) - **interaction.response.send_message**: Sends a message to the channel where the interaction occurred. #### Response Example ``` You selected #general ``` ``` -------------------------------- ### AppInstallationType Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Represents the installation location of an application command, specifying if it's a guild or user install. ```APIDOC ## Class discord.app_commands.AppInstallationType ### Description Represents the installation location of an application command. ### Parameters - **guild** (Optional[`bool`]) – Whether the integration is a guild install. - **user** (Optional[`bool`]) – Whether the integration is a user install. ### Properties - **guild** (`bool`) - Whether the integration is a guild install. - **user** (`bool`) - Whether the integration is a user install. ``` -------------------------------- ### Install voice dependencies on Debian-based Linux Source: https://discordpy.readthedocs.io/en/latest/intro.html Install necessary system dependencies for voice support on Debian-based Linux systems. ```bash $ apt install libffi-dev libnacl-dev python3-dev ``` -------------------------------- ### Intents Example Source: https://discordpy.readthedocs.io/en/latest/migrating.html Iterates through all available intents and prints their friendly names and values. Ensure intents are correctly configured. ```Python friendly_names = { ... 'emojis_and_stickers': 'Emojis Intent', ... } for name, value in discord.Intents.all(): print(f'{friendly_names[name]}: {value}') ``` -------------------------------- ### Minimal Discord Bot Example Source: https://discordpy.readthedocs.io/en/latest/quickstart.html This example demonstrates how to create a basic Discord bot that responds to a specific message. It requires the 'message_content' intent to be enabled. ```Python # This example requires the 'message_content' intent. import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') client.run('your token here') ``` -------------------------------- ### Guild Install Command Decorator Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Marks a command for installation within guilds. This is server-side verified and ignored in subcommands. ```Python import discord from discord import app_commands @app_commands.command() @app_commands.guild_install() async def my_guild_install_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in guilds by default!') ``` -------------------------------- ### Example Cog with Special Methods and Custom Name Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html This example demonstrates a Cog with all special methods registered and a custom name. It includes cleanup, checks, error handling, and invocation hooks. ```Python class MyCog(commands.Cog, name='Example Cog'): def cog_unload(self): print('cleanup goes here') def bot_check(self, ctx): print('bot check') return True def bot_check_once(self, ctx): print('bot check once') return True async def cog_check(self, ctx): print('cog local check') return await ctx.bot.is_owner(ctx.author) async def cog_command_error(self, ctx, error): print('Error in {0.command.qualified_name}: {1}'.format(ctx, error)) async def cog_before_invoke(self, ctx): print('cog local before: {0.command.qualified_name}'.format(ctx)) async def cog_after_invoke(self, ctx): print('cog local after: {0.command.qualified_name}'.format(ctx)) @commands.Cog.listener() async def on_message(self, message): pass ``` -------------------------------- ### Cog-Specific Before and After Invocation Hooks Example Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html This example shows how to implement before and after invocation hooks within a Cog. These hooks affect all commands within that Cog. ```Python class MyCog(commands.Cog): async def cog_before_invoke(self, ctx): ctx.secret_cog_data = 'foo' async def cog_after_invoke(self, ctx): print('{0.command} is done...'.format(ctx)) @commands.command() async def foo(self, ctx): await ctx.send(ctx.secret_cog_data) ``` -------------------------------- ### Add Listener Example Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to add event listeners using the `add_listener` method. This can be used as an alternative to the `listen` decorator. ```Python async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message') ``` -------------------------------- ### Basic discord.py event handling example Source: https://discordpy.readthedocs.io/en/latest/intro.html A simple discord.py client that logs in, prints a message when ready, and prints incoming messages. Requires the 'message_content' intent. ```python # This example requires the 'message_content' intent. import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): print(f'Message from {message.author}: {message.content}') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('my token goes here') ``` -------------------------------- ### load_extension Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Loads an extension, which is a Python module containing commands, cogs, or listeners. Requires a global 'setup' function as the entry point. ```APIDOC ## await _load_extension(name, *, package=None) ### Description Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`. ### Parameters * **name** (`str`) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. `foo.test` if you want to import `foo/test.py`. * **package** (Optional[`str`]) – The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g `.foo.test`. Defaults to `None`. ### Raises * **ExtensionNotFound** – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided `package` parameter. * **ExtensionAlreadyLoaded** – The extension is already loaded. * **NoEntryPointError** – The extension does not have a setup function. * **ExtensionFailed** – The extension or its setup function had an execution error. ``` -------------------------------- ### Event signatures before v0.10.0 Source: https://discordpy.readthedocs.io/en/latest/migrating_to_async.html Provides examples of event signatures that were common before v0.10.0, noting that some like `on_status` were removed. ```python content_copy``` def on_channel_update(channel): pass def on_member_update(member): pass def on_status(member): pass def on_server_role_update(role): pass def on_voice_state_update(member): pass def on_socket_raw_send(payload, is_binary): pass ``` ``` -------------------------------- ### Greedy Converter Example Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how the Greedy converter consumes arguments until a parsing error occurs, allowing for flexible argument parsing. ```Python content_copy``` @commands.command() async def test(ctx, numbers: Greedy[int], reason: str): await ctx.send("numbers: {}, reason: {}".format(numbers, reason)) ``` ``` -------------------------------- ### login Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Logs in the client with the specified credentials and calls the setup_hook(). ```APIDOC ## await _login(token) ### Description Logs in the client with the specified credentials and calls the `setup_hook()`. ### Parameters * **token** (`str`) – The authentication token. Do not prefix this token with anything as the library will do it for you. ### Raises * **LoginFailure** – The wrong credentials are passed. * **HTTPException** – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code. ``` -------------------------------- ### Simple Background Task in a Cog Source: https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html A basic example of a recurring task that prints an index every 5 seconds. The task is started when the Cog is initialized and cancelled when the Cog is unloaded. ```python from discord.ext import tasks, commands class MyCog(commands.Cog): def __init__(self): self.index = 0 self.printer.start() def cog_unload(self): self.printer.cancel() @tasks.loop(seconds=5.0) async def printer(self): print(self.index) self.index += 1 ``` -------------------------------- ### Migrating Extension Loading Source: https://discordpy.readthedocs.io/en/latest/migrating.html Demonstrates how to load extensions asynchronously using `setup_hook` or an `async with` block. `load_extension` must now be awaited. ```Python # before bot.load_extension('my_extension') # after using setup_hook class MyBot(commands.Bot): async def setup_hook(self): await self.load_extension('my_extension') # after using async_with async def main(): async with bot: await bot.load_extension('my_extension') await bot.start(TOKEN) asyncio.run(main()) ``` -------------------------------- ### _prepare_help_command(ctx, command) Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html A low-level coroutine method to prepare the help command before execution. Useful for setting up state in subclasses. ```APIDOC ## _prepare_help_command(ctx, command) ### Description A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it. The default implementation does nothing. This is called _inside_ the help command callback body. So all the usual rules that happen inside apply here as well. ### Parameters #### Path Parameters - **ctx** (Context) – The invocation context. - **command** (Optional[str]) – The argument passed to the help command. ``` -------------------------------- ### Setup Logging with discord.utils.setup_logging() Source: https://discordpy.readthedocs.io/en/latest/logging.html Initialize the library's default logging configuration without using `client.run()` by calling `discord.utils.setup_logging()`. You can specify the log level and whether to affect the root logger. ```python import discord discord.utils.setup_logging() # or, for example discord.utils.setup_logging(level=logging.INFO, root=False) ``` -------------------------------- ### get_command Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets a Command from the internal list of commands. This can also be used as a way to get aliases. ```APIDOC ## get_command ### Description Get a `Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual. ### Parameters #### Positional Parameters - **name** (`str`) – Required - The name of the command to get. ### Returns - The command that was requested. If not found, returns `None`. - **Return type**: Optional[`Command`] ``` -------------------------------- ### Create and activate a virtual environment Source: https://discordpy.readthedocs.io/en/latest/intro.html Create a Python virtual environment for your bot and activate it. ```bash $ cd your-bot-source $ python3 -m venv bot-env ``` ```bash $ source bot-env/bin/activate ``` ```bash $ bot-env\Scripts\activate.bat ``` ```bash $ pip install -U discord.py ``` -------------------------------- ### app_commands.describe and app_commands.choices Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Demonstrates how to use @app_commands.describe to set a description for a command parameter and @app_commands.choices to provide predefined options for that parameter. ```APIDOC ## @app_commands.describe and @app_commands.choices ### Description Used to describe command parameters and provide a list of choices for user selection. ### Method Asynchronous function decorated with app_commands decorators. ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python @app_commands.describe(fruits='fruits to choose from') @app_commands.choices(fruits=[ Choice(name='apple', value=1), Choice(name='banana', value=2), Choice(name='cherry', value=3), ]) async def fruit(interaction: discord.Interaction, fruits: Choice[int]): await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.') ``` ### Response #### Success Response (200) Sends a message indicating the user's choice. #### Response Example N/A (Message sent via interaction response) ``` -------------------------------- ### get_command Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Get a Command from the internal list of commands. This could also be used as a way to get aliases. ```APIDOC ## get_command(_name_) ### Description Get a `Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual. ### Parameters #### Path Parameters * **name** (`str`) – The name of the command to get. ### Returns The command that was requested. If not found, returns `None`. ### Return type Optional[`Command`] ``` -------------------------------- ### Initialize Bot with Mention or '!' Prefix Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to initialize a commands.Bot instance using a prefix that includes being mentioned or a specific string like '!'. This is useful for bots that should respond to mentions and a custom prefix. ```python bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) ``` -------------------------------- ### Loading an Extension Source: https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html Demonstrates how to load an extension named 'hello' using the `Bot.load_extension()` method. ```python await bot.load_extension('hello') ``` -------------------------------- ### _start(_token_, *_ , _reconnect =True_) Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html A shorthand coroutine for login() + connect(). ```APIDOC ## _start(_token_, *_ , _reconnect =True_) ### Description A shorthand coroutine for `login()` + `connect()`. ### Parameters * **token** (`str`) – The authentication token. Do not prefix this token with anything as the library will do it for you. * **reconnect** (`bool`) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). ### Raises **TypeError** – An unexpected keyword argument was received. ``` -------------------------------- ### Running the Client: Old vs. New Source: https://discordpy.readthedocs.io/en/latest/migrating_to_async.html Illustrates the change in how the client is run, from separate login and run calls to a single run call with credentials. The old method required explicit login and then running the client, while the new method combines these into one blocking call. ```python client.login('token') client.run() ``` ```python client.run('token') ``` -------------------------------- ### Basic Container Usage Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Demonstrates how to create a basic Container with a TextDisplay item. This is useful for organizing content within a LayoutView. ```Python class MyView(ui.LayoutView): container = ui.Container(ui.TextDisplay('I am a text display on a container!')) ``` -------------------------------- ### Custom Help Command Implementation Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html This snippet shows how to create a custom help command by subclassing MinimalHelpCommand and assigning it to the bot's help_command attribute. It demonstrates overriding get_command_signature and managing the help command's lifecycle within a cog. ```python class MyHelpCommand(commands.MinimalHelpCommand): def get_command_signature(self, command): return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command) class MyCog(commands.Cog): def __init__(self, bot): self._original_help_command = bot.help_command bot.help_command = MyHelpCommand() bot.help_command.cog = self def cog_unload(self): self.bot.help_command = self._original_help_command ``` -------------------------------- ### _fetch_widget Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets a Widget from a guild ID. This is a coroutine function. ```APIDOC ## _fetch_widget(_guild_id_) ### Description Gets a `Widget` from a guild ID. Note The guild must have the widget enabled to get this information. ### Method Coroutine ### Parameters #### Path Parameters * **guild_id** (`int`) – The ID of the guild. ### Raises * **Forbidden** – The widget for this guild is disabled. * **HTTPException** – Retrieving the widget failed. ### Returns The guild’s widget. ### Return type `Widget` ``` -------------------------------- ### _fetch_template Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets a Template from a discord.new URL or code. This is a coroutine function. ```APIDOC ## _fetch_template(_code_) ### Description Gets a `Template` from a discord.new URL or code. ### Method Coroutine ### Parameters #### Path Parameters * **code** (Union[`Template`, `str`]) – The Discord Template Code or URL (must be a discord.new URL). ### Raises * **NotFound** – The template is invalid. * **HTTPException** – Getting the template failed. ### Returns The template from the URL/code. ### Return type `Template` ``` -------------------------------- ### Fetch Stage Instance Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets a StageInstance for a stage channel ID. ```APIDOC ## Fetch Stage Instance ### Description Gets a StageInstance for a stage channel ID. ### Method GET (assumed) ### Endpoint /stage-instances/{channel_id} ### Parameters #### Path Parameters - **channel_id** (int) - The stage channel ID. ### Raises - **NotFound** - The stage instance or channel could not be found. - **HTTPException** - Getting the stage instance failed. ### Returns - **StageInstance** - The stage instance from the stage channel ID. ``` -------------------------------- ### File Component Initialization Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Shows how to initialize a File component within a LayoutView. The media parameter must point to a local file uploaded alongside the view. ```Python import discord from discord import ui class MyView(ui.LayoutView): file = ui.File('attachment://file.txt') # attachment://file.txt points to an attachment uploaded alongside this view ``` -------------------------------- ### get_cog Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets the cog instance requested. Returns None if the cog is not found. ```APIDOC ## get_cog(_name_) ### Description Gets the cog instance requested. ### Parameters #### Path Parameters * **name** (`str`) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified. ### Returns The cog that was requested. If not found, returns `None`. ### Return type Optional[`Cog`] ``` -------------------------------- ### Using abc.GuildChannel.permissions_for() Source: https://discordpy.readthedocs.io/en/latest/migrating.html The `User.permissions_in` and `Member.permissions_in` methods have been removed. Use `abc.GuildChannel.permissions_for()` to get permissions. ```python channel.permissions_for(member) ``` -------------------------------- ### Describe Command Parameters using Docstrings Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Alternatively, parameter descriptions can be provided using Google, Sphinx, or Numpy style docstrings. ```python @app_commands.command() async def ban(interaction: discord.Interaction, member: discord.Member): """Bans a member Parameters ---------- member: discord.Member the member to ban """ await interaction.response.send_message(f'Banned {member}') ``` -------------------------------- ### Start Typing Indicator Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Initiates a typing indicator in the channel. For interactions, this is equivalent to deferring. ```Python await channel.typing() ``` -------------------------------- ### cog_load() Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html A special asynchronous method called when the cog is loaded into the bot, used for setup tasks. ```APIDOC ## await cog_load() ### Description This function could be a coroutine. A special method that is called when the cog gets loaded. Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous. ### New in version 2.0 ``` -------------------------------- ### _emojis Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html The emojis that the connected client has. This does not include the emojis that are owned by the application. Use `fetch_application_emoji()` to get those. ```APIDOC ## _emojis ### Description The emojis that the connected client has. Note This does not include the emojis that are owned by the application. Use `fetch_application_emoji()` to get those. ### Type Sequence[Emoji] ``` -------------------------------- ### Creating a Select Menu with Options Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Demonstrates how to create a discord.ui.Select component and add options to it using the add_option method. This is useful for presenting a list of choices to the user in an interactive message. ```Python select_menu = discord.ui.Select( placeholder="Choose a color...", options=[ discord.SelectOption( label="Red", description="A vibrant red color.", emoji="πŸ”΄", default=True ), discord.SelectOption( label="Blue", description="A calming blue color.", emoji="πŸ”΅", ), discord.SelectOption( label="Green", description="A natural green color.", emoji="🟒", ) ] ) # Alternatively, using add_option: select_menu_alt = discord.ui.Select(placeholder="Choose a color...") select_menu_alt.add_option( label="Red", description="A vibrant red color.", emoji="πŸ”΄", default=True ) select_menu_alt.add_option( label="Blue", description="A calming blue color.", emoji="πŸ”΅", ) select_menu_alt.add_option( label="Green", description="A natural green color.", emoji="🟒", ) ``` -------------------------------- ### Positional Flag with Default Value Source: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html Example of a FlagConverter with a positional flag that has a default boolean value. ```Python class Greeting(commands.FlagConverter): text: str = commands.flag(positional=True) bold: bool = False ``` -------------------------------- ### Fetch Invite Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Gets an Invite from a discord.gg URL or ID. Can include count information and expiration date. ```APIDOC ## Fetch Invite ### Description Gets an Invite from a discord.gg URL or ID. Can include count information and expiration date. ### Method GET (assumed) ### Endpoint /invites/{url} ### Parameters #### Path Parameters - **url** (Union[Invite, str]) - The Discord invite ID or URL (must be a discord.gg URL). #### Query Parameters - **with_counts** (bool) - Whether to include count information in the invite. - **with_expiration** (bool) - Whether to include the expiration date of the invite. Deprecated. - **scheduled_event_id** (Optional[int]) - The ID of the scheduled event this invite is for. ### Raises - **ValueError** - The url contains an event_id, but scheduled_event_id has also been provided. - **NotFound** - The invite has expired or is invalid. - **HTTPException** - Getting the invite failed. ### Returns - **Invite** - The invite from the URL/ID. ``` -------------------------------- ### HelpCommand Class Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html The base implementation for help command formatting. Instances of this class are deep copied on each invocation to prevent race conditions. ```APIDOC ## Class discord.ext.commands.HelpCommand ### Description The base implementation for help command formatting. Note that internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition. ### Attributes * **cog** (Optional[Cog]): A property for retrieving or setting the cog for the help command. * **command_attrs** (dict): A dictionary of options to pass in for the construction of the help command. * **context** (Optional[Context]): The context that invoked this help formatter. * **invoked_with** (Optional[str]): Similar to `Context.invoked_with` except properly handles the case where `Context.send_help()` is used. * **show_hidden** (bool): Specifies if hidden commands should be shown in the output. Defaults to `False`. * **verify_checks** (Optional[bool]): Specifies if commands should have their `Command.checks` called and verified. ### Methods * **add_check(func, /)**: Adds a check to the help command. * **asynccommand_callback()**: Placeholder for command callback logic. * **command_not_found(string, /)**: This function could be a coroutine. A method called when a command is not found in the help command. Defaults to `No command called {0} found.` * **asyncfilter_commands()**: Placeholder for filtering commands. * **get_bot_mapping()**: Retrieves the bot mapping passed to `send_bot_help()`. * **get_command_signature(command, /)**: Retrieves the signature portion of the help page. * **get_destination()**: Placeholder for getting the destination. * **get_max_size()**: Placeholder for getting the max size. * **asyncon_help_command_error()**: Placeholder for handling help command errors. * **asyncprepare_help_command()**: Placeholder for preparing the help command. * **remove_check(func, /)**: Removes a check from the help command. * **remove_mentions(string, /)**: Removes mentions from the string to prevent abuse. * **asyncsend_bot_help()**: Placeholder for sending bot help. * **asyncsend_cog_help()**: Placeholder for sending cog help. * **asyncsend_command_help()**: Placeholder for sending command help. * **asyncsend_error_message()**: Placeholder for sending error messages. * **asyncsend_group_help()**: Placeholder for sending group help. * **subcommand_not_found(command, string, /)**: This function could be a coroutine. A method called when a command did not have a subcommand requested in the help command. ``` -------------------------------- ### Get Cog Commands Source: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html Retrieves a list of commands associated with a cog. Use this to check available commands. ```python >>> cog = bot.get_cog('Greetings') >>> commands = cog.get_commands() >>> print([c.name for c in commands]) ``` -------------------------------- ### Create aiohttp ClientSession Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html Recommended way to make HTTP requests with aiohttp v2.0+. Create a session and reuse it for multiple requests. ```Python async with aiohttp.ClientSession() as sess: async with sess.get('url') as resp: # work with resp ``` -------------------------------- ### View.find_item Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Gets an item with `Item.id` set as `id`, or `None` if not found. Note: This is not the same as `custom_id`. New in version 2.6. ```APIDOC ## def find_item(id, /) ### Description Gets an item with `Item.id` set as `id`, or `None` if not found. Warning: This is **not the same** as `custom_id`. New in version 2.6. ### Parameters * **id** (int) - The ID of the component. ### Returns The item found, or `None`. ### Return Type Optional[Item] ``` -------------------------------- ### _await _original_response() Source: https://discordpy.readthedocs.io/en/latest/interactions/api.html Fetches the original interaction response message. This is a coroutine and can be called repeatedly to get a cached value. ```APIDOC ## _await _original_response() ### Description Fetches the original interaction response message associated with the interaction. This can be the message sent via `InteractionResponse.send_message()` or `InteractionResponse.defer()`, or the message that triggered the interaction (e.g., through a component). Repeated calls return a cached value. ### Method `await _original_response()` ### Parameters None ### Raises - **HTTPException**: Fetching the original response message failed. - **ClientException**: The channel for the message could not be resolved. - **NotFound**: The interaction response message does not exist. ### Response - **return value** (`InteractionMessage`) - The original interaction response message. ``` -------------------------------- ### _command_callback(ctx, /, *, command=None) Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html The main coroutine implementation of the help command. It is recommended to customize behavior through other dispatched methods rather than overriding this one. ```APIDOC ## _command_callback(ctx, /, *, command=None) ### Description The actual implementation of the help command. It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched. * `send_bot_help()` * `send_cog_help()` * `send_group_help()` * `send_command_help()` * `get_destination()` * `command_not_found()` * `subcommand_not_found()` * `send_error_message()` * `on_help_command_error()` * `prepare_help_command()` ### Parameters #### Path Parameters - **ctx** (Context) – The invocation context. - **command** (Optional[str]) – The argument passed to the help command. ``` -------------------------------- ### Voice State Access Before and After v1.0 Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html Illustrates how to access voice state attributes for a member. The 'after' example shows how to handle potential None values for the member.voice attribute. ```python # before member.deaf member.voice.voice_channel # after if member.voice: # can be None member.voice.deaf member.voice.channel ``` -------------------------------- ### get_command Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Retrieves a Command from the internal list of commands, which can also be used to get aliases. The name can be fully qualified. ```APIDOC ## get_command ### Description Get a `Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual. ### Method get_command ### Parameters #### Path Parameters - **name** (str) - The name of the command to get. ### Returns The command that was requested. If not found, returns `None`. ### Return type Optional[`Command`] ``` -------------------------------- ### Get Connected Client Emojis Source: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html Retrieves the emojis available to the connected client. This property does not include application-owned emojis. ```python client._emojis ``` -------------------------------- ### Registering Commands with Bot.command() and Bot.add_command() Source: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates two equivalent methods for registering commands: using the @bot.command() decorator directly or using the @commands.command() decorator followed by bot.add_command(). The decorator method is generally preferred for brevity. ```python import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='$', intents=intents) @bot.command() async def test(ctx): pass # or: @commands.command() async def test(ctx): pass bot.add_command(test) ``` -------------------------------- ### Get original message content Source: https://discordpy.readthedocs.io/en/latest/faq.html Demonstrates how to access the original message content within a command using `ctx.message.content`. ```python @bot.command() async def length(ctx): await ctx.send(f'Your message is {len(ctx.message.content)} characters long.') ``` -------------------------------- ### Example Cog with Command and Listener Source: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html Defines a 'Greetings' cog with a 'hello' command and an 'on_member_join' listener. Commands require a 'self' parameter. Listeners must be explicitly marked with `@commands.Cog.listener()`. ```python class Greetings(commands.Cog): def __init__(self, bot): self.bot = bot self._last_member = None @commands.Cog.listener() async def on_member_join(self, member): channel = member.guild.system_channel if channel is not None: await channel.send(f'Welcome {member.mention}.') @commands.command() async def hello(self, ctx, *, member: discord.Member = None): """Says hello""" member = member or ctx.author if self._last_member is None or self._last_member.id != member.id: await ctx.send(f'Hello {member.name}~') else: await ctx.send(f'Hello {member.name}... This feels familiar.') self._last_member = member ``` -------------------------------- ### Make a Web Request with aiohttp Source: https://discordpy.readthedocs.io/en/latest/faq.html Performs a GET request to a URL and parses the JSON response using aiohttp. ```Python async with aiohttp.ClientSession() as session: async with session.get('http://aws.random.cat/meow') as r: if r.status == 200: js = await r.json() ``` -------------------------------- ### Subclassing Context: Using Custom Context Source: https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html Demonstrates how to use a custom Context class (MyContext) with a Bot subclass by overriding on_message and using get_context. ```Python class MyBot(commands.Bot): async def on_message(self, message): ctx = await self.get_context(message, cls=MyContext) await self.invoke(ctx) ``` -------------------------------- ### Hybrid Command with Descriptions and Renames Source: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html This example combines inline descriptions and renames for flags within a hybrid command's `FlagConverter`. It shows how to configure both aspects directly when defining the flags. ```python class BanFlags(commands.FlagConverter): member: discord.Member = commands.flag(name='member', description='The member to ban') reason: str = commands.flag(name='reason', description='The reason for the ban') days: int = commands.flag(default=1, name='days', description='The number of days worth of messages to delete') @commands.hybrid_command() async def ban(ctx, *, flags: BanFlags): ... ```