### Setup Logging Without Client.run Source: https://discordpy-self.readthedocs.io/en/latest/logging.html Manually triggers the library's default logging setup using utility functions. ```python import discord discord.utils.setup_logging() # or, for example discord.utils.setup_logging(level=logging.INFO, root=False) ``` -------------------------------- ### Install library in virtual environment Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Standard pip installation command to be run after activating the virtual environment. ```bash $ pip install -U discord.py-self ``` -------------------------------- ### Install discord.py-self on Windows Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Installation command specifically for Windows environments. ```bash py -3 -m pip install -U discord.py-self ``` -------------------------------- ### Update extension setup function to asynchronous Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html The setup function must now be a coroutine to support asynchronous loading. ```python # before def setup(bot): bot.add_cog(MyCog(bot)) # after async def setup(bot): await bot.add_cog(MyCog(bot)) ``` -------------------------------- ### Wait for bot readiness before starting a task Source: https://discordpy-self.readthedocs.io/en/latest/ext/tasks/index.html Use the before_loop decorator to perform setup actions, such as waiting for the bot to be ready, before the first iteration. ```python from discord.ext import tasks, commands class MyCog(commands.Cog): def __init__(self, bot): self.index = 0 self.bot = bot 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 @printer.before_loop async def before_printer(self): print('waiting...') await self.bot.wait_until_ready() ``` -------------------------------- ### start(*args, **kwargs) Source: https://discordpy-self.readthedocs.io/en/latest/ext/tasks/index.html Starts the internal task in the event loop. Returns the asyncio.Task object created. ```APIDOC ## start(*args, **kwargs) ### Description Starts the internal task in the event loop. ### Parameters - ***args** (Any) - Optional - The arguments to use. - ****kwargs** (Any) - Optional - The keyword arguments to use. ### Returns - **asyncio.Task** - The task that has been created. ### Raises - **RuntimeError** - A task has already been launched and is running. ``` -------------------------------- ### Install discord.py-self via pip Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Standard installation command for the library on Unix-like systems. ```bash python3 -m pip install -U discord.py-self ``` -------------------------------- ### Install discord.py-self with voice support Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Installs the library with additional dependencies required for voice functionality. ```bash python3 -m pip install -U discord.py-self[voice] ``` -------------------------------- ### Create a basic event-driven client Source: https://discordpy-self.readthedocs.io/en/latest/intro.html A minimal example demonstrating how to subclass discord.Client and handle on_ready and on_message events. ```python 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}') client = MyClient() client.run('token') ``` -------------------------------- ### Implement setup and teardown Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/extensions.html The teardown function provides a hook to perform cleanup tasks when an extension is unloaded. ```python async def setup(bot): print('I am being loaded!') async def teardown(bot): print('I am being unloaded!') ``` -------------------------------- ### Invoke a command Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Example of how a user invokes a command defined with a prefix. ```text $foo abc ``` -------------------------------- ### Define an extension Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/extensions.html An extension requires a setup coroutine that accepts the bot instance to register commands or other functionality. ```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) ``` -------------------------------- ### fetch_template(code) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Gets a Template from a discord.new URL or code. ```APIDOC ## fetch_template(code) ### Description Gets a Template from a discord.new URL or code. ### Parameters - **code** (Union[Template, str]) - Required - The Discord Template Code or URL. ### Returns - **Template** - The template from the URL/code. ``` -------------------------------- ### Install voice dependencies on Debian Source: https://discordpy-self.readthedocs.io/en/latest/intro.html System-level dependencies required for voice support on Debian-based Linux distributions. ```bash $ apt install libffi-dev libnacl-dev python3-dev ``` -------------------------------- ### _application_commands() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves a list of application commands installed to the current user’s account. Note that this endpoint is heavily rate limited. ```APIDOC ## _application_commands() ### Description Returns a list of application commands installed to the current user’s account. ### Returns - **List[Union[SlashCommand, UserCommand, MessageCommand, PrimaryEntryPointCommand]]** - The list of application commands installed to the current user’s account. ### Raises - **HTTPException** - Fetching the commands failed. ``` -------------------------------- ### Iterate over channel history Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Example of iterating over channel history using an asynchronous iterator. ```python user_messages = [message async for message in channel.history() if not m.author.bot] ``` -------------------------------- ### Command using a Converter class Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Example of invoking a command that utilizes the Slapper converter class. ```python @bot.command() async def slap(ctx, *, reason: Slapper): await ctx.send(reason) ``` -------------------------------- ### Implement setup_hook in Client Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Shows how to subclass Client and implement setup_hook for asynchronous initialization tasks. ```python class MyClient(discord.Client): async def setup_hook(self): print('This is asynchronous!') client = MyClient() client.run(TOKEN) ``` -------------------------------- ### Create a virtual environment Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Commands to navigate to the project directory and initialize a new virtual environment. ```bash $ cd your-bot-source $ python3 -m venv bot-env ``` -------------------------------- ### Migrating Extension Loading Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Updates for loading extensions using setup_hook or async context managers. ```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()) ``` -------------------------------- ### pomelo_suggestion() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Gets the suggested pomelo username for the account. ```APIDOC ## await pomelo_suggestion(global_name=...) ### Description Gets the suggested pomelo username for your account. This username can be used with edit() to migrate your account to Discord’s new unique username system. ### Parameters - **global_name** (Optional[str]) - Optional - The global name to suggest a username for. ### Returns - **str** - The suggested username. ### Raises - **HTTPException** - You are not in the pomelo rollout. ``` -------------------------------- ### fetch_widget(guild_id) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Gets a Widget from a guild ID. ```APIDOC ## fetch_widget(guild_id) ### Description Gets a Widget from a guild ID. The guild must have the widget enabled. ### Parameters - **guild_id** (int) - Required - The ID of the guild. ### Returns - **Widget** - The guild’s widget. ``` -------------------------------- ### Run Client with asyncio.run Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Demonstrates using asyncio.run to manage the event loop instead of the traditional Client.run method. ```python client = discord.Client() async def main(): # do other async things await my_async_function() # start the client async with client: await client.start(TOKEN) asyncio.run(main()) ``` -------------------------------- ### _fetch_stage_instance(channel_id) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Gets a StageInstance for a stage channel ID. ```APIDOC ## _fetch_stage_instance(channel_id) ### Description Gets a StageInstance for a stage channel ID. ### Parameters - **channel_id** (int) - Required - The stage channel ID. ``` -------------------------------- ### @before_loop Source: https://discordpy-self.readthedocs.io/en/latest/ext/tasks/index.html Decorator that registers a coroutine to be called before the loop starts running. ```APIDOC ## @before_loop ### Description A decorator that registers a coroutine to be called before the loop starts running. This is useful for waiting for bot state, such as client readiness. ### Parameters - **coro** (coroutine) - Required - The coroutine to register before the loop runs. ### Raises - **TypeError** - The function was not a coroutine. ``` -------------------------------- ### Default Opening Note Implementation Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html The default string returned by get_opening_note, which provides instructions on how to use the help command. ```text Use {prefix}{command_name} [command] for more info on a command. You can also use {prefix}{command_name} [category] for more info on a category. ``` -------------------------------- ### Get sent message ID Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Retrieves the ID of a message after it has been sent. ```python message = await channel.send('hmm…') message_id = message.id ``` -------------------------------- ### Send message after computational task Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Example of sending a message after a blocking operation. ```python # Do some computational magic for about 10 seconds await channel.send('Done!') ``` -------------------------------- ### Configure File Logging via Client.run Source: https://discordpy-self.readthedocs.io/en/latest/logging.html Directs log output to a file instead of stderr by passing a logging.FileHandler to the client. ```python import logging handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') # Assume client refers to a discord.Client subclass... client.run(token, log_handler=handler) ``` -------------------------------- ### Migrate Webhook implementation Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Update webhook initialization by removing the adapter and using SyncWebhook instead of the partial Webhook class. ```python # before webhook = discord.Webhook.partial(123456, 'token-here', adapter=discord.RequestsWebhookAdapter()) webhook.send('Hello World', username='Foo') # after webhook = discord.SyncWebhook.partial(123456, 'token-here') webhook.send('Hello World', username='Foo') ``` -------------------------------- ### Create a custom converter by subclassing Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Shows how to extend an existing converter to perform custom logic, such as processing a member's roles. ```python class MemberRoles(commands.MemberConverter): async def convert(self, ctx, argument): member = await super().convert(ctx, argument) return [role.name for role in member.roles[1:]] # Remove everyone role! @bot.command() async def roles(ctx, *, member: MemberRoles): """Tells you a member's roles.""" await ctx.send('I see the following roles: ' + ', '.join(member)) ``` -------------------------------- ### Set client activity Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Configures the client's activity status upon initialization. ```python activity = discord.Activity(name='my activity', type=discord.ActivityType.watching) client = discord.Client(activity=activity) ``` -------------------------------- ### Use and configure clean_content converter Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Shows how to use the built-in clean_content converter with and without fine-tuning parameters. ```python @bot.command() async def clean(ctx, *, content: commands.clean_content): await ctx.send(content) # or for fine-tuning @bot.command() async def clean(ctx, *, content: commands.clean_content(use_nicknames=False)): await ctx.send(content) ``` -------------------------------- ### Creating a Basic Command Check Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Shows how to define a simple predicate function and apply it to a command using the @commands.check decorator. ```python def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!') ``` -------------------------------- ### Configure Log Level via Client.run Source: https://discordpy-self.readthedocs.io/en/latest/logging.html Sets the logging verbosity level when initializing the client. ```python import logging handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') # Assume client refers to a discord.Client subclass... client.run(token, log_handler=handler, log_level=logging.DEBUG) ``` -------------------------------- ### Create a simple background task in a Cog Source: https://discordpy-self.readthedocs.io/en/latest/ext/tasks/index.html Use the @tasks.loop decorator to define a recurring task within a Cog. Ensure the task is started in the constructor and cancelled in cog_unload. ```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 ``` -------------------------------- ### greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Sends a sticker greeting to the destination, used to begin a new DM or reply to a system message. ```APIDOC ## greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...) ### Description Sends a sticker greeting to the destination. A sticker greeting is used to begin a new DM or reply to a system message. ### Parameters - **sticker** (Union[GuildSticker, StickerItem]) - Required - The sticker to greet with. - **allowed_mentions** (AllowedMentions) - Optional - Controls the mentions being processed in this message. - **reference** (Union[Message, MessageReference, PartialMessage]) - Optional - A reference to the Message to which you are replying. - **mention_author** (bool) - Optional - If set, overrides the replied_user attribute of allowed_mentions. ### Returns - **Message** - The sticker greeting that was sent. ### Raises - **HTTPException** - Sending the message failed. - **Forbidden** - You do not have the proper permissions to send the message, or this is not a valid greet context. - **TypeError** - The reference object is not a Message, MessageReference or PartialMessage. ``` -------------------------------- ### Define a basic command converter Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates a simple command using a custom converter class. ```python @bot.command() async def slap(ctx, *, reason: Slapper()): await ctx.send(reason) ``` -------------------------------- ### application_commands() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Returns a list of application commands available in the channel. ```APIDOC ## application_commands() ### Description Returns a list of application commands available in the channel. ### Raises - **ValueError** - Could not resolve the channel’s guild ID. - **HTTPException** - Getting the commands failed. ``` -------------------------------- ### _promotions() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all the promotions available for your account. ```APIDOC ## _promotions(claimed=False) ### Description Retrieves all the promotions available for your account. ### Parameters - **claimed** (`bool`) - Whether to only retrieve claimed promotions. ### Returns - List[`Promotion`] - The promotions available for you. ### Raises - `HTTPException` - Retrieving the promotions failed. ``` -------------------------------- ### _user_offer(*, discount_id=..., payment_gateway=None) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the current user offer for your account, including trial and discount offers. ```APIDOC ## _user_offer(*, discount_id=..., payment_gateway=None) ### Description Retrieves the current user offer for your account. This includes the trial offer and discount offer. ### Parameters - **discount_id** (int) - Optional - The specific discount ID to fetch the offer of. - **payment_gateway** (Optional[PaymentGateway]) - Optional - The payment gateway to fetch the user offer for. ### Returns - **UserOffer** - The user offer for your account. ``` -------------------------------- ### Activate virtual environment Source: https://discordpy-self.readthedocs.io/en/latest/intro.html Commands to activate the virtual environment on different operating systems. ```bash $ source bot-env/bin/activate ``` ```bash $ bot-env\Scripts\activate.bat ``` -------------------------------- ### fetch_experiments(with_guild_experiments=True, platform=None) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the experiment rollouts available in relation to the user. ```APIDOC ## await fetch_experiments(with_guild_experiments=True, platform=None) ### Description Retrieves the experiment rollouts available in relation to the user. ### Parameters - **with_guild_experiments** (bool) - Optional - Whether to include guild experiment rollouts in the response. - **platform** (ExperimentPlatform) - Optional - The platform to retrieve additional experiments for. ### Returns - **List[Union[UserExperiment, GuildExperiment]]** - The experiment rollouts. ### Raises - **HTTPException** - Retrieving the experiment assignments failed. ``` -------------------------------- ### Register commands via decorator or add_command Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates two equivalent ways to register commands: using the bot decorator or the add_command method. ```python from discord.ext import commands bot = commands.Bot(command_prefix='$') @bot.command() async def test(ctx): pass # or: @commands.command() async def test(ctx): pass bot.add_command(test) ``` -------------------------------- ### login Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Logs in the client with the specified credentials. ```APIDOC ## await login(token) ### Description Logs in the client with the specified credentials and calls the setup_hook(). ### Parameters - **token** (str) - Required - The authentication token. ### Raises - **LoginFailure** - The wrong credentials are passed. - **HTTPException** - An unknown HTTP related error occurred. ``` -------------------------------- ### discord.ext.commands.Bot Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html The Bot class is the main entry point for creating a bot. It provides access to various attributes representing the bot's state, configuration, and Discord data. ```APIDOC ## class discord.ext.commands.Bot(command_prefix, help_command=, description=None, **options) ### Description Represents a Discord bot. This class is a subclass of Client and provides additional functionality for command handling. ### Attributes - **activities** - **activity** - **allowed_mentions** - **apex_experiments** - **blocked** - **cached_messages** - **case_insensitive** - **client_activities** - **client_status** - **cogs** - **command_prefix** - **commands** - **connections** - **country_code** - **description** - **disclose** - **emojis** - **experiments** - **extensions** - **friend_suggestion_count** - **friends** - **guild_experiments** - **guilds** - **help_command** - **idle_since** - **initial_activities** - **initial_activity** - **initial_afk** - **initial_idle_since** - **initial_status** - **installation_id** - **latency** - **notification_settings** - **owner_id** - **owner_ids** - **pending_payments** - **preferred_rtc_regions** - **private_channels** - **raw_status** - **read_states** - **relationships** - **required_action** - **sessions** - **settings** - **status** - **stickers** - **strip_after_prefix** - **tracking_settings** - **tutorial** - **user** - **users** - **voice_client** - **voice_clients** ``` -------------------------------- ### Manual iteration using anext() Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Use anext() or __anext__() when manual item retrieval is required instead of a full loop. ```python # before it = channel.history() first = await it.next() if first.content == 'do not iterate': return async for message in it: ... ``` -------------------------------- ### Define a basic command Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Use the @bot.command() decorator to define a command that takes a context and an argument. ```python @bot.command() async def foo(ctx, arg): await ctx.send(arg) ``` -------------------------------- ### Run the Bot Script Source: https://discordpy-self.readthedocs.io/en/latest/quickstart.html Commands to execute the bot script on different operating systems. ```bash $ py -3 example_bot.py ``` ```bash $ python3 example_bot.py ``` -------------------------------- ### Migrating AsyncIterator.get Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Replace the .get() method with discord.utils.get. ```python # before msg = await channel.history().get(author__name='Dave') # after msg = await discord.utils.get(channel.history(), author__name='Dave') ``` -------------------------------- ### Configure Bot Prefix with when_mentioned_or Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Sets the command prefix to include mentions and a custom string. ```python bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) ``` -------------------------------- ### detectable_applications Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the list of applications detectable by the Discord client. ```APIDOC ## await detectable_applications() ### Description Retrieves the list of applications detectable by the Discord client. New in version 2.0. ### Returns - **List[DetectableApplication]** - The applications detectable by the Discord client. ``` -------------------------------- ### Migrate Asynchronous Webhooks Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Update webhook initialization to pass the aiohttp session directly to the from_url method instead of using an AsyncWebhookAdapter. ```python # before async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url('url-here', adapter=discord.AsyncWebhookAdapter(session)) await webhook.send('Hello World', username='Foo') # after async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url('url-here', session=session) await webhook.send('Hello World', username='Foo') ``` -------------------------------- ### fetch_application Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the application with the given ID. ```APIDOC ## fetch_application(application_id) ### Description Retrieves the application with the given ID. The application must be owned by you or a team you are a part of. ### Parameters - **application_id** (int) - Required - The ID of the application to fetch. ### Returns - Application - The retrieved application. ``` -------------------------------- ### _pricing_promotion() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the current localized pricing promotion for your account. ```APIDOC ## _pricing_promotion() ### Description Retrieves the current localized pricing promotion for your account, if any. This also updates your current country code. ### Returns - Optional[`PricingPromotion`] - The pricing promotion for your account, if any. ### Raises - `HTTPException` - Retrieving the pricing promotion failed. ``` -------------------------------- ### _fetch_settings() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the current user settings. ```APIDOC ## _fetch_settings() ### Description Retrieves the current user settings. ### Returns - **UserSettings** - The current settings for the account. ``` -------------------------------- ### Create a command group Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Define a command group to organize subcommands. ```python @bot.group() async def git(ctx): if ctx.invoked_subcommand is None: await ctx.send('Invalid git command passed...') @git.command() async def push(ctx, remote: str, branch: str): await ctx.send(f'Pushing to {remote} {branch}') ``` -------------------------------- ### fetch_tracking_settings() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves your Discord tracking consents. ```APIDOC ## fetch_tracking_settings() ### Description Retrieves your Discord tracking consents. ### Returns - **TrackingSettings** - The tracking settings. ``` -------------------------------- ### Create a Minimal Discord Bot Source: https://discordpy-self.readthedocs.io/en/latest/quickstart.html A basic implementation of a Discord client that logs in and responds to a specific message. ```python import discord client = discord.Client() @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') ``` -------------------------------- ### fetch_apex_experiments Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the apex experiment rollouts available in relation to the user. ```APIDOC ## fetch_apex_experiments(surface=ApexExperimentSurface.app) ### Description Retrieves the apex experiment rollouts available in relation to the user. ### Parameters - **surface** (ApexExperimentSurface) - Optional - The surface to retrieve the apex experiments for. Only supports ApexExperimentSurface.app and ApexExperimentSurface.developer_portal. ### Returns - List[ApexExperiment] - The apex experiment rollouts. ``` -------------------------------- ### Migrating AsyncIterator.find Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Replace the .find() method with discord.utils.find. ```python def predicate(event): return event.reason is not None # before event = await guild.audit_logs().find(predicate) # after event = await discord.utils.find(predicate, guild.audit_logs()) ``` -------------------------------- ### Create an abstract cog mixin class Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to combine CogMeta with other metaclasses like abc.ABCMeta to create an abstract cog mixin. ```python import abc class CogABCMeta(commands.CogMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): pass ``` -------------------------------- ### _fetch_sku_subscription_plans(sku_id, *, country_code=..., payment_source=..., with_unpublished=False) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all subscription plans for a specific SKU ID. ```APIDOC ## _fetch_sku_subscription_plans(sku_id, *, country_code=..., payment_source=..., with_unpublished=False) ### Description Retrieves all subscription plans for the given SKU ID. ### Parameters - **sku_id** (int) - Required - The ID of the SKU. - **country_code** (str) - Optional - Country code for prices. - **payment_source** (PaymentSource) - Optional - Specific payment source. - **with_unpublished** (bool) - Optional - Whether to include unpublished plans. ``` -------------------------------- ### Implementing Custom Command Exceptions Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Shows how to create a custom exception derived from CommandError to provide more robust error handling in command checks. ```python class NoPrivateMessages(commands.CheckFailure): pass def guild_only(): async def predicate(ctx): if ctx.guild is None: raise NoPrivateMessages('Hey no DMs!') return True return commands.check(predicate) @bot.command() @guild_only() async def test(ctx): await ctx.send('Hey this is not a DM! Nice.') @test.error async def test_error(ctx, error): if isinstance(error, NoPrivateMessages): await ctx.send(error) ``` -------------------------------- ### _preview_subscription() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Preview an invoice for the subscription with the given parameters. ```APIDOC ## _preview_subscription(items, *, payment_source=None, currency='usd', trial=None, apply_entitlements=True, renewal=False, code=None, metadata=None, guild=None) ### Description Preview an invoice for the subscription with the given parameters. All parameters are optional and default to the current subscription values. ### Parameters - **items** (List[`SubscriptionItem`]) - The items the previewed subscription should have. - **payment_source** (Optional[`PaymentSource`]) - The payment source the previewed subscription should be paid with. - **currency** (`str`) - The currency the previewed subscription should be paid in. - **trial** (Optional[`SubscriptionTrial`]) - The trial plan the previewed subscription should be on. - **apply_entitlements** (`bool`) - Whether to apply entitlements (credits) to the previewed subscription. - **renewal** (`bool`) - Whether the previewed subscription should be a renewal. - **code** (Optional[`str`]) - Unknown. - **metadata** (Optional[Mapping[`str`, Any]]) - Extra metadata about the subscription. - **guild** (Optional[`Guild`]) - The guild the previewed subscription’s entitlements should be applied to. ### Returns - `SubscriptionInvoice` - The previewed invoice. ### Raises - `HTTPException` - Failed to preview the invoice. ``` -------------------------------- ### fetch_connections Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all of your connections. ```APIDOC ## fetch_connections() ### Description Retrieves all of your connections. ### Returns - List[Connection] - All your connections. ``` -------------------------------- ### Define a command with a custom function converter Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates using a custom callable function as a converter to transform input strings. ```python def to_upper(argument): return argument.upper() @bot.command() async def up(ctx, *, content: to_upper): await ctx.send(content) ``` -------------------------------- ### send_help(entity=) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Shows the help command for the specified entity (command or cog). ```APIDOC ## send_help(entity=) ### Description Shows the help command for the specified entity if given. The entity can be a command or a cog. ### Parameters - **entity** (Optional[Union[Command, Cog, str]]) - Optional - The entity to show help for. ``` -------------------------------- ### Override headers context Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to override the headers_context method to specify a custom client context, such as desktop. ```python class MyClient(discord.Client): async def headers_context(self): async with aiohttp.ClientSession() as session: # We want the desktop client context return await discord.HeadersContext.desktop(session) ``` -------------------------------- ### Implement Custom Prefix Logic Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to invoke the callable returned by when_mentioned_or within a custom prefix function. ```python async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) ``` -------------------------------- ### _fetch_sku(sku_id, *, localize=True) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves a SKU with the given ID. ```APIDOC ## _fetch_sku(sku_id, *, localize=True) ### Description Retrieves a SKU with the given ID. ### Parameters - **sku_id** (int) - Required - The ID of the SKU to retrieve. - **localize** (bool) - Optional - Whether to localize the SKU name and description. ``` -------------------------------- ### _applications(with_team_applications=True) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all applications owned by the current user. ```APIDOC ## _applications(with_team_applications=True) ### Description Retrieves all applications owned by you. ### Parameters - **with_team_applications** (bool) - Optional - Whether to include applications owned by teams you’re a part of. ### Returns - **List[Application]** - The applications you own. ### Raises - **HTTPException** - Retrieving the applications failed. ``` -------------------------------- ### fetch_partial_application Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the partial application with the given ID. ```APIDOC ## fetch_partial_application(application_id) ### Description Retrieves the partial application with the given ID. ### Parameters - **application_id** (int) - Required - The ID of the partial application to fetch. ### Returns - **PartialApplication** - The retrieved application. ``` -------------------------------- ### _reply(content=None, **kwargs) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html A shortcut method to reply to a specific message. ```APIDOC ## _reply(content=None, **kwargs) ### Description A shortcut method to abc.Messageable.send() to reply to the Message. ### Returns - **Message** - The message that was sent. ``` -------------------------------- ### global_activity_statistics(with_users=True, with_applications=True) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves the available activity usage statistics for the games your friends and implicit relationships play. ```APIDOC ## global_activity_statistics(with_users=True, with_applications=True) ### Description Retrieves the available activity usage statistics for the games your friends and implicit relationships play. ### Parameters - **with_users** (`bool`) - Optional - Whether to include user statistics. - **with_applications** (`bool`) - Optional - Whether to include application statistics. ### Returns - `List[ApplicationActivityStatistics]` - The activity statistics. ### Errors - `HTTPException` - Retrieving the statistics failed. ``` -------------------------------- ### Make a web request with aiohttp Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Perform non-blocking HTTP requests using the aiohttp library. ```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() ``` -------------------------------- ### _entitlements() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all the entitlements for your account. ```APIDOC ## _entitlements(with_sku=True, with_application=True, include_ended=True, entitlement_type=None) ### Description Retrieves all the entitlements for your account. ### Parameters - **with_sku** (bool) - Optional - Whether to include the SKU information in the returned entitlements. - **with_application** (bool) - Optional - Whether to include the application in the returned entitlements’ SKUs. - **include_ended** (bool) - Optional - Whether to include ended entitlements in the returned list. - **entitlement_type** (Optional[EntitlementType]) - Optional - The type of entitlement to retrieve. ### Returns - **List[Entitlement]** - The entitlements for your account. ``` -------------------------------- ### Use List for repeated flags Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates using List to allow a flag to be specified multiple times in a command. ```python from discord.ext import commands from typing import List import discord class BanFlags(commands.FlagConverter): members: List[discord.Member] = commands.flag(name='member') reason: str days: int = 1 @commands.command() async def ban(ctx, *, flags: BanFlags): for member in flags.members: await member.ban(reason=flags.reason, delete_message_days=flags.days) members = ', '.join(str(member) for member in flags.members) plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day' await ctx.send(f'Banned {members} for {flags.reason!r} (deleted {plural} worth of messages)') ``` -------------------------------- ### _premium_subscription_plans() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all premium subscription plans. ```APIDOC ## _premium_subscription_plans() ### Description Retrieves all premium subscription plans. This is a coroutine. ### Returns - List[`SubscriptionPlan`] - The premium subscription plans. ### Raises - `HTTPException` - Retrieving the premium subscription plans failed. ``` -------------------------------- ### fetch_eula(eula_id) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves a EULA with the given ID. ```APIDOC ## await fetch_eula(eula_id) ### Description Retrieves a EULA with the given ID. ### Parameters - **eula_id** (int) - Required - The ID of the EULA to retrieve. ### Returns - **EULA** - The retrieved EULA. ### Raises - **NotFound** - The EULA does not exist. - **HTTPException** - Retrieving the EULA failed. ``` -------------------------------- ### load_extension Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Loads a python module extension. ```APIDOC ## await load_extension(name, *, package=None) ### Description Loads an extension. An extension is a python module that contains commands, cogs, or listeners. ### Parameters - **name** (str) - Required - The extension name to load. - **package** (Optional[str]) - Optional - The package name to resolve relative imports with. ### Raises - **ExtensionNotFound** - The extension could not be imported. - **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. ``` -------------------------------- ### Loop.get_task Source: https://discordpy-self.readthedocs.io/en/latest/ext/tasks/index.html Fetches the internal asyncio.Task. ```APIDOC ## Loop.get_task() ### Description Returns the internal `asyncio.Task` or `None` if not running. ``` -------------------------------- ### fetch_notes Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all your user notes. ```APIDOC ## fetch_notes() ### Description Retrieves all your user notes. ### Returns - **Dict[int, str]** - A dictionary mapping user IDs to their notes. ``` -------------------------------- ### Handling Command Errors with CheckFailure Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates catching a CheckFailure exception in a command-specific error handler. ```python @bot.command() @commands.is_owner() @is_in_guild(41771983423143937) async def secretguilddata(ctx): """super secret stuff""" await ctx.send('secret stuff') @secretguilddata.error async def secretguilddata_error(ctx, error): if isinstance(error, commands.CheckFailure): await ctx.send('nothing to see here comrade.') ``` -------------------------------- ### Define a command with a Member converter Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Demonstrates using a discord.Member type hint to automatically convert a string argument into a Member object. ```python @bot.command() async def joined(ctx, *, member: discord.Member): await ctx.send(f'{member} joined on {member.joined_at}') ``` -------------------------------- ### _change_presence(activity=..., activities=..., status=..., afk=..., idle_since=..., edit_settings=True) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Changes the client’s presence, including activity, status, and AFK state. ```APIDOC ## _change_presence(activity=..., activities=..., status=..., afk=..., idle_since=..., edit_settings=True) ### Description Changes the client’s presence. ### Parameters - **activity** (Optional[BaseActivity]) - Optional - The activity being done. - **activities** (List[BaseActivity]) - Optional - A list of the activities being done. - **status** (Status) - Optional - Indicates what status to change to. - **afk** (bool) - Optional - Indicates if you are going AFK. - **idle_since** (Optional[datetime.datetime]) - Optional - When the client went idle. - **edit_settings** (bool) - Optional - Whether to update user settings with the new status and/or custom activity. ``` -------------------------------- ### create_subscription Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Creates a new subscription with the specified items and payment source. ```APIDOC ## await create_subscription(items, payment_source, currency='usd', *, trial=None, payment_source_token=None, purchase_token=None, return_url=None, gateway_checkout_context=None, code=None, metadata=None, guild=None) ### Description Creates a new subscription. New in version 2.0. ### Parameters - **items** (List[SubscriptionItem]) - Required - The items in the subscription. - **payment_source** (PaymentSource) - Required - The payment source to pay with. - **currency** (str) - Required - The currency to pay with. - **trial** (Optional[SubscriptionTrial]) - Optional - The trial to apply to the subscription. - **payment_source_token** (Optional[str]) - Optional - The token used to authorize with the payment source. - **purchase_token** (Optional[str]) - Optional - The purchase token to use. - **return_url** (Optional[str]) - Optional - The URL to return to after the payment is complete. - **gateway_checkout_context** (Optional[Dict[str, Any]]) - Optional - The current checkout context. - **code** (Optional[str]) - Optional - Unknown. - **metadata** (Optional[Mapping[str, Any]]) - Optional - Extra metadata about the subscription. - **guild** (Optional[Guild]) - Optional - The guild the subscription’s entitlements should be applied to. ### Returns - **Subscription** - The newly-created subscription. ``` -------------------------------- ### Use a local file in an embed Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Upload a local image file and reference it in an embed using the attachment scheme. ```python file = discord.File("path/to/my/image.png", filename="image.png") embed = discord.Embed() embed.set_image(url="attachment://image.png") await channel.send(file=file, embed=embed) ``` -------------------------------- ### handle_captcha(exception) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Handles a CAPTCHA challenge and returns a solution. ```APIDOC ## handle_captcha(exception) ### Description Handles a CAPTCHA challenge and returns a solution. The default implementation tries to use the CAPTCHA handler passed in the constructor. ### Parameters - **exception** (`CaptchaRequired`) - Required - The exception that was raised. ### Returns - `str` - The solution to the CAPTCHA challenge. ### Errors - `CaptchaRequired` - The CAPTCHA challenge could not be solved. ``` -------------------------------- ### Send Typing Indicator Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates how to use the typing context manager to indicate activity during long-running operations. ```python async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!') ``` ```python await channel.typing() ``` -------------------------------- ### Consume remaining arguments in commands Source: https://discordpy-self.readthedocs.io/en/latest/faq.html Use the asterisk syntax to capture multiple words as a single argument. ```python @bot.command() async def echo(ctx, message: str): await ctx.send(message) ``` ```python @bot.command() async def echo(ctx, *, message: str): await ctx.send(message) ``` -------------------------------- ### Define a basic command with integer converters Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Uses function annotations to automatically cast command arguments to integers. ```python @bot.command() async def add(ctx, a: int, b: int): await ctx.send(a + b) ``` -------------------------------- ### Implement an advanced asynchronous Converter Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Creates a custom converter class by inheriting from commands.Converter and overriding the convert method. ```python import random class Slapper(commands.Converter): async def convert(self, ctx, argument): to_slap = random.choice(ctx.guild.members) return f'{ctx.author} slapped {to_slap} because *{argument}*' @bot.command() async def slap(ctx, *, reason: Slapper): await ctx.send(reason) ``` -------------------------------- ### Registering a Global Check Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Applies a check to every command by using the bot.check decorator. ```python @bot.check async def globally_block_dms(ctx): return ctx.guild is not None ``` -------------------------------- ### can_run(ctx) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Checks if the command can be executed based on predicates and disabled status. ```APIDOC ## can_run(ctx) ### Description Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled. ### Parameters - **ctx** (Context) - Required - The ctx of the command currently being invoked. ### Returns - **bool** - A boolean indicating if the command can be invoked. ``` -------------------------------- ### Wait for a reaction Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates using wait_for with a timeout to handle a specific reaction event from a message author. ```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('👍') ``` -------------------------------- ### @discord.ext.commands.command Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html A decorator that transforms a function into a Command. By default, the help attribute is derived from the function's docstring. ```APIDOC ## @discord.ext.commands.command(name=..., cls=..., **attrs) ### Description A decorator that transforms a function into a `Command`. By default, the `help` attribute is automatically extracted from the function's docstring. ### Parameters - **name** (str) - Optional - The name to create the command with. Defaults to the function name. - **cls** (class) - Optional - The class to construct with. Defaults to `Command`. - **attrs** (dict) - Optional - Keyword arguments to pass into the construction of the class. ``` -------------------------------- ### Annotate Parameters with Metadata Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/commands.html Use parameter() to provide type information for custom converters and handle late binding for command arguments. ```python class SomeType: foo: int class MyVeryCoolConverter(commands.Converter[SomeType]): ... # implementation left as an exercise for the reader @bot.command() async def bar(ctx, cool_value: MyVeryCoolConverter): cool_value.foo # type checker warns MyVeryCoolConverter has no value foo (uh-oh) ``` ```python @bot.command() async def bar(ctx, cool_value: SomeType = commands.parameter(converter=MyVeryCoolConverter)): cool_value.foo # no error (hurray) ``` ```python @bot.command() async def wave(to: discord.User = commands.parameter(default=lambda ctx: ctx.author)): await ctx.send(f'Hello {to.mention} :wave:') ``` ```python @bot.command() async def wave(to: discord.User = commands.Author): await ctx.send(f'Hello {to.mention} :wave:') ``` -------------------------------- ### _upload_files(*files) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Pre-uploads files to Discord’s GCP bucket for use with the send method. ```APIDOC ## _upload_files(*files) ### Description Pre-uploads files to Discord’s GCP bucket for use with send(). This is useful for reusing local files. ### Parameters - **files** (File) - Required - A list of files to upload (max 10). ### Returns - **List[CloudFile]** - The files that were uploaded. ``` -------------------------------- ### Greedy Converter Usage Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Demonstrates using the Greedy converter to consume multiple arguments into a list until parsing fails. ```python @commands.command() async def test(ctx, numbers: Greedy[int], reason: str): await ctx.send("numbers: {}, reason: {}".format(numbers, reason)) ``` -------------------------------- ### search_companies Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Query companies registered on Discord. This is a coroutine. ```APIDOC ## search_companies(query, /) ### Description Query companies registered on Discord. ### Parameters - **query** (str) - Required - The query to search for. ### Returns - **List[Company]** - The companies found. ### Raises - **HTTPException** - Searching failed. ``` -------------------------------- ### Migrating AsyncIterator.chunk Source: https://discordpy-self.readthedocs.io/en/latest/migrating.html Replace .chunk() with discord.utils.as_chunks. ```python # before async for leader, *users in reaction.users().chunk(3): ... # after async for leader, *users in discord.utils.as_chunks(reaction.users(), 3): ... ``` -------------------------------- ### create_team Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Creates a new team with the specified name. ```APIDOC ## await create_team(name) ### Description Creates a team. New in version 2.0. ### Parameters - **name** (str) - Required - The name of the team. ### Returns - **Team** - The newly-created team. ``` -------------------------------- ### fetch_guilds(with_counts=True) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Retrieves all your guilds. ```APIDOC ## await fetch_guilds(with_counts=True) ### Description Retrieves all your guilds as a list of UserGuild objects. ### Parameters - **with_counts** (bool) - Optional - Whether to fill Guild.approximate_member_count and Guild.approximate_presence_count. ### Returns - **List[UserGuild]** - A list of all your guilds. ### Raises - **HTTPException** - Getting the guilds failed. ``` -------------------------------- ### _proxy_external_application_assets() Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Proxies external asset URLs through Discord’s media proxy. ```APIDOC ## _proxy_external_application_assets(application_id, *urls) ### Description Proxies up to 2 external asset URLs through Discord’s media proxy, for use in rich presence. ### Parameters - **application_id** (`int`) - The rich presence application ID. - ***urls** (`str`) - The external asset URLs to proxy. ### Returns - The proxied asset URLs. ### Raises - `HTTPException` - Proxying the assets failed. ``` -------------------------------- ### run_converters(ctx, converter, argument, param) Source: https://discordpy-self.readthedocs.io/en/latest/ext/commands/api.html Runs converters for a given converter, argument, and parameter. This function performs the same conversion logic used internally by the library. ```APIDOC ## run_converters(ctx, converter, argument, param) ### Description Runs converters for a given converter, argument, and parameter. This function performs the same conversion logic used internally by the library. ### Parameters - **ctx** (Context) - Required - The invocation context to run the converters under. - **converter** (Any) - Required - The converter to run, corresponding to the annotation in the function. - **argument** (str) - Required - The argument to convert to. - **param** (Parameter) - Required - The parameter being converted, used for error reporting. ### Returns - **Any** - The resulting conversion. ### Raises - **CommandError** - The converter failed to convert. ```