### Install Pycord (Direct from GitHub) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst Installs the Pycord library directly from its GitHub repository without cloning. This is useful for getting the latest code directly. ```sh # Linux/macOS python3 -m pip install git+https://github.com/Pycord-Development/pycord # Windows py -3 -m pip install git+https://github.com/Pycord-Development/pycord ``` -------------------------------- ### Install Pycord (Speedup Packages) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst Installs Pycord with additional packages for improved speed. Requires Python 3.9 or higher. ```sh # Linux/macOS python3 -m pip install -U "py-cord[speed]" # Windows py -3 -m pip install -U py-cord[speed] ``` -------------------------------- ### Install Pycord (Development Version) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst Installs the latest development version of Pycord from GitHub. This involves cloning the repository and installing locally, with an option to include voice support. ```sh $ git clone https://github.com/Pycord-Development/pycord $ cd pycord $ python3 -m pip install -U .[voice] ``` -------------------------------- ### Pycord Basic Event Handling Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst A simple Python example showcasing Pycord's event-driven nature. It defines a client that logs in and prints messages to the console when a message is received or when the client is ready. ```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') ``` -------------------------------- ### Install Pycord (Voice Support) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst Installs Pycord with full voice support. Requires Python 3.9 or higher. Ensure necessary system packages like libffi-dev are installed beforehand on Linux. ```sh # Linux/macOS python3 -m pip install -U "py-cord[voice]" # Windows py -3 -m pip install -U py-cord[voice] ``` -------------------------------- ### Create a Basic Discord Bot Extension Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/extensions.rst This Python code defines a simple Discord bot extension with a command and a setup function. The `setup` function adds the `hello` command to the bot when the extension is loaded. This is a fundamental example for creating runnable extensions. ```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) ``` -------------------------------- ### Install Pycord with Speed Support Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Installs Pycord with additional packages for speed optimization. This is achieved by appending '[speed]' to the package name during installation. Examples are provided for Linux/macOS and Windows. ```shell # Linux/macOS python3 -m pip install -U "py-cord[speed]" ``` ```shell # Windows py -3 -m pip install -U py-cord[speed] ``` -------------------------------- ### Install Pycord (Basic) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst Installs the Pycord library without voice support. Requires Python 3.9 or higher. This command is compatible with Linux, macOS, and Windows. ```sh # Linux/macOS python3 -m pip install -U py-cord # Windows py -3 -m pip install -U py-cord ``` -------------------------------- ### Pycord Slash Command Bot Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst A basic Pycord bot implementation using slash commands. It defines a 'hello' command that greets a user and a 'Say Hello' user command. Requires a bot token to run. ```py import discord bot = discord.Bot() @bot.slash_command() async def hello(ctx, name: str = None): name = name or ctx.author.name await ctx.respond(f"Hello {name}!") @bot.user_command(name="Say Hello") async def hi(ctx, user): await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!") bot.run("token") ``` -------------------------------- ### Pycord Traditional Command Bot Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/README.rst An example of a Pycord bot using traditional commands with a prefix. It sets up default intents and includes a simple 'ping' command that replies with 'pong'. Requires a bot token to run. ```py 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") ``` -------------------------------- ### Create Discord Bot Extension with Setup and Teardown Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/extensions.rst This Python code shows an extension with both `setup` and `teardown` functions. The `setup` function is called when the extension is loaded, and the `teardown` function is called when it's unloaded, allowing for initialization and cleanup logic. ```python def setup(bot): print('I am being loaded!') def teardown(bot): print('I am being unloaded!') ``` -------------------------------- ### Install Pycord Stable Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Installs the stable version of Pycord from PyPI. This is the recommended method for most users. The command differs slightly for Windows users. ```shell python3 -m pip install -U py-cord ``` ```shell py -3 -m pip install -U py-cord ``` -------------------------------- ### Basic Console Logging Setup Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/logging.rst Configures the logging module to output messages to the console with INFO level or higher. This is a simple setup for immediate feedback. ```python import logging logging.basicConfig(level=logging.INFO) ``` -------------------------------- ### Install Pycord Pre-release Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Installs the pre-release version of Pycord. This is useful for testing new features before they are officially released. The command is the same for Linux/macOS and Windows, with a slight variation in the python executable name. ```shell python3 -m pip install -U py-cord --pre ``` ```shell py -3 -m pip install -U py-cord --pre ``` -------------------------------- ### Install Pycord with Voice Support Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Installs Pycord with support for voice functionalities. This requires installing the package with '[voice]' appended. Linux users may need to install additional system dependencies like libffi, libnacl, and python3-dev. ```shell python3 -m pip install -U py-cord[voice] ``` -------------------------------- ### Install Debian Dependencies for Voice Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Installs necessary system dependencies on Debian-based Linux systems for Pycord's voice support. These include libffi-dev, libnacl-dev, and python3-dev. ```shell $ apt install libffi-dev libnacl-dev python3-dev ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/installing.rst Demonstrates the process of creating and activating a Python virtual environment. This is a standard practice to isolate project dependencies. Commands are provided for Linux/macOS and Windows. ```shell $ cd your-bot-source $ python3 -m venv bot-env ``` ```shell $ source bot-env/bin/activate ``` ```shell $ bot-env\Scripts\activate.bat ``` ```shell $ pip install -U py-cord ``` -------------------------------- ### Create Minimal Discord Bot (Python) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/quickstart.rst This snippet demonstrates how to create a basic Discord bot using Pycord that responds to a specific message command ('$hello'). It requires the message content privileged intent and shows how to handle the 'on_ready' and 'on_message' events. ```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') ``` -------------------------------- ### Run Python Bot Script (Shell) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/quickstart.rst These commands show how to execute a Python script containing a Pycord bot. The first command is for Windows using the 'py' launcher, and the second is for other systems using 'python3'. ```shell $ py -3 example_bot.py ``` ```shell $ python3 example_bot.py ``` -------------------------------- ### Python: Asynchronous HTTP Requests with aiohttp Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/faq.rst Shows how to perform asynchronous HTTP GET requests using the `aiohttp` library, contrasting it with the blocking `requests` library. ```Python # 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']) ``` -------------------------------- ### Example Pycord Cog with Special Methods and Custom Name Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Provides a comprehensive example of a Pycord cog implementing various special methods for customization, such as cog_unload, bot_check, cog_check, and cog_command_error. It also demonstrates setting a custom name for the cog. ```python class MyCog(commands.Cog, name='Example Cog'): def cog_unload(self): print('cleanup goes here') def bot_check(self, ctx): print('bot check') return True def bot_check_once(self, ctx): print('bot check once') return True async def cog_check(self, ctx): print('cog local check') return await ctx.bot.is_owner(ctx.author) async def cog_command_error(self, ctx, error): print('Error in {0.command.qualified_name}: {1}'.format(ctx, error)) ``` -------------------------------- ### Create Discord Bot with Slash Commands (Python) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/quickstart.rst This snippet illustrates how to create a Discord bot with slash commands using Pycord's Bot class. It demonstrates registering a slash command '/hello' that responds to the user and requires a bot token and optionally guild IDs for command registration. ```python import discord bot = discord.Bot() @bot.event async def on_ready(): print(f"We have logged in as {bot.user}") @bot.slash_command(guild_ids=[your, guild_ids, here]) async def hello(ctx): await ctx.respond("Hello!") bot.run("your token here") ``` -------------------------------- ### Get or Fetch Discord Objects Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/utils.rst Attempts to get an object from the cache, and if not found, fetches it from the API. This ensures you have the most up-to-date information. ```python discord.utils.get_or_fetch(cache, fetch_func, **kwargs) ``` -------------------------------- ### Make HTTP GET Request with aiohttp Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/faq.rst Shows how to make a non-blocking HTTP GET request to a specified URL using the `aiohttp` library. The response is processed as JSON if the request is successful (status code 200). ```Python async with aiohttp.ClientSession() as session: async with session.get('http://aws.random.cat/meow') as r: if r.status == 200: js = await r.json() ``` -------------------------------- ### Create Prefix and Slash Commands with discord.ext.bridge Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/bridge/index.rst This example demonstrates how to use the discord.ext.bridge module to create commands that work as both prefix commands and slash commands. It sets up a bot, defines 'hello', 'bye', and 'sum' commands, and runs the bot. ```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") ``` -------------------------------- ### Python: Greedy Converter Example Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Demonstrates how to use the Greedy converter to accept an arbitrary number of discord.Member arguments in a command. The command joins the names of the slapped members and includes a reason. ```python from discord.ext import commands import discord @bot.command() async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'): slapped = ", ".join(x.name for x in members) await ctx.send(f'{slapped} just got slapped for {reason}') ``` -------------------------------- ### Advanced File Logging Setup Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/logging.rst Sets up logging to write messages to a file named 'discord.log' with UTF-8 encoding and a specific format. This is recommended for verbose logging levels to avoid cluttering the console. ```python import discord import logging logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) ``` -------------------------------- ### Pycord Cog Inter-communication Example Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/cogs.rst This example illustrates how one Cog ('Gambling') can interact with another Cog ('Economy') to share data and functionality. It retrieves the 'Economy' cog using `bot.get_cog('Economy')` and then calls its methods like `withdraw_money` and `deposit_money`. ```python class Economy(commands.Cog): ... async def withdraw_money(self, member, money): # implementation here ... async def deposit_money(self, member, money): # implementation here ... class Gambling(commands.Cog): def __init__(self, bot): self.bot = bot def coinflip(self): return random.randint(0, 1) @commands.command() async def gamble(self, ctx, money: int): """Gambles some money.""" economy = self.bot.get_cog('Economy') if economy is not None: await economy.withdraw_money(ctx.author, money) if self.coinflip() == 1: await economy.deposit_money(ctx.author, money * 1.5) ``` -------------------------------- ### Create and Use a Basic Pycord Cog Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/cogs.rst This example demonstrates how to create a Pycord Cog named 'Greetings'. It includes a listener for member join events and a command to greet a member. Cogs are Python classes that subclass `commands.Cog`, with commands decorated by `@commands.command()` and listeners by `@commands.Cog.listener()`. ```python class Greetings(commands.Cog): def __init__(self, bot): self.bot = bot self._last_member = None @commands.Cog.listener() async def on_member_join(self, member): channel = member.guild.system_channel if channel is not None: await channel.send(f'Welcome {member.mention}.') @commands.command() async def hello(self, ctx, *, member: discord.Member = None): """Says hello""" member = member or ctx.author if self._last_member is None or self._last_member.id != member.id: await ctx.send(f'Hello {member.name}~') else: await ctx.send(f'Hello {member.name}... This feels familiar.') self._last_member = member ``` -------------------------------- ### Customizing Command Context Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Provides an example of subclassing the default Context class to add custom functionality. It shows how to define a custom context and use it with the bot. ```python class MyContext(commands.Context): @property def secret(self): return 'my secret here' ``` ```python # Example usage within on_message (conceptual) # class MyBot(commands.Bot): # # ... # async def on_message(self, message): # ctx = await self.get_context(message, cls=MyContext) # await self.invoke(ctx) ``` -------------------------------- ### Get Invite Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Retrieves an invite from Discord. This method is an alias for Client.fetch_invite. ```python client.get_invite(invite_code) ``` -------------------------------- ### Ban Command with List of Members and Reason Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Provides a complete example of a 'ban' command using a FlagConverter that accepts a list of members, a reason, and the number of days for message deletion. It demonstrates iterating through the parsed members and applying the ban. ```python from discord.ext import commands from typing import List import discord class BanFlags(commands.FlagConverter): members: List[discord.Member] = commands.flag(name='member') reason: str days: int = 1 @commands.command() async def ban(ctx, *, flags: BanFlags): for member in flags.members: await member.ban(reason=flags.reason, delete_message_seconds=flags.days * 60 * 24) members = ', '.join(str(member) for member in flags.members) plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day' await ctx.send(f'Banned {members} for {flags.reason!r} (deleted {plural} worth of messages)') ``` -------------------------------- ### Target Paginator with Prefix Command Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Provides an example of sending a paginator to a different target user when using a prefix command. It also shows how to include a custom message with the target response. ```Python paginator = pages.Paginator(pages=self.get_pages()) await paginator.send(ctx, target=ctx.author, target_message="Paginator sent!") ``` -------------------------------- ### Define a Cog with Commands and Listeners Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/cogs.rst This example demonstrates how to create a Pycord Cog named 'Greetings'. It includes a listener for member join events and a slash command 'hello'. Cogs subclass `discord.Cog` and use decorators like `@discord.Cog.listener()` and `@discord.slash_command()`. ```python class Greetings(discord.Cog): def __init__(self, bot): self.bot = bot self._last_member = None @discord.Cog.listener() async def on_member_join(self, member): channel = member.guild.system_channel if channel is not None: await channel.send(f'Welcome {member.mention}.') @discord.slash_command() async def hello(self, ctx, *, member: discord.Member = None): """Says hello""" member = member or ctx.author if self._last_member is None or self._last_member.id != member.id: await ctx.send(f'Hello {member.name}~') else: await ctx.send(f'Hello {member.name}... This feels familiar.') self._last_member = member ``` -------------------------------- ### Enable Messages and Guilds Intents Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/intents.rst This code example shows how to create Discord intents by specifying only the 'messages' and 'guilds' events. This is suitable for bots that primarily interact with message content and guild information, while ignoring other events. It also includes an optional line to enable 'reactions' events. ```python 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) ``` -------------------------------- ### Python: Greedy with Optional Converter Example Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Shows how to combine Greedy with Optional for more flexible command syntax, allowing an optional integer parameter for delete_seconds before the reason. This enables bulk banning with optional message deletion. ```python import typing from discord.ext import commands import discord @bot.command() async def ban(ctx, members: commands.Greedy[discord.Member], delete_seconds: typing.Optional[int] = 0, *, reason: str): """Bulk bans members with an optional delete_seconds parameter""" await ctx.guild.bulk_ban(*members, delete_message_seconds=delete_seconds, reason=reason) ``` -------------------------------- ### Custom Flag Syntax with Delimiter and Prefix Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Shows how to customize the flag syntax by specifying a delimiter and prefix for the FlagConverter. Examples include POSIX-like '--' prefix and Windows-like '/' prefix with different delimiters. ```python # --hello world syntax class PosixLikeFlags(commands.FlagConverter, delimiter=' ', prefix='--'): hello: str # /make food class WindowsLikeFlags(commands.FlagConverter, prefix='/', delimiter=''): make: str ``` -------------------------------- ### Python: Sending a Message to a Specific Channel Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/faq.rst Provides an example of how to send a message to a specific Discord channel by fetching the channel object using its ID and then calling the `send` method. ```Python channel = client.get_channel(12324234183172) await channel.send('hello') ``` -------------------------------- ### Get UTC Now Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/utils.rst Returns the current time in UTC. This is a standard way to get the current time for consistent logging and scheduling. ```python discord.utils.utcnow() ``` -------------------------------- ### Pycord Paginator with Custom Buttons Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Demonstrates how to create a paginator with custom button labels and a custom page indicator. This example shows how to override default button behavior and appearance. ```Python await paginator.respond(ctx.interaction, ephemeral=False) ``` -------------------------------- ### Pycord Paginator with Page Groups Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Explains how to use page groups to allow users to switch between different sets of pages within a single paginator instance. This example also shows custom button labels and a custom view. ```Python page_buttons = [ pages.PaginatorButton( "first", label="<<-", style=discord.ButtonStyle.green ), pages.PaginatorButton("prev", label="<-", style=discord.ButtonStyle.green), pages.PaginatorButton( "page_indicator", style=discord.ButtonStyle.gray, disabled=True ), pages.PaginatorButton("next", label="->", style=discord.ButtonStyle.green), pages.PaginatorButton("last", label=">>-", style=discord.ButtonStyle.green), ] view = discord.ui.View() view.add_item(discord.ui.Button(label="Test Button, Does Nothing", row=2)) view.add_item( discord.ui.Select( placeholder="Test Select Menu, Does Nothing", options=[ discord.SelectOption( label="Example Option", value="Example Value", description="This menu does nothing!", ) ], ) ) page_groups = [ pages.PageGroup( pages=self.get_pages(), ``` -------------------------------- ### Get Server Voice Client Shortcut with Pycord Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst This snippet shows how to use the Server.voice_client shortcut property to get the voice client associated with a server. ```Python voice_client = server.voice_client ``` -------------------------------- ### Getting Last Message by Author Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/async_iter.rst Shows how to use the 'get' method on an async iterator to retrieve a specific item, such as the last message sent by a user named 'Dave'. ```python msg = await channel.history().get(author__name='Dave') ``` -------------------------------- ### Using Clean Content Converter Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Shows how to use the `commands.clean_content` converter to clean user-provided content before sending it. It also demonstrates how to instantiate the converter with options like `use_nicknames=False` for fine-tuning. ```python import discord from discord.ext import commands bot = commands.Bot(command_prefix='!') @bot.command() async def clean(ctx, *, content: commands.clean_content): await ctx.send(content) @bot.command() async def clean_no_nicknames(ctx, *, content: commands.clean_content(use_nicknames=False)): await ctx.send(content) # Example of running the bot (replace 'YOUR_BOT_TOKEN' with your actual token) # bot.run('YOUR_BOT_TOKEN') ``` -------------------------------- ### Registering Slash Commands with Bot Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/clients.rst Provides an example of registering slash commands for a Bot object using the .slash_command() decorator. Slash commands offer a structured way to interact with bots via Discord's command interface. ```python bot.slash_command(**kwargs) async def my_slash_command(): pass ``` -------------------------------- ### Inter-Cog Communication Example Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/cogs.rst This example illustrates how one Cog ('Gambling') can interact with another Cog ('Economy') to share state and functionality. It retrieves the 'Economy' cog using `self.bot.get_cog('Economy')` and calls its methods like `withdraw_money` and `deposit_money`. ```python class Economy(discord.Cog): ... async def withdraw_money(self, member, money): # implementation here ... async def deposit_money(self, member, money): # implementation here ... class Gambling(discord.Cog): def __init__(self, bot): self.bot = bot def coinflip(self): return random.randint(0, 1) @discord.slash_command() async def gamble(self, ctx, money: int): """Gambles some money.""" economy = self.bot.get_cog('Economy') if economy is not None: await economy.withdraw_money(ctx.author, money) if self.coinflip() == 1: await economy.deposit_money(ctx.author, money * 1.5) ``` -------------------------------- ### Get User Info Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Fetches information about a user. This method is an alias for Client.fetch_user. ```python client.get_user_info(user_id) ``` -------------------------------- ### Define a Simple Command Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Demonstrates how to define a basic command using the @bot.command() decorator. The command takes a context object and a single argument, then sends the argument back to the channel. ```python @bot.command() async def foo(ctx, arg): await ctx.send(arg) ``` -------------------------------- ### Get Message Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Fetches a specific message from a channel. This method is an alias for abc.Messageable.fetch_message. ```python client.get_message(channel, message_id) ``` -------------------------------- ### Global Before/After Invocation Hooks - Python Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Demonstrates how to set up global hooks that execute before and after any command is invoked. These are useful for general logging or cleanup tasks. ```python 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 ``` -------------------------------- ### Using aiohttp ClientSession Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Demonstrates the recommended way to use aiohttp for making HTTP requests by creating a ClientSession. It shows how to manage the session lifecycle, including closing it when no longer needed. ```python async with aiohttp.ClientSession() as sess: async with sess.get('url') as resp: # work with resp ``` -------------------------------- ### Get Reaction Users Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Retrieves users who have reacted to a message. This corresponds to the Reaction.users method. ```python client.get_reaction_users(message, reaction) ``` -------------------------------- ### Get All Emojis Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Retrieves all emojis available to the client. This is equivalent to accessing the client.emojis attribute. ```python client.get_all_emojis() ``` -------------------------------- ### Pycord Member Nickname Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/audit_logs.rst Gets the nickname of a member, which is an optional string. ```Python member.nick ``` -------------------------------- ### Variable Arguments (*args) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Explains how to define a command that accepts an arbitrary number of arguments using the *args syntax. All arguments passed by the user are collected into a tuple. ```python @bot.command() async def test(ctx, *args): arguments = ', '.join(args) await ctx.send(f'{len(args)} arguments: {arguments}') ``` -------------------------------- ### Literal Type Hint for String and Integer Choices in Python Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Demonstrates using typing.Literal to enforce that a command parameter must match one of the specified literal values. This example shows enforcing 'buy' or 'sell' for one parameter and integers 1 or 2 for another. ```python from typing import Literal @bot.command() async def shop(ctx, buy_sell: Literal['buy', 'sell'], amount: Literal[1, 2], *, item: str): await ctx.send(f'{buy_sell.capitalize()}ing {amount} {item}(s)!') ``` -------------------------------- ### Pycord Voice Channel Bitrate Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/audit_logs.rst Gets the bitrate of a VoiceChannel as an integer. ```Python voice_channel.bitrate ``` -------------------------------- ### Create Discord UI Select Menu Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/ui_kit.rst This snippet shows how to create a UI select menu for Discord using the discord.ui.select decorator. This is a shortcut for defining select menu components. ```python import discord @discord.ui.select() def select_callback(interaction: discord.Interaction): pass ``` -------------------------------- ### Get Animated Guild Icon URL Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Supports animated icons in `icon_url_as` and `icon_url` for guilds. ```Python guild.icon_url_as(format='gif') guild.icon_url ``` -------------------------------- ### Create Discord UI Mentionable Select Menu Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/ui_kit.rst This snippet demonstrates creating a mentionable (users or roles) UI select menu for Discord using the discord.ui.mentionable_select decorator. ```python import discord @discord.ui.mentionable_select() def mentionable_select_callback(interaction: discord.Interaction): pass ``` -------------------------------- ### Pycord OnboardingPrompt Model Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/models.rst Represents a prompt within a Discord guild's onboarding flow. This model is read-only and its attributes are defined by slots. ```Python class OnboardingPrompt: pass ``` -------------------------------- ### Get PartialEmoji Creation Timestamp Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Adds the 'created_at' attribute to PartialEmoji for retrieving its creation timestamp. ```Python Add :attr:`PartialEmoji.created_at` (:dpy-issue:`6128`) ``` -------------------------------- ### Get Invites From Channel Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Retrieves invites from a guild channel. This can be done using abc.GuildChannel.invites or Guild.invites. ```python client.invites_from(channel) ``` -------------------------------- ### Basic Paginator Usage in Cog Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Demonstrates the fundamental usage of the Paginator class within a Discord cog, utilizing a list of strings and embeds for pagination. It shows how to initialize the Paginator and respond to a slash command interaction. ```python import asyncio import discord from discord.commands import SlashCommandGroup from discord.ext import commands, pages class PageTest(commands.Cog): def __init__(self, bot): self.bot = bot self.pages = [ "Page 1", [ discord.Embed(title="Page 2, Embed 1"), discord.Embed(title="Page 2, Embed 2"), ], "Page Three", discord.Embed(title="Page Four"), discord.Embed(title="Page Five"), [ discord.Embed(title="Page Six, Embed 1"), discord.Embed(title="Page Seven, Embed 2"), ], ] self.pages[3].set_image( url="https://c.tenor.com/pPKOYQpTO8AAAAAM/monkey-developer.gif" ) self.pages[4].add_field( name="Example Field", value="Example Value", inline=False ) self.pages[4].add_field( name="Another Example Field", value="Another Example Value", inline=False ) self.more_pages = [ "Second Page One", discord.Embed(title="Second Page Two"), discord.Embed(title="Second Page Three"), ] self.even_more_pages = ["11111", "22222", "33333"] def get_pages(self): return self.pages pagetest = SlashCommandGroup("pagetest", "Commands for testing ext.pages") # These examples use a Slash Command Group in a cog for better organization - it's not required for using ext.pages. @pagetest.command(name="default") async def pagetest_default(self, ctx: discord.ApplicationContext): """Demonstrates using the paginator with the default options.""" paginator = pages.Paginator(pages=self.get_pages()) await paginator.respond(ctx.interaction, ephemeral=False) ``` -------------------------------- ### Get Bans Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v1.rst Fetches the list of banned members from a guild. This functionality is accessed via Guild.bans. ```python client.get_bans(guild) ``` -------------------------------- ### Respond with Paginator Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Demonstrates creating and responding with a paginator that displays multiple page groups. It shows how to structure pages and groups, and how to send the paginator to the interaction context. ```Python paginator = pages.Paginator(pages=page_groups, show_menu=True) await paginator.respond(ctx.interaction, ephemeral=False) ``` -------------------------------- ### Pycord Role or Channel Position Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/audit_logs.rst Gets the position of a Role or an abc.GuildChannel as an integer. ```Python role_or_channel.position ``` -------------------------------- ### Upload File from URL with Pycord Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/faq.rst Explains how to upload a file from a URL by using `aiohttp` to download the content and then passing it as an `io.BytesIO` instance to `discord.File`. ```python import io import aiohttp async with aiohttp.ClientSession() as session: async with session.get(my_url) as resp: if resp.status != 200: return await channel.send('Could not download file...') data = io.BytesIO(await resp.read()) await channel.send(file=discord.File(data, 'cool_image.png')) ``` -------------------------------- ### Get Guild Premium Subscribers Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Retrieves a list of all members currently boosting a guild using the `premium_subscribers` attribute. ```Python guild.premium_subscribers ``` -------------------------------- ### Pycord Bot Commands Framework Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/index.rst The Pycord commands extension provides a framework for building Discord bots with a structured command system. It simplifies command creation and management. ```Python ext/commands/index.rst ``` -------------------------------- ### Get Member Premium Since Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Retrieves the date since which a member has been boosting a guild using the `premium_since` attribute. ```Python member.premium_since ``` -------------------------------- ### Get Random Colour with discord.Colour Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Provides a method to generate a random color value using the discord.Colour class. ```Python Add :meth:`Colour.random` to get a random colour (:dpy-issue:`6067`) ``` -------------------------------- ### Paginator with Prefix Command Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/pages/index.rst Demonstrates using the paginator with a traditional prefix-based command. It includes customizing buttons for navigation and displaying a page indicator. ```Python paginator = pages.Paginator(pages=self.get_pages(), use_default_buttons=False) paginator.add_button(pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.green)) paginator.add_button(pages.PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True)) paginator.add_button(pages.PaginatorButton("next", style=discord.ButtonStyle.green)) await paginator.send(ctx) ``` -------------------------------- ### Pycord Role Color Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/audit_logs.rst Gets the color of a role, represented by the Colour type. 'color' is an alias. ```Python role.colour ``` ```Python role.color ``` -------------------------------- ### Keyword-Only Argument (*) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/commands.rst Illustrates the use of a keyword-only argument using the '*' syntax. This captures all remaining input as a single argument, useful for arguments that might contain spaces and do not need quoting. ```python @bot.command() async def test(ctx, *, arg): await ctx.send(arg) ``` -------------------------------- ### Getting Banned Members Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Adds the Client.get_bans method to retrieve a list of banned members from a server. This facilitates moderation tasks. ```Python import discord client = discord.Client() async def get_banned_members_example(guild_id): guild = client.get_guild(guild_id) if guild: banned_users = await guild.bans() for ban_entry in banned_users: print(f"Banned user: {ban_entry.user} (Reason: {ban_entry.reason})") # Example usage: # asyncio.run(get_banned_members_example(123456789012345678)) ``` -------------------------------- ### Creating a Server Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Adds the Client.create_server method, enabling the programmatic creation of new Discord servers. ```Python import discord client = discord.Client() async def create_new_server(): try: # Note: This functionality might require specific permissions or be limited. # The actual implementation details and requirements may vary. # new_server = await client.create_server(name='My New Server') # print(f"Created new server: {new_server.name}") print("Server creation functionality is noted, but requires specific API access.") except Exception as e: print(f"Error creating server: {e}") # Example usage: # asyncio.run(create_new_server()) ``` -------------------------------- ### Get User Information with Pycord Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst This snippet demonstrates how to retrieve a user's information using their ID with the Client.get_user_info method. ```Python user_info = await client.get_user_info(user_id) ``` -------------------------------- ### Get Users Who Reacted to a Message Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Retrieves a list of users who have reacted to a specific message. This feature is useful for tracking engagement. ```python await client.get_reaction_users(message, emoji) ``` -------------------------------- ### Python MinimalHelpCommand Class Definition Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/ext/commands/api.rst Defines the MinimalHelpCommand class, inheriting from HelpCommand, for Pycord's prefixed command extension. It offers a more concise help command output. ```Python class discord.ext.commands.MinimalHelpCommand: pass ``` -------------------------------- ### Get Guild Premium Subscription Count Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Queries the number of members currently boosting a guild using the `premium_subscription_count` attribute. ```Python guild.premium_subscription_count ``` -------------------------------- ### Get Cooldown Retry After (Pycord Commands) Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Adds Command.get_cooldown_retry_after to retrieve the remaining time before a command's cooldown expires. ```Python from discord.ext import commands # Example usage (conceptual): # @commands.command() # @commands.cooldown(1, 60, commands.BucketType.user) # async def my_command(ctx): # retry_after = ctx.command.get_cooldown_retry_after(ctx) # if retry_after: # await ctx.send(f"Please wait {retry_after:.2f} seconds before trying again.") ``` -------------------------------- ### Create Discord UI User Select Menu Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/ui_kit.rst This snippet illustrates creating a user selection UI component for Discord using the discord.ui.user_select decorator. This allows users to select other users from a list. ```python import discord @discord.ui.user_select() def user_select_callback(interaction: discord.Interaction): pass ``` -------------------------------- ### Get Emoji URL with Emoji.url_as Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Adds the 'url_as' method to the Emoji class for retrieving emoji URLs in different formats. ```Python Add :meth:`Emoji.url_as` (:dpy-issue:`6162`) ``` -------------------------------- ### Create Discord UI Channel Select Menu Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/ui_kit.rst This snippet shows how to create a channel selection UI component for Discord using the discord.ui.channel_select decorator. This allows users to select channels. ```python import discord @discord.ui.channel_select() def channel_select_callback(interaction: discord.Interaction): pass ``` -------------------------------- ### Get Guild System Channel Flags Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Queries the settings for a guild's system channel, including a new `SystemChannelFlags` type. ```Python guild.system_channel_flags ``` -------------------------------- ### Get Guild Boost Limits Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Retrieves new guild limits for emojis, bitrate, and file size based on boosting status. ```Python guild.emoji_limit guild.bitrate_limit guild.filesize_limit ``` -------------------------------- ### Create Discord UI Role Select Menu Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/ui_kit.rst This snippet shows how to create a role selection UI component for Discord using the discord.ui.role_select decorator. This enables users to select roles from a list. ```python import discord @discord.ui.role_select() def role_select_callback(interaction: discord.Interaction): pass ``` -------------------------------- ### Pycord WelcomeScreen Model Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/api/models.rst Represents the welcome screen configuration for a Discord guild. This model is read-only and its attributes are defined by slots. ```Python class WelcomeScreen: pass ``` -------------------------------- ### Get Guild Nitro Boost Level Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Retrieves the guild's current nitro boost level using the `premium_tier` attribute. ```Python guild.premium_tier ``` -------------------------------- ### Fix __path__ for editable extensions Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Corrects the `__path__` attribute to properly support editable extensions, facilitating easier development and installation of extensions. ```Python import sys sys.path.append('path/to/extension') __path__ = sys.path ``` -------------------------------- ### Sticker Item Fetching Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/migrating_to_v2.rst StickerItem now supports fetching Sticker objects via the fetch method. Attributes like description and pack_id are not directly available on StickerItem. ```python sticker_item: discord.StickerItem sticker: discord.Sticker = await sticker_item.fetch() ``` -------------------------------- ### Getting Cleaned Message Content Source: https://github.com/satcomx00-x00/pycord-2.7.0/blob/master/docs/old_changelog.rst Introduces the Message.clean_content attribute, which returns a version of the message content with user and channel mentions replaced by their names. ```Python import discord client = discord.Client() @client.event async def on_message(message): if message.author == client.user: return # Example: If a message contains '@Someone' or '#channel' # message.clean_content will show 'Someone' or 'channel' print(f"Cleaned content: {message.clean_content}") ```