================ CODE SNIPPETS ================ TITLE: Basic discord.py Event Handling DESCRIPTION: A fundamental example of a discord.py client that logs in, prints a message when ready, and logs incoming messages. Requires the 'message_content' intent to be enabled. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/intro.rst#_snippet_3 LANGUAGE: python CODE: ``` # This example requires the 'message_content' intent. import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): print(f'Message from {message.author}: {message.content}') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('my token goes here') ``` -------------------------------- TITLE: discord.py: OnboardingPrompt Class DESCRIPTION: Represents a prompt within the guild's onboarding feature. These prompts guide new members through setup. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_265 LANGUAGE: python CODE: ``` class OnboardingPrompt: """Represents a prompt within the guild's onboarding feature.""" pass ``` -------------------------------- TITLE: Discord Extension Setup and Teardown DESCRIPTION: An example showing both the 'setup' function for loading an extension and the 'teardown' function for unloading it in discord.py. The 'teardown' function is called when the extension is unloaded and any exceptions raised are ignored. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/extensions.rst#_snippet_2 LANGUAGE: python CODE: ``` async def setup(bot): print('I am being loaded!') async def teardown(bot): print('I am being unloaded!') ``` -------------------------------- TITLE: Install discord.py DESCRIPTION: Installs the discord.py library using pip. For Windows users, a specific command is provided. Voice support can be enabled by including '[voice]' in the installation command. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/intro.rst#_snippet_0 LANGUAGE: shell CODE: ``` python3 -m pip install -U discord.py ``` LANGUAGE: shell CODE: ``` py -3 -m pip install -U discord.py ``` LANGUAGE: shell CODE: ``` python3 -m pip install -U discord.py[voice] ``` -------------------------------- TITLE: Create a Simple Discord Command Extension DESCRIPTION: An example of a basic discord.py extension that defines a command and adds it to the bot upon loading. It requires the discord.py library and defines an async 'setup' function. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/extensions.rst#_snippet_0 LANGUAGE: python CODE: ``` 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) ``` -------------------------------- TITLE: Install Debian Dependencies for Voice Support DESCRIPTION: Installs necessary system dependencies on Debian-based Linux distributions to enable voice support for discord.py. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/intro.rst#_snippet_1 LANGUAGE: shell CODE: ``` $ apt install libffi-dev libnacl-dev python3-dev ``` -------------------------------- TITLE: Install discord.py (Development Version) DESCRIPTION: Installs the latest development version of discord.py from GitHub, including voice support. This involves cloning the repository and installing locally. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.rst#_snippet_2 LANGUAGE: sh CODE: ``` $ git clone https://github.com/Rapptz/discord.py $ cd discord.py $ python3 -m pip install -U .[voice] ``` -------------------------------- TITLE: Install discord.py (With Voice Support) DESCRIPTION: Installs the discord.py library with full voice support. This requires additional dependencies, including PyNaCl. The installation command includes the '[voice]' extra. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.ja.rst#_snippet_1 LANGUAGE: sh CODE: ``` python3 -m pip install -U discord.py[voice] ``` LANGUAGE: sh CODE: ``` py -3 -m pip install -U discord.py[voice] ``` -------------------------------- TITLE: Install discord.py (Development Version) DESCRIPTION: Installs the development version of discord.py from its GitHub repository. This involves cloning the repository and then installing it using pip, with optional voice support. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.ja.rst#_snippet_2 LANGUAGE: sh CODE: ``` git clone https://github.com/Rapptz/discord.py cd discord.py python3 -m pip install -U .[voice] ``` -------------------------------- TITLE: Setup Discord Logging Manually DESCRIPTION: Shows how to use `discord.utils.setup_logging()` to apply the library's default logging configuration without using `client.run`. Allows customization of level and root logger. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_4 LANGUAGE: python CODE: ``` import discord import logging discord.utils.setup_logging() # or, for example discord.utils.setup_logging(level=logging.INFO, root=False) ``` -------------------------------- TITLE: discord.py: WelcomeScreen Class DESCRIPTION: Represents the welcome screen for a guild. This feature helps new members get started by providing channels and information. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_254 LANGUAGE: python CODE: ``` class WelcomeScreen: """Represents the welcome screen for a guild.""" pass ``` -------------------------------- TITLE: Install discord.py (with Voice Support) DESCRIPTION: Installs discord.py with voice support. Requires Python 3.8 or higher and specific system packages (like libffi-dev) on Linux before installation. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.rst#_snippet_1 LANGUAGE: sh CODE: ``` # Linux/macOS python3 -m pip install -U "discord.py[voice]" # Windows py -3 -m pip install -U discord.py[voice] ``` -------------------------------- TITLE: Wait for bot readiness before starting a discord.ext.tasks loop DESCRIPTION: This example shows how to ensure a discord.ext.tasks loop only starts after the bot has finished its initial setup and is ready. It uses the `@tasks.loop.before_loop` decorator to achieve this synchronization. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/tasks/index.rst#_snippet_3 LANGUAGE: python CODE: ``` 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() ``` -------------------------------- TITLE: Discord Bot with Commands Example DESCRIPTION: An example of a Discord bot using the `discord.ext.commands` extension. It sets up a bot with a '>' prefix and defines a 'ping' command that replies with 'pong'. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.rst#_snippet_4 LANGUAGE: py CODE: ``` import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='>', intents=intents) @bot.command() async def ping(ctx): await ctx.send('pong') bot.run('token') ``` -------------------------------- TITLE: Basic Discord Client Example DESCRIPTION: A simple example of a Discord client using discord.py. It defines a class that inherits from discord.Client, handling the 'on_ready' and 'on_message' events. The client logs in with a provided token. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.ja.rst#_snippet_3 LANGUAGE: py CODE: ``` import discord class MyClient(discord.Client): async def on_ready(self): print('Logged on as', self.user) async def on_message(self, message): # don't respond to ourselves if message.author == self.user: return if message.content == 'ping': await message.channel.send('pong') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('token') ``` -------------------------------- TITLE: Install discord.py (Basic) DESCRIPTION: Installs the discord.py library without voice support. Requires Python 3.8 or higher. A virtual environment is recommended. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.rst#_snippet_0 LANGUAGE: sh CODE: ``` # Linux/macOS python3 -m pip install -U discord.py # Windows py -3 -m pip install -U discord.py ``` -------------------------------- TITLE: Install discord.py (No Voice Support) DESCRIPTION: Installs the discord.py library without voice support. This is the basic installation for most users. It uses pip to install the package and its dependencies. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.ja.rst#_snippet_0 LANGUAGE: sh CODE: ``` python3 -m pip install -U discord.py ``` LANGUAGE: sh CODE: ``` py -3 -m pip install -U discord.py ``` -------------------------------- TITLE: Discord Bot with Commands Example DESCRIPTION: An example of a Discord bot using the commands extension of discord.py. It sets up a bot with a command prefix and defines a simple 'ping' command that responds with 'pong'. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.ja.rst#_snippet_4 LANGUAGE: py CODE: ``` import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='>', intents=intents) @bot.command() async def ping(ctx): await ctx.send('pong') bot.run('token') ``` -------------------------------- TITLE: Add Support for User-Installable Apps DESCRIPTION: Enables the creation of user-installable applications, allowing users to install bots or commands directly. This involves new attributes for commands and functions to manage installation types. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_105 LANGUAGE: Python CODE: ``` from discord.app_commands import allowed_installs, guild_install, user_install, AppInstallationType from discord.app_commands import Command, AppCommand, ContextMenu from discord import Interaction # Example usage (conceptual): # @user_install() # async def my_user_command(interaction: discord.Interaction): # pass # interaction.is_user_integration() ``` -------------------------------- TITLE: Python: Asynchronous Extension Setup Function DESCRIPTION: Demonstrates the change in the setup function for extensions from a regular function to an asynchronous coroutine in discord.py v2.0. This change is part of the broader asynchronous updates for extension and cog management. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_70 LANGUAGE: python CODE: ``` # before def setup(bot): bot.add_cog(MyCog(bot)) # after async def setup(bot): await bot.add_cog(MyCog(bot)) ``` -------------------------------- TITLE: Set Discord Log Level to DEBUG DESCRIPTION: Configures the logging level for discord.py to DEBUG, allowing verbose output for troubleshooting. This example also shows redirecting logs to a file. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_2 LANGUAGE: python CODE: ``` 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) ``` -------------------------------- TITLE: Install discord.py with Speed Extras DESCRIPTION: Installs the discord.py library with the 'speed' extras, which includes zstd gateway compression support. This is useful for improving performance in certain environments. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_103 LANGUAGE: Shell CODE: ``` pip install discord.py[speed] ``` -------------------------------- TITLE: Create and Activate Virtual Environment DESCRIPTION: Demonstrates how to create a Python virtual environment and activate it for project dependency management. Includes commands for both Linux/macOS and Windows. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/intro.rst#_snippet_2 LANGUAGE: shell CODE: ``` $ cd your-bot-source $ python3 -m venv bot-env ``` LANGUAGE: shell CODE: ``` $ source bot-env/bin/activate ``` LANGUAGE: shell CODE: ``` $ bot-env\Scripts\activate.bat ``` -------------------------------- TITLE: discord.py: Logging Setup DESCRIPTION: This section explains how to set up the Python logging module for discord.py. It highlights that if the logging module is not configured, diagnostic and error logs from the library will not be output anywhere. Refer to the logging setup section for more details. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_0 LANGUAGE: Python CODE: ``` import discord # ... logging setup code here ... client = discord.Client() # ... rest of your client code ... ``` -------------------------------- TITLE: Minimal Discord Bot in Python DESCRIPTION: Creates a basic Discord bot that logs in, prints a ready message, and responds to a '$hello' command with 'Hello!'. Requires the 'message_content' intent. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/quickstart.rst#_snippet_0 LANGUAGE: python CODE: ``` # This example requires the 'message_content' intent. import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') client.run('your token here') ``` -------------------------------- TITLE: Advanced Logging Setup with Rotating File Handler DESCRIPTION: Implements a more advanced logging setup using `RotatingFileHandler` for `discord.py`. It configures different log levels for the 'discord' and 'discord.http' loggers and custom formatting. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_5 LANGUAGE: python CODE: ``` import discord import logging import logging.handlers logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) logging.getLogger('discord.http').setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( filename='discord.log', encoding='utf-8', maxBytes=32 * 1024 * 1024, # 32 MiB backupCount=5, # Rotate through 5 files ) dt_fmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{') handler.setFormatter(formatter) logger.addHandler(handler) # Assume client refers to a discord.Client subclass... # Suppress the default configuration since we have our own client.run(token, log_handler=None) ``` -------------------------------- TITLE: Running the Python Bot on Windows DESCRIPTION: Command to execute the Python bot script on a Windows system using the 'py' launcher. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/quickstart.rst#_snippet_1 LANGUAGE: shell CODE: ``` $ py -3 example_bot.py ``` -------------------------------- TITLE: Activity Start Time DESCRIPTION: Adds the Activity.created_at attribute to view when an activity was started. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_492 LANGUAGE: Python CODE: ``` Activity.created_at ``` -------------------------------- TITLE: discord.py: Basic FlagConverter Example DESCRIPTION: Provides an example of a custom FlagConverter for a 'ban' command, defining required flags like 'member' and 'reason', and an optional 'days' flag. It demonstrates how to parse these flags into a class. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_25 LANGUAGE: python CODE: ``` from discord.ext import commands import discord class BanFlags(commands.FlagConverter): member: discord.Member reason: str days: int = 1 @commands.command() async def ban(ctx, *, flags: BanFlags): plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day' await ctx.send(f'Banned {flags.member} for {flags.reason!r} (deleted {plural} worth of messages)') ``` -------------------------------- TITLE: discord.app_commands.user_install decorator DESCRIPTION: A decorator to indicate that a command is intended for user installation. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/interactions/api.rst#_snippet_50 LANGUAGE: Python CODE: ``` def user_install(): pass ``` -------------------------------- TITLE: Running the Python Bot on Other Systems DESCRIPTION: Command to execute the Python bot script on non-Windows systems using the 'python3' command. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/quickstart.rst#_snippet_2 LANGUAGE: shell CODE: ``` $ python3 example_bot.py ``` -------------------------------- TITLE: discord.py: SessionStartLimits Class DESCRIPTION: Details the limits for starting sessions, often related to gateway connections and rate limits. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_271 LANGUAGE: python CODE: ``` class SessionStartLimits: """Details the limits for starting sessions.""" pass ``` -------------------------------- TITLE: discord.app_commands.allowed_installs decorator DESCRIPTION: A decorator to specify the types of installations allowed for a command. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/interactions/api.rst#_snippet_52 LANGUAGE: Python CODE: ``` def allowed_installs(*installs): pass ``` -------------------------------- TITLE: Basic Discord Client Example DESCRIPTION: A simple asynchronous Discord client that logs in, prints a message when ready, and responds to 'ping' with 'pong'. It requires the `discord` library and message content intent. SOURCE: https://github.com/rapptz/discord.py/blob/master/README.rst#_snippet_3 LANGUAGE: py CODE: ``` import discord class MyClient(discord.Client): async def on_ready(self): print('Logged on as', self.user) async def on_message(self, message): # don't respond to ourselves if message.author == self.user: return if message.content == 'ping': await message.channel.send('pong') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('token') ``` -------------------------------- TITLE: Global Before/After Invocation Hooks DESCRIPTION: Demonstrates how to register global hooks that execute before and after any command is invoked. These are useful for general setup or cleanup tasks. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_69 LANGUAGE: Python CODE: ``` async def before_any_command(ctx): # do something before a command is called pass async def after_any_command(ctx): # do something after a command is called pass # bot.before_invoke = before_any_command # bot.after_invoke = after_any_command ``` -------------------------------- TITLE: Example Cog with Special Methods and Custom Name in discord.py DESCRIPTION: Provides an example of a discord.py cog that utilizes various special methods for customization and error handling. It includes `cog_unload`, `bot_check`, `bot_check_once`, `cog_check`, `cog_command_error`, `cog_before_invoke`, and `cog_after_invoke`, along with a custom cog name. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_68 LANGUAGE: python CODE: ``` class MyCog(commands.Cog, name='Example Cog'): def cog_unload(self): print('cleanup goes here') def bot_check(self, ctx): print('bot check') return True def bot_check_once(self, ctx): print('bot check once') return True async def cog_check(self, ctx): print('cog local check') return await ctx.bot.is_owner(ctx.author) async def cog_command_error(self, ctx, error): # Error handling logic here ``` -------------------------------- TITLE: App Info Approximate User Install Count DESCRIPTION: Adds approximate_user_install_count to AppInfo, providing an estimate of user installs for an application. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_72 LANGUAGE: Python CODE: ``` app_info.approximate_user_install_count ``` -------------------------------- TITLE: Handle exceptions during reconnect with discord.ext.tasks DESCRIPTION: This example shows how to add specific exception types, like asyncpg.PostgresConnectionError, to be handled by a discord.ext.tasks loop. It configures the loop to catch these exceptions and includes starting and cancelling the task within a Cog. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/tasks/index.rst#_snippet_1 LANGUAGE: python CODE: ``` import asyncpg from discord.ext import tasks, commands class MyCog(commands.Cog): def __init__(self, bot): self.bot = bot self.data = [] self.batch_update.add_exception_type(asyncpg.PostgresConnectionError) self.batch_update.start() def cog_unload(self): self.batch_update.cancel() @tasks.loop(minutes=5.0) async def batch_update(self): async with self.bot.pool.acquire() as con: # batch update here... pass ``` -------------------------------- TITLE: discord.py: Client Event Handling Example DESCRIPTION: Demonstrates how to handle Discord events using discord.py. It shows two primary methods: using the `Client.event` decorator or subclassing `discord.Client` and overriding event methods. The example specifically illustrates overriding the `on_message` event. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_1 LANGUAGE: Python CODE: ``` import discord class MyClient(discord.Client): async def on_message(self, message): if message.author == self.user: return if message.content.startswith('$hello'): await message.channel.send('Hello World!') # To use this, you would instantiate MyClient and run it: # client = MyClient() # client.run('YOUR_BOT_TOKEN') ``` -------------------------------- TITLE: Custom Minimal Help Command Implementation in discord.py DESCRIPTION: Demonstrates how to create a custom help command by subclassing `commands.MinimalHelpCommand`. This example overrides `get_command_signature` to format command signatures and shows how to associate the custom help command with a cog and manage its lifecycle. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_67 LANGUAGE: python CODE: ``` class MyHelpCommand(commands.MinimalHelpCommand): def get_command_signature(self, command): return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command) class MyCog(commands.Cog): def __init__(self, bot): self._original_help_command = bot.help_command bot.help_command = MyHelpCommand() bot.help_command.cog = self def cog_unload(self): self.bot.help_command = self._original_help_command ``` -------------------------------- TITLE: Fetch Session Start Limits DESCRIPTION: Adds the ability to fetch session start limits for the AutoShardedClient. This is useful for understanding rate limiting behavior. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_56 LANGUAGE: Python CODE: ``` await client.fetch_session_start_limits() ``` -------------------------------- TITLE: Using aiohttp ClientSession DESCRIPTION: Demonstrates the recommended way to use aiohttp for making HTTP requests by creating a ClientSession. It shows how to perform a GET request and handle the response, emphasizing the importance of closing the session when it's no longer needed. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_51 LANGUAGE: python CODE: ``` async with aiohttp.ClientSession() as sess: async with sess.get('url') as resp: # work with resp ``` -------------------------------- TITLE: discord.app_commands.guild_install decorator DESCRIPTION: A decorator to indicate that a command is intended for guild installation. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/interactions/api.rst#_snippet_51 LANGUAGE: Python CODE: ``` def guild_install(): pass ``` -------------------------------- TITLE: Make Web Requests with aiohttp DESCRIPTION: Shows how to make asynchronous HTTP requests using the `aiohttp` library, which is a dependency of discord.py. This example fetches a JSON response from a public API. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/faq.rst#_snippet_16 LANGUAGE: python CODE: ``` 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() ``` -------------------------------- TITLE: Custom Flag Syntax: WindowsLikeFlags DESCRIPTION: This example demonstrates customizing flag syntax with a '/' prefix and an empty delimiter, mimicking Windows-like command syntax. It defines a 'make' flag of type string. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_29 LANGUAGE: python CODE: ``` class WindowsLikeFlags(commands.FlagConverter, prefix='/', delimiter=''): make: str ``` -------------------------------- TITLE: Python: Combine commands.Greedy with typing.Optional DESCRIPTION: Demonstrates combining `commands.Greedy` with `typing.Optional` to create flexible command signatures. This example allows an optional integer argument for `delete_days` before processing multiple members for a ban operation. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_20 LANGUAGE: python CODE: ``` import discord import typing from discord.ext import commands @bot.command() async def ban(ctx, members: commands.Greedy[discord.Member], delete_days: typing.Optional[int] = 0, *, reason: str): """Mass bans members with an optional delete_days parameter""" delete_seconds = delete_days * 86400 # one day for member in members: await member.ban(delete_message_seconds=delete_seconds, reason=reason) ``` -------------------------------- TITLE: Custom Client with setup_hook in discord.py DESCRIPTION: Illustrates subclassing discord.Client to implement the setup_hook method, which is executed asynchronously after login but before connecting to the gateway. This is useful for initializing bot features in an async context. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_1 LANGUAGE: Python CODE: ``` import discord class MyClient(discord.Client): async def setup_hook(self): print('This is asynchronous!') client = MyClient() client.run(TOKEN) # TOKEN should be defined ``` -------------------------------- TITLE: Fix cchardet Installation for Python >=3.10 DESCRIPTION: Resolves an issue where ``cchardet`` was incorrectly installed on Python versions 3.10 and above when using the ``speed`` extras. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_283 LANGUAGE: Python CODE: ``` Fix ``cchardet`` being installed on Python >=3.10 when using the ``speed`` extras. ``` -------------------------------- TITLE: Configure File Handler for Discord Logs DESCRIPTION: Sets up a FileHandler to redirect discord.py logs to a file named 'discord.log'. This is useful for persistent logging of errors and debug information. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_0 LANGUAGE: python CODE: ``` 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) ``` -------------------------------- TITLE: Implement before_invoke and after_invoke decorators DESCRIPTION: Adds decorators to execute functions before and after a command is invoked, useful for setup and cleanup. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_443 LANGUAGE: Python CODE: ``` from discord.ext import commands @commands.before_invoke def pre_command(ctx): print('Executing before command') @commands.after_invoke def post_command(ctx): print('Executing after command') ``` -------------------------------- TITLE: Asyncio Event Loop with discord.py Client DESCRIPTION: Demonstrates how to use asyncio.run to manage the event loop for a discord.py client, allowing for other asynchronous operations before starting the client. It shows the modern approach to running asynchronous applications. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_0 LANGUAGE: Python CODE: ``` import discord import asyncio client = discord.Client() async def main(): # do other async things await my_async_function() # Assuming my_async_function is defined elsewhere # start the client async with client: await client.start(TOKEN) # TOKEN should be defined asyncio.run(main()) ``` -------------------------------- TITLE: Synchronous Webhook Usage in discord.py DESCRIPTION: Illustrates the changes in synchronous webhook handling within discord.py. This example shows the transition from using RequestsWebhookAdapter to the new SyncWebhook class for creating and sending webhook messages. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_5 LANGUAGE: python CODE: ``` # 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') ``` -------------------------------- TITLE: Custom Context Example DESCRIPTION: Demonstrates how to use a custom context class in discord.py commands. The custom context provides access to additional attributes like 'secret'. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_55 LANGUAGE: python CODE: ``` async def on_message(self, message): ctx = await self.get_context(message, cls=MyContext) await self.invoke(ctx) ``` LANGUAGE: python CODE: ``` @bot.command() async def secret(ctx): await ctx.send(ctx.secret) ``` -------------------------------- TITLE: Get User Info with discord.py Client DESCRIPTION: This method corresponds to Client.fetch_user, used to retrieve user information. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_28 LANGUAGE: Python CODE: ``` client.get_user_info(user_id) ``` -------------------------------- TITLE: Get Application Information with Teams DESCRIPTION: Fetches application information, including support for teams. This is accessed through the Client.application_info method. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_476 LANGUAGE: Python CODE: ``` Client.application_info ``` -------------------------------- TITLE: Python: Use typing.Annotated for Custom Converters DESCRIPTION: Shows how to use `typing.Annotated` to provide a type hint for static analysis while specifying a custom converter for runtime execution. The example converts the input string argument to uppercase using a lambda function. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_18 LANGUAGE: python CODE: ``` from typing import Annotated @bot.command() async def fun(ctx, arg: Annotated[str, lambda s: s.upper()]): await ctx.send(arg) ``` -------------------------------- TITLE: Get Guild Emoji DESCRIPTION: Adds a helper method to get a specific emoji from a guild. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_189 LANGUAGE: Python CODE: ``` emoji = await guild.get_emoji(emoji_id) ``` -------------------------------- TITLE: Converter System - After v1.0 DESCRIPTION: Example of a converter class after version 1.0, where the `convert` method is a coroutine and accepts both `ctx` and `argument`. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_73 LANGUAGE: Python CODE: ``` class MyConverter(commands.Converter): async def convert(self, ctx, argument): return ctx.me ``` -------------------------------- TITLE: Get Invite with discord.py Client DESCRIPTION: This method corresponds to Client.fetch_invite, used to retrieve an invite object from its code. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_25 LANGUAGE: Python CODE: ``` client.get_invite(invite_code) ``` -------------------------------- TITLE: Converter System - Before v1.0 DESCRIPTION: Example of a converter class before version 1.0, where the `convert` method was not necessarily a coroutine and only took the argument string. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_72 LANGUAGE: Python CODE: ``` class MyConverter(commands.Converter): def convert(self): return self.ctx.message.server.me ``` -------------------------------- TITLE: Intents Requirement in discord.py Client Initialization DESCRIPTION: Shows the change in discord.py v2.0 regarding intents. Previously optional, intents are now required during client initialization. This example contrasts the old and new ways of creating a client with default intents. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_2 LANGUAGE: Python CODE: ``` # before # client = discord.Client() # after intents = discord.Intents.default() client = discord.Client(intents=intents) ``` -------------------------------- TITLE: Customizing discord.py Context DESCRIPTION: Provides an example of subclassing discord.ext.commands.Context to add custom functionality. It defines a 'MyContext' class with a 'secret' property and shows how to use it with a custom Bot subclass by overriding get_context and invoke. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_54 LANGUAGE: python CODE: ``` class MyContext(commands.Context): @property def secret(self): return 'my secret here' ``` LANGUAGE: python CODE: ``` class MyBot(commands.Bot): ``` -------------------------------- TITLE: Invite Code DESCRIPTION: Gets the invite's code. This attribute is of type str. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_220 LANGUAGE: Python CODE: ``` code The invite's code. See also :attr:`Invite.code` :type: :class:`str` ``` -------------------------------- TITLE: Sending a Message to a Specific Channel DESCRIPTION: Provides an example of how to send a message to a specific channel by first fetching the channel object using its ID and then calling the `send` method. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/faq.rst#_snippet_3 LANGUAGE: Python CODE: ``` channel = client.get_channel(12324234183172) await channel.send('hello') ``` -------------------------------- TITLE: Asynchronous HTTP Request with aiohttp DESCRIPTION: Shows how to perform asynchronous HTTP GET requests using the `aiohttp` library, which is suitable for asyncio applications, compared to a blocking approach with `requests`. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/faq.rst#_snippet_1 LANGUAGE: Python CODE: ``` # bad r = requests.get('http://aws.random.cat/meow') if r.status_code == 200: js = r.json() await channel.send(js['file']) # good 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() await channel.send(js['file']) ``` -------------------------------- TITLE: discord.py: OnboardingPromptOption Class DESCRIPTION: Represents an option for an onboarding prompt. Users select these options to customize their onboarding experience. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_266 LANGUAGE: python CODE: ``` class OnboardingPromptOption: """Represents an option for an onboarding prompt.""" pass ``` -------------------------------- TITLE: Client Constructor DESCRIPTION: Configures the client at startup. Use 'chunk_guild_at_startup' instead of the 'fetch_offline_members' parameter. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_66 LANGUAGE: python CODE: ``` client = discord.Client(chunk_guild_at_startup=True) ``` -------------------------------- TITLE: Create a simple background task using discord.ext.tasks DESCRIPTION: This snippet demonstrates how to create a basic background task that runs every 5 seconds within a discord.py Cog. It includes starting the task in the Cog's constructor and cancelling it when the Cog is unloaded. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/tasks/index.rst#_snippet_0 LANGUAGE: python CODE: ``` 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 ``` -------------------------------- TITLE: Custom Flag Syntax: Case-Insensitive Settings DESCRIPTION: This example defines a FlagConverter named 'Settings' with case-insensitive flag parsing. It includes optional flags for 'topic' (string), 'nsfw' (boolean), and 'slowmode' (integer), allowing them to be specified in any case. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_30 LANGUAGE: python CODE: ``` class Settings(commands.FlagConverter, case_insensitive=True): topic: Optional[str] nsfw: Optional[bool] slowmode: Optional[int] ``` -------------------------------- TITLE: Define a Simple Command DESCRIPTION: Demonstrates how to define a basic command using the @bot.command() decorator. This command takes a context object and an argument, then sends the argument back to the channel. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_0 LANGUAGE: python CODE: ``` @bot.command() async def foo(ctx, arg): await ctx.send(arg) ``` -------------------------------- TITLE: discord.py: Customizing FlagConverter with flag() DESCRIPTION: Illustrates customizing FlagConverter behavior using the commands.flag function. This example maps a 'members' attribute to a 'member' flag and sets a default empty list. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_26 LANGUAGE: python CODE: ``` from typing import List class BanFlags(commands.FlagConverter): members: List[discord.Member] = commands.flag(name='member', default=lambda ctx: []) ``` -------------------------------- TITLE: Send a message and get the Message object DESCRIPTION: Demonstrates how to send a message using discord.py and access the returned Message object, specifically its ID. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/faq.rst#_snippet_5 LANGUAGE: python CODE: ``` message = await channel.send('hmm…') message_id = message.id ``` -------------------------------- TITLE: Configure Specific Intents in discord.py DESCRIPTION: Shows how to initialize intents by specifying only the necessary ones, such as messages and guilds. This approach allows for a more granular control over event subscriptions. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/intents.rst#_snippet_1 LANGUAGE: python CODE: ``` import discord intents = discord.Intents(messages=True, guilds=True) # If you also want reaction events enable the following: # intents.reactions = True # Somewhere else: # client = discord.Client(intents=intents) # or # from discord.ext import commands # bot = commands.Bot(command_prefix='!', intents=intents) ``` -------------------------------- TITLE: Get Reaction Users with discord.py Client DESCRIPTION: This method corresponds to Reaction.users, used to retrieve a list of users who reacted to a message. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_27 LANGUAGE: Python CODE: ``` client.get_reaction_users(reaction) ``` -------------------------------- TITLE: Python: Asynchronous Extension Loading with Bot DESCRIPTION: Illustrates how to load extensions asynchronously in discord.py v2.0. It shows two methods: using `setup_hook` within a custom Bot class and using an `async with bot:` block in a main function. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_71 LANGUAGE: python CODE: ``` # 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()) ``` -------------------------------- TITLE: Get Message with discord.py Client DESCRIPTION: This method corresponds to abc.Messageable.fetch_message, used to retrieve a specific message from a channel. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_26 LANGUAGE: Python CODE: ``` client.get_message(channel, message_id) ``` -------------------------------- TITLE: Disable Default Discord Logging Configuration DESCRIPTION: Demonstrates how to completely disable the default logging configuration provided by discord.py by passing `log_handler=None` to `client.run`. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_1 LANGUAGE: python CODE: ``` client.run(token, log_handler=None) ``` -------------------------------- TITLE: discord.py Onboarding Prompt Attributes DESCRIPTION: This section details the attributes of an onboarding prompt within the discord.py library. It covers properties like default channels, prompts, title, single select options, required status, in onboarding status, and mode. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_246 LANGUAGE: Python CODE: ``` class Onboarding: default_channels: List[Union[GuildChannel, Object]] prompts: List[OnboardingPrompt] mode: OnboardingMode class OnboardingPrompt: title: str single_select: bool required: bool in_onboarding: bool ``` -------------------------------- TITLE: Get Invites From Channel with discord.py Client DESCRIPTION: This method corresponds to abc.GuildChannel.invites or Guild.invites, used to retrieve invites from a guild channel. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_29 LANGUAGE: Python CODE: ``` client.invites_from(channel) ``` -------------------------------- TITLE: Get Thread from ForumChannel DESCRIPTION: Adds the get_thread method to ForumChannel for retrieving a specific thread. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_204 LANGUAGE: Python CODE: ``` thread = await forum_channel.get_thread(thread_id) ``` -------------------------------- TITLE: Variable Arguments (*args) DESCRIPTION: Shows how to accept an arbitrary number of arguments using the *args syntax, similar to Python's variable-length argument lists. Arguments are joined into a tuple. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_4 LANGUAGE: python CODE: ``` @bot.command() async def test(ctx, *args): arguments = ', '.join(args) await ctx.send(f'{len(args)} arguments: {arguments}') ``` -------------------------------- TITLE: Python: Local Command Error Handler DESCRIPTION: Provides an example of a local error handler for a `discord.py` command named `info`. It specifically catches `commands.BadArgument` and sends a user-friendly message. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_41 LANGUAGE: python CODE: ``` @bot.command() async def info(ctx, *, member: discord.Member): """Tells you some info about the member.""" msg = f'{member} joined on {member.joined_at} and has {len(member.roles)} roles.' await ctx.send(msg) @info.error async def info_error(ctx, error): if isinstance(error, commands.BadArgument): await ctx.send('I could not find that member...') ``` -------------------------------- TITLE: Member Avatar Asset DESCRIPTION: Gets the avatar of a member. This attribute is of type Asset. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_229 LANGUAGE: Python CODE: ``` avatar The avatar of a member. See also :attr:`User.avatar`. :type: :class:`Asset` ``` -------------------------------- TITLE: discord.py v1.2.0: Member Nitro Boosting Attribute DESCRIPTION: Adds the `Member.premium_since` attribute to query when a member started boosting the guild. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_582 LANGUAGE: Python CODE: ``` import discord # async def display_member_boost_time(member: discord.Member): # if member.premium_since: # print(f"{member.name} has been boosting since {member.premium_since}") # else: # print(f"{member.name} is not currently boosting.") ``` -------------------------------- TITLE: Object ID DESCRIPTION: Gets the ID of the object being changed. This attribute is of type int. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_228 LANGUAGE: Python CODE: ``` id The ID of the object being changed. :type: :class:`int` ``` -------------------------------- TITLE: Create Guild Template DESCRIPTION: Creates a template for a guild. The 'description' parameter is no longer optional and expects a string describing the template. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating.rst#_snippet_50 LANGUAGE: python CODE: ``` await guild.create_template(name='My Template', description='A template for my server') ``` -------------------------------- TITLE: Apply Discord Logging to Root Logger DESCRIPTION: Enables the discord.py logging configuration to affect all loggers in the application, not just the 'discord' logger, by setting `root_logger=True`. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/logging.rst#_snippet_3 LANGUAGE: python CODE: ``` client.run(token, log_handler=handler, root_logger=True) ``` -------------------------------- TITLE: Get Member Nickname (discord.py) DESCRIPTION: Retrieves the nickname of a member in a Discord guild. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_210 LANGUAGE: Python CODE: ``` member.nick ``` -------------------------------- TITLE: Expire Behaviour DESCRIPTION: Gets the behaviour of expiring subscribers. This attribute is documented under both 'expire_behaviour' and 'expire_behavior'. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_245 LANGUAGE: Python CODE: ``` expire_behaviour expire_behavior The behaviour of expiring subscribers changed. ``` -------------------------------- TITLE: discord.py: Onboarding Class DESCRIPTION: Represents the onboarding feature for a guild. This helps new members discover relevant channels and information. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_264 LANGUAGE: python CODE: ``` class Onboarding: """Represents the onboarding feature for a guild.""" pass ``` -------------------------------- TITLE: discord.py: AuditLogEntry.onboarding_create DESCRIPTION: Represents an audit log entry when the guild's onboarding configuration is created. AuditLogDiff can contain enabled, default_channels, and prompts. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_150 LANGUAGE: python CODE: ``` onboarding_create = "The guild's onboarding configuration was created." ``` -------------------------------- TITLE: Invite Uses DESCRIPTION: Gets the current number of uses for the invite. This attribute is of type int. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_224 LANGUAGE: Python CODE: ``` uses The invite's current uses. See also :attr:`Invite.uses`. :type: :class:`int` ``` -------------------------------- TITLE: Get Role Color (discord.py) DESCRIPTION: Retrieves the color associated with a role in a Discord guild. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_214 LANGUAGE: Python CODE: ``` role.colour ``` LANGUAGE: Python CODE: ``` role.color ``` -------------------------------- TITLE: Get All Emojis with discord.py Client DESCRIPTION: This method is an alias for accessing Client.emojis, providing a way to retrieve all emojis available to the client. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/migrating_to_v1.rst#_snippet_23 LANGUAGE: Python CODE: ``` client.get_all_emojis() ``` -------------------------------- TITLE: Hybrid command equivalent for BanFlags DESCRIPTION: This example illustrates how a FlagConverter used in a hybrid command is flattened into individual parameters for the application command. The BanFlags converter with 'member', 'reason', and 'days' parameters is shown to be equivalent to a hybrid command with these parameters directly defined. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_35 LANGUAGE: python CODE: ``` class BanFlags(commands.FlagConverter): member: discord.Member reason: str days: int = 1 @commands.hybrid_command() async def ban(ctx, *, flags: BanFlags): ... # Equivalent application command definition: @commands.hybrid_command() async def ban(ctx, member: discord.Member, reason: str, days: int = 1): ... ``` -------------------------------- TITLE: User Timed Out Until DESCRIPTION: Gets the datetime until which a user is timed out, if applicable. This attribute is of type Optional[datetime.datetime]. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_243 LANGUAGE: Python CODE: ``` timed_out_until Whether the user is timed out, and if so until when. :type: Optional[:class:`datetime.datetime`] ``` -------------------------------- TITLE: Creating a Server DESCRIPTION: Details the process of creating a new Discord server programmatically using the 'create_server' method. This requires appropriate permissions. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_645 LANGUAGE: Python CODE: ``` new_server = await client.create_server('My New Server') ``` -------------------------------- TITLE: Getting Active Invites DESCRIPTION: Demonstrates how to fetch currently active invites within a server using the 'invites_from' method of the Client. This can help in tracking invite usage and managing server access. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/whats_new.rst#_snippet_640 LANGUAGE: Python CODE: ``` invites = await client.invites_from(guild) ``` -------------------------------- TITLE: Guild/Sticker/Event Description DESCRIPTION: Gets the description for a guild, sticker, or scheduled event. This attribute is of type str. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_236 LANGUAGE: Python CODE: ``` description The description of a guild, a sticker, or a scheduled event. See also :attr:`Guild.description`, :attr:`GuildSticker.description`, or :attr:`ScheduledEvent.description`. :type: :class:`str` ``` -------------------------------- TITLE: discord.py: AuditLogEntry.onboarding_prompt_create DESCRIPTION: Represents an audit log entry when a guild onboarding prompt is created. AuditLogDiff can contain type, title, options, single_select, required, and in_onboarding. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_147 LANGUAGE: python CODE: ``` onboarding_prompt_create = "A guild onboarding prompt was created." ``` -------------------------------- TITLE: discord.py: RawTypingEvent Class DESCRIPTION: Represents the raw data received when a user starts or stops typing in a channel. Includes user, channel, and guild info. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_285 LANGUAGE: python CODE: ``` class RawTypingEvent: """Represents the raw data received when a user starts or stops typing in a channel.""" pass ``` -------------------------------- TITLE: Python: Simplified Late Binding with commands.Author DESCRIPTION: Shows a simplified way to achieve late binding for the `to` parameter using the pre-defined `commands.Author` object, making the `wave` command more concise. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/ext/commands/commands.rst#_snippet_40 LANGUAGE: python CODE: ``` @bot.command() async def wave(ctx, to: discord.User = commands.Author): await ctx.send(f'Hello {to.mention} :wave:') ``` -------------------------------- TITLE: Guild Sticker Format Type DESCRIPTION: Gets the format type of a sticker. This attribute is of type StickerFormatType. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_233 LANGUAGE: Python CODE: ``` format_type The format type of a sticker being changed. See also :attr:`GuildSticker.format` :type: :class:`StickerFormatType` ``` -------------------------------- TITLE: Invite Max Age DESCRIPTION: Gets the maximum age of the invite in seconds. This attribute is of type int. SOURCE: https://github.com/rapptz/discord.py/blob/master/docs/api.rst#_snippet_225 LANGUAGE: Python CODE: ``` max_age The invite's max age in seconds. See also :attr:`Invite.max_age`. :type: :class:`int` ```