### Pycord Getting Started Guide Source: https://docs.pycord.dev/en/stable/index Provides essential steps for new users to begin with Pycord, including installation, quickstart tutorials, setting up logging, and understanding Discord bot account creation and gateway intents. ```APIDOC Getting started: - First steps: Installing Pycord, Quickstart, Setting Up Logging, Guide - Working with Discord: Creating a Bot Account, A Primer to Gateway Intents - Examples: Available in the repository ``` -------------------------------- ### Virtual Environment Setup Source: https://docs.pycord.dev/en/stable/installing Guides through creating and activating a Python virtual environment for Pycord development. This isolates project dependencies. Includes commands for Linux/macOS and Windows. ```shell # Navigate to your project directory $ cd your-bot-source ``` ```shell # Create a virtual environment named 'bot-env' $ python3 -m venv bot-env ``` ```shell # Activate the virtual environment on Linux/macOS $ source bot-env/bin/activate ``` ```shell # Activate the virtual environment on Windows $ bot-env\Scripts\activate.bat ``` ```shell # Install Pycord within the activated environment $ pip install -U py-cord ``` -------------------------------- ### Pycord Extension Example Source: https://docs.pycord.dev/en/stable/ext/commands/extensions A basic Pycord extension demonstrating how to define a command and register it with the bot using a `setup` function. This file can be loaded by the bot using `bot.load_extension('hello')`. ```python from discord.ext import commands @commands.command() async def hello(ctx): await ctx.send(f'Hello {ctx.author.display_name}.') def setup(bot): bot.add_command(hello) ``` -------------------------------- ### Pycord Bridge Command Example Source: https://docs.pycord.dev/en/stable/ext/bridge/index Demonstrates how to use the discord.ext.bridge module to create commands that work as both prefix and slash commands. It shows basic command setup, argument parsing, and response handling. ```python import discord from discord.ext import bridge intents = discord.Intents.default() intents.message_content = True bot = bridge.Bot(command_prefix="!", intents=intents) @bot.bridge_command() async def hello(ctx): await ctx.respond("Hello!") @bot.bridge_command() async def bye(ctx): await ctx.respond("Bye!") @bot.bridge_command() async def sum(ctx, first: int, second: int): s = first + second await ctx.respond(f"{s}") bot.run("TOKEN") ``` -------------------------------- ### Help Command Opening Note Generation Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/help Generates the initial introductory text for the help command, guiding users on how to get more information about specific commands. ```python def get_opening_note(self): """Returns help command's opening note. This is mainly useful to override for i18n purposes. The default implementation returns :: Use `{prefix}{command_name} [command]` for more info on a command. """ prefix = self.context.clean_prefix command_name = self.context.invoked_with return f"Use `{prefix}{command_name} [command]` for more info on a command." ``` -------------------------------- ### Discord Onboarding and Guild Configuration Source: https://docs.pycord.dev/en/stable/genindex Classes and attributes related to Discord's onboarding feature, which helps new members get started in a server. This includes classes for the overall onboarding process, modes, and prompts, as well as methods to access guild-specific onboarding settings. ```APIDOC discord.Onboarding (class) - Represents the onboarding feature for a guild. - Attributes: - guild_id (int): The ID of the guild. - prompts (list[discord.OnboardingPrompt]): A list of onboarding prompts. - mode (discord.OnboardingMode): The current onboarding mode. - default_channel (discord.TextChannel | None): The default channel for onboarding. discord.Guild.onboarding (method) - Returns the Onboarding object for the guild. - Parameters: None - Returns: discord.Onboarding discord.OnboardingMode (enum) - Represents the different modes for guild onboarding. - Members: - WELCOME (int): Welcome mode. - NEWCOMER_TASKS (int): Newcomer tasks mode. discord.OnboardingPrompt (class) - Represents a single prompt within the onboarding process. - Attributes: - id (int): The ID of the prompt. - type (discord.OnboardingPromptType): The type of prompt. - title (str): The title of the prompt. - prompt (str): The content of the prompt. - options (list[discord.OnboardingPromptOption]): A list of options for the prompt. ``` -------------------------------- ### Pycord Extension Setup and Teardown Source: https://docs.pycord.dev/en/stable/ext/commands/extensions Demonstrates the `setup` and `teardown` entry points for Pycord extensions. The `setup` function is called when an extension is loaded, and the `teardown` function is called when it is unloaded, allowing for necessary cleanup operations. ```Python def setup(bot): print('I am being loaded!') def teardown(bot): print('I am being unloaded!') ``` -------------------------------- ### Install Pycord with Extras Source: https://docs.pycord.dev/en/stable/installing Installs Pycord with additional optional dependencies for enhanced functionality, such as speedups or voice support. Use the appropriate extra name in brackets. ```shell # Linux/macOS with speedups python3 -m pip install -U "py-cord[speed]" ``` ```shell # Windows with speedups py -3 -m pip install -U py-cord[speed] ``` ```shell # Linux/macOS with voice support python3 -m pip install -U py-cord[voice] ``` -------------------------------- ### Pycord: Get Help Command Opening Note Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/help This method generates the initial introductory note for the help command. It informs users about how to get more detailed information on specific commands or command categories. The note includes dynamic prefixes and command names. ```python command_name = self.invoked_with return ( f"Use `{self.context.clean_prefix}{command_name} [command]` for more info" " on a command.\nYou can also use" f" `{self.context.clean_prefix}{command_name} [category]` for more info on" " a category." ) ``` -------------------------------- ### Basic Slash Command Example Source: https://docs.pycord.dev/en/stable/api/application_commands A basic example demonstrating how to define a slash command with options in Python using the discord.py library. ```Python @bot.slash_command(guild_ids=[...]) async def hello( ``` -------------------------------- ### API: Get Opening Note for Help Source: https://docs.pycord.dev/en/stable/genindex Gets the opening note displayed at the top of the help message. Implemented by MinimalHelpCommand. ```APIDOC discord.ext.commands.MinimalHelpCommand.get_opening_note() - Returns the string to be displayed at the beginning of the help message. ``` -------------------------------- ### API: Get Prompt Source: https://docs.pycord.dev/en/stable/genindex Retrieves a prompt object from an Onboarding configuration. ```APIDOC discord.Onboarding.get_prompt(prompt_id: int) - Gets a prompt from the onboarding configuration. ``` -------------------------------- ### Minimal Discord Bot Example Source: https://docs.pycord.dev/en/stable/quickstart This Python script demonstrates the creation of a basic Discord bot. It configures message content intent, logs in, prints a ready message, and responds to a specific command ('$hello') in channels. It requires a Discord bot token to run. ```python 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') ``` -------------------------------- ### Get Internal Task Object Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/tasks Retrieves the internal asyncio.Task object if it has been created and is running. Returns None if the task has not been started or has already completed. ```python def get_task(self) -> asyncio.Task[None] | None: ``` -------------------------------- ### Get Root Parent Command (Python) Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/core Retrieves the root parent of the command. If the command has no parents, it returns None. For example, in commands '?a b c test', the root parent is 'a'. ```Python def root_parent(self) -> Group | None: """Retrieves the root parent of this command. If the command has no parents then it returns ``None``. For example in commands ``?a b c test``, the root parent is ``a``. """ if not self.parent: return None return self.parents[-1] ``` -------------------------------- ### Get Starting Message of Thread Source: https://docs.pycord.dev/en/stable/_modules/discord/threads Retrieves the message that initiated the thread. The message might not be valid or exist in cache. The ID of this message is the same as the thread's ID. ```python @property def starting_message(self) -> Message | None: """Returns the message that started this thread. The message might not be valid or point to an existing message. .. note:: The ID for this message is the same as the thread ID. Returns ------- Optional[:class:`Message`] The message that started this thread or ``None`` if not found in the cache. """ return self._state._get_message(self.id) ``` -------------------------------- ### Pycord Basic Event Handling Source: https://docs.pycord.dev/en/stable/installing Demonstrates how to create a Discord bot client using Pycord, defining asynchronous event handlers for when the bot is ready (`on_ready`) and when a message is received (`on_message`). This snippet requires the `discord.py` library. ```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('my token goes here') ``` -------------------------------- ### FFmpegPCMAudio Constructor and Configuration Source: https://docs.pycord.dev/en/stable/_modules/discord/player Details the initialization of FFmpegPCMAudio, including setting up FFmpeg arguments, handling input sources, and configuring subprocess behavior. It specifies parameters for executable path, piping, and command-line options. ```APIDOC FFmpegPCMAudio: __init__(source: Union[str, io.BufferedIOBase], *, executable: str = "ffmpeg", pipe: bool = False, stderr: IO[str] | None = None, before_options: str | None = None, options: str | None = None) Initializes an audio source from FFmpeg or AVConv. Parameters: source: The input for FFmpeg. Can be a file path (str) or a file-like object (io.BufferedIOBase) if pipe is True. executable: The FFmpeg executable name or path. Defaults to "ffmpeg". pipe: If True, the source is piped to FFmpeg's stdin. Defaults to False. stderr: A file-like object or subprocess.PIPE for stderr output. Defaults to None. before_options: FFmpeg command-line arguments before the -i flag. options: FFmpeg command-line arguments after the -i flag. Raises: ClientException: If the FFmpeg subprocess fails to be created. Example Usage: # Basic usage with a file path audio = FFmpegPCMAudio("input.mp3") # Usage with piping and custom options with open("input.wav", "rb") as f: audio = FFmpegPCMAudio(f, pipe=True, before_options="-re", options="-vn -acodec pcm_s16le") ``` -------------------------------- ### Prepare Help Command in pycord Source: https://docs.pycord.dev/en/stable/ext/commands/api A low-level method to prepare the help command before execution, allowing subclasses to set up state. The default implementation does nothing, and it's called within the help command's callback body. ```python async def prepare_help_command(ctx, command=None): """ 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. Note This is called *inside* the help command callback body. So all the usual rules that happen inside apply here as well. Parameters: : * **ctx** ([`Context`](#discord.ext.commands.Context "discord.ext.commands.Context")) – The invocation context. * **command** (Optional[[`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]) – The argument passed to the help command. """ pass ``` -------------------------------- ### Get Command Parents List (Python) Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/core Retrieves a list of parent groups for the current command. If the command has no parents, it returns an empty list. For example, in commands '?a b c test', the parents are '[c, b, a]'. ```Python def parents(self) -> list[Group]: """Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1 """ entries = [] command = self while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command) return entries ``` -------------------------------- ### Onboarding Class Definition and Methods Source: https://docs.pycord.dev/en/stable/_modules/discord/onboarding Represents the onboarding flow for a guild. It manages prompts, enabled status, and default channels, and provides methods to update these settings. ```python class Onboarding: """Represents the onboarding flow for a guild. .. versionadded:: 2.5 Attributes ---------- prompts: List[:class:`OnboardingPrompt`] A list of prompts displayed in the onboarding flow. enabled: :class:`bool` Whether onboarding is enabled in the guild. mode: :class:`OnboardingMode` The current onboarding mode. """ def __init__(self, data: OnboardingPayload, guild: Guild): self.guild = guild self._update(data) def __repr__(): return f"" def _update(self, data: OnboardingPayload): self.guild_id: Snowflake = data["guild_id"] self.prompts: list[OnboardingPrompt] = [ OnboardingPrompt._from_dict(prompt, self.guild) for prompt in data.get("prompts", []) ] self.default_channel_ids: list[int] = [ int(c) for c in data["default_channel_ids"] ] self.enabled: bool = data["enabled"] self.mode: OnboardingMode = try_enum(OnboardingMode, data.get("mode")) @cached_property def default_channels( self, ) -> list[TextChannel | ForumChannel | VoiceChannel | Object]: """The channels that members are opted into by default. If a channel is not found in the guild's cache, then it will be returned as an :class:`Object`. """ if self.guild is None: return [Object(channel_id) for channel_id in self.default_channel_ids] return [ self.guild.get_channel(channel_id) or Object(channel_id) for channel_id in self.default_channel_ids ] ``` -------------------------------- ### Get Full Parent Command Name (Python) Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/core Retrieves the fully qualified parent command name, which is the base name required to execute the command. For example, in '?one two three', the parent name is 'one two'. ```Python def full_parent_name(self) -> str: """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command.name) # type: ignore return " ".join(reversed(entries)) ``` -------------------------------- ### MinimalHelpCommand Methods Source: https://docs.pycord.dev/en/stable/ext/commands/api Documentation for key methods within the MinimalHelpCommand class, including formatting commands and retrieving the help message destination. ```APIDOC MinimalHelpCommand: add_command_formatting(command) Description: A utility function to format commands and groups. Parameters: command: The command to format. Type: discord.ext.commands.Command get_destination() Description: Returns the Messageable where the help command will be output. This method can be overridden to customize behavior. By default, it returns the context's channel. Returns: The destination where the help command will be output. Type: discord.abc.Messageable ``` -------------------------------- ### Basic Command Example Source: https://docs.pycord.dev/en/stable/migrating_to_v1 A simple command demonstrating the use of ctx.send() for sending messages, leveraging the new abc.Messageable interface. ```python @bot.command() async def foo(ctx): await ctx.send('Hello') ``` -------------------------------- ### Get Start Embedded Activities Permission Flag Source: https://docs.pycord.dev/en/stable/_modules/discord/permissions Retrieves the integer flag that permits a user to launch activities flagged as 'EMBEDDED' within a voice channel. This is for interactive experiences. Introduced in version 2.0. ```python @flag_value def start_embedded_activities(self) -> int: """Returns ``True`` if a user can launch an activity flagged 'EMBEDDED' in a voice channel. .. versionadded:: 2.0 """ return 1 << 39 ``` -------------------------------- ### Get Qualified Command Name (Python) Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/core Retrieves the fully qualified command name, which includes the full parent name concatenated with the command's own name. For example, in '?one two three', the qualified name is 'one two three'. ```Python def qualified_name(self) -> str: """Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return f"{parent} {self.name}" else: return self.name ``` -------------------------------- ### OnboardingPrompt Class Definition Source: https://docs.pycord.dev/en/stable/_modules/discord/onboarding Represents an onboarding prompt displayed in a guild. It includes attributes for ID, type, title, options, selection behavior, and requirement status. ```python class OnboardingPrompt: """Represents an onboarding prompt displayed in :class:`Onboarding`. .. versionadded:: 2.5 Attributes ---------- id: :class:`int` The id of the prompt. type: :class:`PromptType` The type of onboarding prompt. title: :class:`str` The prompt's title. options: List[:class:`PromptOption`] The list of options available in the prompt. single_select: :class:`bool` Whether the user is limited to selecting one option on this prompt. required: :class:`bool` Whether the user is required to answer this prompt. in_onboarding: :class:`bool` Whether this prompt is displayed in the initial onboarding flow """ def __init__( self, type: PromptType, title: str, options: list[PromptOption], single_select: bool, required: bool, in_onboarding: bool, id: int | None = None, # Currently optional as users can manually create these ): # ID is required when making edits, but it can be any snowflake that isn't already used by another prompt during edits self.id: int = int(id) if id else generate_snowflake() self.type: PromptType = type if isinstance(self.type, int): self.type = try_enum(PromptType, self.type) self.options: list[PromptOption] = options self.title: str = title self.single_select: bool = single_select self.required: bool = required self.in_onboarding: bool = in_onboarding def __repr__(): return f"" def to_dict(self) -> OnboardingPromptPayload: dict_: OnboardingPromptPayload = { "type": self.type.value, "title": self.title, "single_select": self.single_select, "required": self.required, "in_onboarding": self.in_onboarding, "options": [option.to_dict() for option in self.options], "id": self.id, } return dict_ @classmethod def _from_dict( cls, data: OnboardingPromptPayload, guild: Guild ) -> OnboardingPrompt: id = data.get("id", 0) type = try_enum(PromptType, data.get("type")) title = data.get("title") single_select = data.get("single_select") required = data.get("required") in_onboarding = data.get("in_onboarding") options = [ PromptOption._from_dict(option, guild) for option in data.get("options", []) ] return cls(type=type, title=title, single_select=single_select, required=required, in_onboarding=in_onboarding, options=options, id=id) # type: ignore ``` -------------------------------- ### Activity Start and Status API Source: https://docs.pycord.dev/en/stable/genindex API references for starting activities, setting user status, and related properties in discord.py. This includes starting the bot client, loops, and managing activity start times. ```APIDOC discord.Activity.start (property) Returns the start time of the activity. - Type: datetime.datetime discord.Game.start (property) Returns the start time of the game activity. - Type: datetime.datetime discord.Spotify.start (property) Returns the start time of the Spotify activity. - Type: datetime.datetime discord.ScheduledEvent.start_time (property) Returns the start time of the scheduled event. - Type: datetime.datetime discord.Permissions.start_embedded_activities (attribute) Represents permission to start embedded activities. discord.VoiceClient.start_recording() (method) Starts recording audio from the voice client. - Returns: None discord.Bot.start(activity=None) Starts the bot client. - Parameters: - activity: An Activity to set for the bot (optional). - Returns: None discord.Client.start(activity=None) Starts the client. - Parameters: - activity: An Activity to set for the client (optional). - Returns: None discord.ext.commands.Bot.start(activity=None) Starts the command bot client. - Parameters: - activity: An Activity to set for the bot (optional). - Returns: None discord.ext.tasks.Loop.start() Starts the background task loop. - Returns: None discord.Activity.state (property) Returns the state of the activity (e.g., 'Playing', 'Listening'). - Type: str discord.CustomActivity.state (property) Returns the state of the custom activity. - Type: str discord.Status (class in discord) Represents the online status of a user (online, idle, dnd, invisible). discord.AuditLogDiff.status (property) Returns the old status of a user or guild member in an audit log entry. - Type: discord.Status | None discord.Bot.status (property) Returns the current status of the bot. - Type: discord.Status discord.Client.status (property) Returns the current status of the client. - Type: discord.Status ``` -------------------------------- ### Discord Help Command Preparation Source: https://docs.pycord.dev/en/stable/genindex Reference to the 'prepare_help_command' method in Discord's help command system, used for setting up the help command. ```APIDOC discord.ext.commands.HelpCommand.prepare_help_command(): Method to prepare the help command before execution. ``` -------------------------------- ### Install Pycord (Pre-release) Source: https://docs.pycord.dev/en/stable/installing Installs the latest pre-release version of Pycord using pip. This is recommended for testing upcoming features. Supports both Linux/macOS and Windows environments. ```shell python3 -m pip install -U py-cord --pre ``` ```shell py -3 -m pip install -U py-cord --pre ``` -------------------------------- ### Install Pycord (Stable) Source: https://docs.pycord.dev/en/stable/installing Installs the latest stable version of Pycord using pip. This is the recommended method for production applications. Supports both Linux/macOS and Windows environments. ```shell python3 -m pip install -U py-cord ``` ```shell py -3 -m pip install -U py-cord ``` -------------------------------- ### VoiceClient Initialization and Dependencies Source: https://docs.pycord.dev/en/stable/_modules/discord/voice_client Illustrates the initialization of the VoiceClient class, highlighting its dependencies and internal setup. It shows how the client manages voice connections, including the use of Opus encoding and exponential backoff for retries. ```Python from __future__ import annotations import asyncio import logging import select import socket import struct import threading import time from typing import TYPE_CHECKING, Any, Callable, Literal, overload from . import opus, utils from .backoff import ExponentialBackoff from .errors import ClientException, ConnectionClosed from .gateway import * from .player import AudioPlayer, AudioSource from .sinks import RawData, RecordingException, Sink from .utils import MISSING if TYPE_CHECKING: from . import abc from .client import Client from .guild import Guild from .opus import Encoder from .state import ConnectionState from .types.voice import GuildVoiceState as GuildVoiceStatePayload from .types.voice import SupportedModes from .types.voice import VoiceServerUpdate as VoiceServerUpdatePayload from .user import ClientUser has_nacl: bool try: import nacl.secret # type: ignore has_nacl = True except ImportError: has_nacl = False __all__ = ( "VoiceProtocol", "VoiceClient", ) _log = logging.getLogger(__name__) ``` -------------------------------- ### Install Linux Dependencies for Voice Source: https://docs.pycord.dev/en/stable/installing On Debian-based Linux systems, specific development libraries are required to enable voice support in Pycord. This command installs those dependencies using apt. ```shell $ apt install libffi-dev libnacl-dev python3-dev ``` -------------------------------- ### Voice Playback: Before vs After Source: https://docs.pycord.dev/en/stable/migrating_to_v1 Compares the old method of creating and managing audio players with the new approach using VoiceClient.play() and AudioSource objects. ```Python vc = await client.join_voice_channel(channel) player = vc.create_ffmpeg_player('testing.mp3', after=lambda: print('done')) player.start() player.is_playing() player.pause() player.resume() player.stop() # ... ``` ```Python vc = await channel.connect() vc.play(discord.FFmpegPCMAudio('testing.mp3'), after=lambda e: print('done', e)) vc.is_playing() vc.pause() vc.resume() vc.stop() # ... ``` -------------------------------- ### Pycord: Onboarding Prompt Management API Source: https://docs.pycord.dev/en/stable/_modules/discord/onboarding This section details the API for managing onboarding prompts within the Pycord library. It covers retrieving and deleting prompts, including necessary permissions, parameters, return values, and potential exceptions. The methods are part of a class that handles guild onboarding configurations. ```python class OnboardingManager: # ... other methods ... def get_prompt(self, id: int): """ Retrieve an onboarding prompt by its ID. Parameters ---------- id: :class:`int` The ID of the prompt to retrieve. Returns ------- Optional[:class:`Prompt`] The matching prompt, or None if it didn't exist. """ return get(self.prompts, id=id) async def delete_prompt( self, id: int, *, reason: str | None = MISSING, ): """|coro| Delete an onboarding prompt with the given ID. You must have the :attr:`~Permissions.manage_guild` and :attr:`~Permissions.manage_roles` permissions in the guild to do this. Parameters ---------- id: :class:`int` The ID of the prompt to delete. reason: Optional[:class:`str`] The reason for deleting this prompt. Shows up on the audit log. Returns ------- :class:`Onboarding` The updated onboarding flow. Raises ------ ValueError No prompt with this ID exists. HTTPException Editing the onboarding flow failed somehow. Forbidden You don't have permission to edit the onboarding flow. """ to_delete = self.get_prompt(id) if not to_delete: raise ValueError("Prompt with the given ID was not found.") prompts = self.prompts[:] prompts.remove(to_delete) return await self.edit(prompts=prompts, reason=reason) ``` -------------------------------- ### API: Get or Fetch Utility Source: https://docs.pycord.dev/en/stable/genindex A utility function to get an object from cache or fetch it if not found. ```APIDOC discord.utils.get_or_fetch(obj_id: int, fetch_method: callable, cache: dict) - Gets an object from the cache or fetches it if not present. - Parameters: - obj_id: The ID of the object. - fetch_method: The method to call to fetch the object. - cache: The cache dictionary. - Returns: The fetched or cached object. ``` -------------------------------- ### MinimalHelpCommand Methods Source: https://docs.pycord.dev/en/stable/ext/commands/api Methods for the MinimalHelpCommand class, offering a more concise help message format. ```APIDOC discord.ext.commands.MinimalHelpCommand: sort_commands: bool Whether to sort commands alphabetically. commands_heading: str The heading for the commands list. aliases_heading: str The heading for command aliases. dm_help: bool Whether to send help messages via direct message. dm_help_threshold: int The minimum number of guilds a bot must be in to send help via DM. no_category: str The string to display for commands without a category. paginator: Paginator The paginator instance used for help messages. send_pages(pages: list) Sends the paginated help messages. get_opening_note() -> str Returns the opening note for the help message. get_command_signature(command) -> str Gets the signature string for a given command. get_ending_note() -> str Returns the ending note for the help message. add_bot_commands_formatting(commands: list) Formats bot commands for display. add_subcommand_formatting(command) Formats subcommands for display. add_aliases_formatting(command) Formats command aliases for display. add_command_formatting(command) Formats a single command for display. get_destination() Retrieves the destination for sending help messages. ``` -------------------------------- ### Entitlement Start Time API Source: https://docs.pycord.dev/en/stable/genindex API reference for the start time property of an Entitlement object in discord.py. ```APIDOC discord.Entitlement.starts_at (property) Returns the start timestamp of the entitlement. - Type: datetime.datetime ``` -------------------------------- ### Thread Starting Message API Source: https://docs.pycord.dev/en/stable/genindex API reference for the starting message property of a Thread object in discord.py. ```APIDOC discord.Thread.starting_message (property) Returns the message that started the thread. - Type: discord.Message | None ``` -------------------------------- ### Add Onboarding Prompt Source: https://docs.pycord.dev/en/stable/_modules/discord/onboarding Adds a new onboarding prompt to an existing flow. Requires manage guild and manage roles permissions. Specifies prompt type, title, options, selection behavior, and requirement status. ```APIDOC Onboarding.add_prompt(type: PromptType, title: str, options: list[PromptOption], single_select: bool, required: bool, in_onboarding: bool, *, reason: Optional[str] = None) Adds a new onboarding prompt. You must have the :attr:`~Permissions.manage_guild` and :attr:`~Permissions.manage_roles` permissions in the guild to do this. Parameters: type: :class:`PromptType` - The type of onboarding prompt. title: :class:`str` - The prompt's title. options: List[:class:`PromptOption`] - The list of options available in the prompt. single_select: :class:`bool` - Whether the user is limited to selecting one option on this prompt. required: :class:`bool` - Whether the user is required to answer this prompt. in_onboarding: :class:`bool` - Whether this prompt is displayed in the initial onboarding flow. reason: Optional[:class:`str`] - The reason for adding this prompt. Shows up on the audit log. Returns: :class:`Onboarding` - The updated onboarding flow. Raises: HTTPException - Editing the onboarding flow failed somehow. Forbidden - You don't have permissions to edit the onboarding flow. ``` -------------------------------- ### Client Construction with Intents Source: https://docs.pycord.dev/en/stable/intents Demonstrates how to construct a Pycord client, specifying intents and controlling the startup behavior for member chunking. ```python import discord # Option 1: Enable privileged intents for faster startup intents = discord.Intents.default() intents.members = True intents.presences = True client_with_privileged_intents = discord.Client(intents=intents) # Option 2: Disable member chunking at startup # This requires manually fetching members later if needed intents_no_chunk = discord.Intents.default() client_no_chunk = discord.Client( intents=intents_no_chunk, chunk_guilds_at_startup=False ) # Example of how to use these clients: # @client_with_privileged_intents.event # async def on_ready(): # print(f'Logged in as {client_with_privileged_intents.user}') # @client_no_chunk.event # async def on_ready(): # print(f'Logged in as {client_no_chunk.user}') # # To fetch members for a specific guild after startup: # # guild = client_no_chunk.get_guild(GUILD_ID) # # await guild.chunk(cache_guilds=True) # client_with_privileged_intents.run('YOUR_BOT_TOKEN') # client_no_chunk.run('YOUR_BOT_TOKEN') ``` -------------------------------- ### API: Get Max Size for Help Source: https://docs.pycord.dev/en/stable/genindex Gets the maximum size for the help command's output. ```APIDOC discord.ext.commands.HelpCommand.get_max_size() - Returns the maximum size allowed for the help command's output. ``` -------------------------------- ### Pycord: Prepare Help Command Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/help This asynchronous method prepares the help command for display. It clears the paginator and calls the superclass's `prepare_help_command` method to ensure proper initialization before formatting content. ```python async def prepare_help_command(self, ctx, command): self.paginator.clear() await super().prepare_help_command(ctx, command) ``` -------------------------------- ### API: Get Destination for Help Source: https://docs.pycord.dev/en/stable/genindex Gets the destination where the help message should be sent. This method is implemented by various help command classes. ```APIDOC discord.ext.commands.DefaultHelpCommand.get_destination() - Returns the channel or user where the help message should be sent. discord.ext.commands.HelpCommand.get_destination() - Returns the destination for the help message. discord.ext.commands.MinimalHelpCommand.get_destination() - Returns the destination for the help message. ``` -------------------------------- ### discord.ext.commands.MinimalHelpCommand API Source: https://docs.pycord.dev/en/stable/ext/commands/api Provides detailed documentation for the MinimalHelpCommand class, an implementation of a help command with minimal output. It outlines configurable attributes and methods for customizing help message generation in Discord bots. ```APIDOC class discord.ext.commands.MinimalHelpCommand(*args, **kwargs): """An implementation of a help command with minimal output. This inherits from [`HelpCommand`](#discord.ext.commands.HelpCommand). """ # Attributes sort_commands: bool Whether to sort the commands in the output alphabetically. Defaults to `True`. commands_heading: str The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands" aliases_heading: str The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:". dm_help: Optional[bool] A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to `True`, then all help output is DM’d. If `False`, none of the help output is DM’d. If `None`, then the bot will only DM when the help message becomes too long (dictated by more than [`dm_help_threshold`](#discord.ext.commands.MinimalHelpCommand.dm_help_threshold) characters). Defaults to `False`. dm_help_threshold: Optional[int] The number of characters the paginator must accumulate before getting DM’d to the user if [`dm_help`](#discord.ext.commands.MinimalHelpCommand.dm_help) is set to `None`. Defaults to 1000. no_category: str The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category" paginator: Paginator The paginator used to paginate the help command output. # Methods add_aliases_formatting(aliases): Formats the aliases for display. add_bot_commands_formatting(commands): Formats the bot commands for display. add_command_formatting(command): Formats a single command for display. add_subcommand_formatting(command): Formats a subcommand for display. get_command_signature(command): Returns the command signature. get_destination(): Returns the destination where the help message should be sent. get_ending_note(): Returns the ending note for the help message. get_opening_note(): Returns the opening note for the help message. async send_pages(): Sends the paginated help messages to the destination. ``` -------------------------------- ### API: Get Ending Note for Help Source: https://docs.pycord.dev/en/stable/genindex Gets the ending note displayed at the bottom of the help message. Implemented by specific help command classes. ```APIDOC discord.ext.commands.DefaultHelpCommand.get_ending_note() - Returns the string to be displayed at the end of the help message. discord.ext.commands.MinimalHelpCommand.get_ending_note() - Returns the string to be displayed at the end of the help message. ``` -------------------------------- ### HelpCommand.prepare_help_command Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/commands/help A low-level method that can be overridden to prepare the help command's state before execution. The default implementation does nothing, allowing subclasses to inject custom logic. ```python async def prepare_help_command(self, ctx, command=None): """|coro| 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. .. note:: This is called *inside* the help command callback body. So all the usual rules that happen inside apply here as well. Parameters ---------- ctx: :class:`Context` The invocation context. command: Optional[:class:`str`] The argument passed to the help command. """ pass ``` -------------------------------- ### Start Internal Task Source: https://docs.pycord.dev/en/stable/_modules/discord/ext/tasks Starts the internal asynchronous task in the event loop. It handles arguments, keyword arguments, and raises a RuntimeError if a task is already running. Returns the created asyncio.Task. ```python def start(self, *args: Any, **kwargs: Any) -> asyncio.Task[None]: r"""Starts the internal task in the event loop. Parameters ------------ *args The arguments to use. **kwargs The keyword arguments to use. Raises -------- RuntimeError A task has already been launched and is running. Returns --------- :class:`asyncio.Task` The task that has been created. """ if self._task is not MISSING and not self._task.done(): raise RuntimeError("Task is already launched and is not completed.") if self._injected is not None: args = (self._injected, *args) if self.loop is MISSING: self.loop = asyncio.get_event_loop() self._task = self.loop.create_task(self._loop(*args, **kwargs)) return self._task ``` -------------------------------- ### discord.Onboarding Append Prompt Method Source: https://docs.pycord.dev/en/stable/genindex Method to append a prompt to an onboarding object. ```APIDOC discord.Onboarding.append_prompt(prompt) - Description: Appends a new prompt to the onboarding object. ``` -------------------------------- ### IntegrationType Enum (Python) Source: https://docs.pycord.dev/en/stable/_modules/discord/enums Defines the types of integrations an application can have. This includes 'guild_install' for applications installed within a guild and 'user_install' for applications installed by individual users. ```python class IntegrationType(Enum): """The application's integration type""" guild_install = 0 user_install = 1 ``` -------------------------------- ### Wait for Bot Ready Before Task Start (Python) Source: https://docs.pycord.dev/en/stable/ext/tasks/index Demonstrates how to ensure a background task only starts after the Discord bot is fully ready. The `@tasks.loop.before_loop` decorator is used with `await self.bot.wait_until_ready()` to achieve this synchronization. ```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() ```