Skip to content

Commit

Permalink
Update repository examples (#1389)
Browse files Browse the repository at this point in the history
* Initial example updates

* More typehinting + comment changes

* Cleanup view examples + touchup previous examples

* Update custom_context.py

* TicTacToe example + import syntax consistency

* Prefixes + debug_guilds

* Use new embed/modal parameters + trailing commas

* Paginator + comment updates/additions

* Update slash_cog_groups.py

* Update bridge_commands.py

* Update slash_options.py

Co-authored-by: Lala Sabathil <lala@pycord.dev>
Co-authored-by: Dorukyum <53639936+Dorukyum@users.noreply.github.com>
  • Loading branch information
3 people authored Jun 13, 2022
1 parent a2dd302 commit e441641
Show file tree
Hide file tree
Showing 37 changed files with 683 additions and 521 deletions.
19 changes: 13 additions & 6 deletions examples/app_commands/context_menus.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
# This example requires the 'members' privileged intent to use the Member converter.

import discord

bot = discord.Bot()
intents = discord.Intents.default()
intents.members = True

bot = discord.Bot(debug_guilds=[...], intents=intents)
# Remove debug_guilds and set guild_ids in the slash command decorators
# to restrict specific commands to the supplied guild IDs.


@bot.user_command(guild_ids=[...]) # create a user command for the supplied guilds
async def mention(ctx, member: discord.Member): # user commands return the member
@bot.user_command() # Create a global user command
async def mention(ctx: discord.ApplicationContext, member: discord.Member): # User commands give a member param
await ctx.respond(f"{ctx.author.name} just mentioned {member.mention}!")


# user commands and message commands can have spaces in their names
@bot.message_command(name="Show ID") # creates a global message command
async def show_id(ctx, message: discord.Message): # message commands return the message
# User commands and message commands can have spaces in their names
@bot.message_command(name="Show ID") # Creates a global message command
async def show_id(ctx: discord.ApplicationContext, message: discord.Message): # Message commands give a message param
await ctx.respond(f"{ctx.author.name}, here's the message id: {message.id}!")


Expand Down
77 changes: 39 additions & 38 deletions examples/app_commands/info.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,46 @@
import discord
from discord.ext import commands
# This example requires the 'members' privileged intent to use the Member converter.

# imports
import discord

intents = discord.Intents(
guilds=True,
members=True,
messages=True,
)
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(
command_prefix="/",
description="An example to showcase how to extract info about users",
bot = discord.Bot(
debug_guilds=[...],
description="An example to showcase how to extract info about users.",
intents=intents,
)


@bot.slash_command(name="userinfo", description="gets the info of a user")
async def info(ctx, user: discord.Member = None):
user = user or ctx.author # if no user is provided it'll use the the author of the message
e = discord.Embed()
e.set_author(name=user.name)
e.add_field(name="ID", value=user.id, inline=False) # user ID
e.add_field(
name="Joined",
value=discord.utils.format_dt(user.joined_at, "F"),
inline=False,
) # When the user joined the server
e.add_field(
name="Created",
value=discord.utils.format_dt(user.created_at, "F"),
inline=False,
) # When the user's account was created
colour = user.colour
if colour.value: # if user has a role with a color
e.colour = colour

if isinstance(user, discord.User): # checks if the user in the server
e.set_footer(text="This member is not in this server.")

await ctx.respond(embed=e) # sends the embed


bot.run("your token")
@bot.slash_command(name="userinfo", description="Gets info about a user.")
async def info(ctx: discord.ApplicationContext, user: discord.Member = None):
user = user or ctx.author # If no user is provided it'll use the author of the message
embed = discord.Embed(
fields=[
discord.EmbedField(name="ID", value=str(user.id), inline=False), # User ID
discord.EmbedField(
name="Created",
value=discord.utils.format_dt(user.created_at, "F"),
inline=False,
), # When the user's account was created
],
)
embed.set_author(name=user.name)
embed.set_thumbnail(url=user.display_avatar.url)

if user.colour.value: # If user has a role with a color
embed.colour = user.colour

if isinstance(user, discord.User): # Checks if the user in the server
embed.set_footer(text="This user is not in this server.")
else: # We end up here if the user is a discord.Member object
embed.add_field(
name="Joined",
value=discord.utils.format_dt(user.joined_at, "F"),
inline=False,
) # When the user joined the server

await ctx.respond(embeds=[embed]) # Sends the embed


bot.run("TOKEN")
46 changes: 34 additions & 12 deletions examples/app_commands/slash_autocomplete.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import discord
from discord.commands import option

bot = discord.Bot()
bot = discord.Bot(debug_guilds=[...])

COLORS = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

Expand Down Expand Up @@ -86,14 +86,19 @@
"yellowgreen",
]

BASIC_ALLOWED = [...] # this would normally be a list of discord user IDs for the purpose of this example
BASIC_ALLOWED = [...] # This would normally be a list of discord user IDs for the purpose of this example


async def color_searcher(ctx: discord.AutocompleteContext):
"""Returns a list of matching colors from the LOTS_OF_COLORS list
In this example, we've added logic to only display any results in the returned list if the user's ID exists in the BASIC_ALLOWED list.
"""
Returns a list of matching colors from the LOTS_OF_COLORS list.
In this example, we've added logic to only display any results in the
returned list if the user's ID exists in the BASIC_ALLOWED list.
This is to demonstrate passing a callback in the discord.utils.basic_autocomplete function.
"""

return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED]


Expand All @@ -116,7 +121,7 @@ async def get_animals(ctx: discord.AutocompleteContext):
elif picked_color == "blue":
return ["blue jay", "blue whale"]
elif picked_color == "indigo":
return ["eastern indigo snake"] # needs to return an iterable even if only one item
return ["eastern indigo snake"] # Needs to return an iterable even if only one item
elif picked_color == "violet":
return ["purple emperor butterfly", "orchid dottyback"]
else:
Expand All @@ -131,9 +136,17 @@ async def autocomplete_example(
color: str,
animal: str,
):
"""Demonstrates using ctx.options to create options that are dependent on the values of other options.
For the `color` option, a callback is passed, where additional logic can be added to determine which values are returned.
For the `animal` option, the callback uses the input from the color option to return an iterable of animals"""
"""
Demonstrates using ctx.options to create options
that are dependent on the values of other options.
For the `color` option, a callback is passed, where additional
logic can be added to determine which values are returned.
For the `animal` option, the callback uses the input
from the color option to return an iterable of animals
"""

await ctx.respond(f"You picked {color} for the color, which allowed you to choose {animal} for the animal.")


Expand All @@ -155,11 +168,20 @@ async def autocomplete_basic_example(
color: str,
animal: str,
):
"""This demonstrates using the discord.utils.basic_autocomplete helper function.
For the `color` option, a callback is passed, where additional logic can be added to determine which values are returned.
"""
This demonstrates using the discord.utils.basic_autocomplete helper function.
For the `color` option, a callback is passed, where additional
logic can be added to determine which values are returned.
For the `animal` option, a static iterable is passed.
While a small amount of values for `animal` are used in this example, iterables of any length can be passed to discord.utils.basic_autocomplete
Note that the basic_autocomplete function itself will still only return a maximum of 25 items."""
While a small amount of values for `animal` are used in this example,
iterables of any length can be passed to discord.utils.basic_autocomplete
Note that the basic_autocomplete function itself will still only return a maximum of 25 items.
"""

await ctx.respond(f"You picked {color} as your color, and {animal} as your animal!")


Expand Down
30 changes: 18 additions & 12 deletions examples/app_commands/slash_basic.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
# This example requires the 'members' privileged intent to use the Member converter.

import discord

bot = discord.Bot()
intents = discord.Intents.default()
intents.members = True

bot = discord.Bot(intents=intents)
# The debug guilds parameter can be used to restrict slash command registration to only the supplied guild IDs.
# This is done like so: discord.Bot(debug_guilds=[...])
# Without this, all commands are made global unless they have a guild_ids parameter in the command decorator.

# Note: If you want you can use commands.Bot instead of discord.Bot
# Use discord.Bot if you don't want prefixed message commands
# Note: If you want you can use commands.Bot instead of discord.Bot.
# Use discord.Bot if you don't want prefixed message commands.

# With discord.Bot you can use @bot.command as an alias
# of @bot.slash_command but this is overridden by commands.Bot
# of @bot.slash_command but this is overridden by commands.Bot.


@bot.slash_command(guild_ids=[...]) # create a slash command for the supplied guilds
async def hello(ctx):
"""Say hello to the bot""" # the command description can be supplied as the docstring
@bot.slash_command(guild_ids=[...]) # Create a slash command
async def hello(ctx: discord.ApplicationContext):
"""Say hello to the bot""" # The command description can be supplied as the docstring
await ctx.respond(f"Hello {ctx.author}!")
# Please note that you MUST respond with ctx.respond(), ctx.defer(), or any other
# interaction response within 3 seconds in your slash command code, otherwise the
# interaction will fail.


@bot.slash_command(
name="hi"
) # Not passing in guild_ids creates a global slash command (might take an hour to register)
async def global_command(ctx, num: int): # Takes one integer parameter
@bot.slash_command(name="hi")
async def global_command(ctx: discord.ApplicationContext, num: int): # Takes one integer parameter
await ctx.respond(f"This is a global command, {num}!")


@bot.slash_command(guild_ids=[...])
async def joined(ctx, member: discord.Member = None): # Passing a default value makes the argument optional
async def joined(ctx: discord.ApplicationContext, member: discord.Member = None):
# Setting a default value for the member parameter makes it optional ^
user = member or ctx.author
await ctx.respond(f"{user.name} joined at {discord.utils.format_dt(user.joined_at)}")

Expand Down
20 changes: 13 additions & 7 deletions examples/app_commands/slash_cog.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
from discord.commands import ( # Importing the decorator that makes slash commands.
slash_command,
)
# This example demonstrates a standalone cog file with the bot instance in a separate file.

import discord
from discord.ext import commands


class Example(commands.Cog):
def __init__(self, bot):
self.bot = bot

@slash_command(guild_ids=[...]) # Create a slash command for the supplied guilds.
async def hello(self, ctx):
@commands.slash_command(guild_ids=[...]) # Create a slash command for the supplied guilds.
async def hello(self, ctx: discord.ApplicationContext):
await ctx.respond("Hi, this is a slash command from a cog!")

@slash_command() # Not passing in guild_ids creates a global slash command (might take an hour to register).
async def hi(self, ctx):
@commands.slash_command() # Not passing in guild_ids creates a global slash command.
async def hi(self, ctx: discord.ApplicationContext):
await ctx.respond("Hi, this is a global slash command from a cog!")


def setup(bot):
bot.add_cog(Example(bot))


# The basic bot instance in a separate file should look something like this:
# bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"))
# bot.load_extension("slash_cog")
# bot.run("TOKEN")
32 changes: 22 additions & 10 deletions examples/app_commands/slash_cog_groups.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
# This example requires the 'members' privileged intent to use the Member converter.

import discord
from discord.commands import CommandPermission, SlashCommandGroup
from discord.commands import SlashCommandGroup
from discord.ext import commands

bot = discord.Bot(debug_guilds=[...], owner_id=...) # main file
intents = discord.Intents.default()
intents.members = True

bot = discord.Bot(debug_guilds=[...], intents=intents, owner_id=...) # Main file


class Example(commands.Cog):
def __init__(self, bot):
self.bot = bot
def __init__(self, bot_: discord.Bot):
self.bot = bot_

greetings = SlashCommandGroup("greetings", "Various greeting from cogs!")

Expand All @@ -16,21 +21,28 @@ def __init__(self, bot):
secret_greetings = SlashCommandGroup(
"secret_greetings",
"Secret greetings",
permissions=[CommandPermission("owner", 2, True)], # Ensures the owner_id user can access this, and no one else
checks=[commands.is_owner().predicate], # Ensures the owner_id user can access this group, and no one else
)

@greetings.command()
async def hello(self, ctx):
async def hello(self, ctx: discord.ApplicationContext):
await ctx.respond("Hello, this is a slash subcommand from a cog!")

@international_greetings.command()
async def aloha(self, ctx):
async def aloha(self, ctx: discord.ApplicationContext):
await ctx.respond("Aloha, a Hawaiian greeting")

@secret_greetings.command()
async def secret_handshake(self, ctx, member: discord.Member):
async def secret_handshake(self, ctx: discord.ApplicationContext, member: discord.Member):
await ctx.respond(f"{member.mention} secret handshakes you")

@commands.Cog.listener()
async def on_application_command_error(self, ctx: discord.ApplicationContext, error: discord.DiscordException):
if isinstance(error, commands.NotOwner):
await ctx.respond("You can't use that command!")
else:
raise error # Raise other errors so they aren't ignored


bot.add_cog(Example(bot)) # put in a setup function for cog files
bot.run("TOKEN") # main file
bot.add_cog(Example(bot)) # Put in a setup function for cog files
bot.run("TOKEN") # Main file
27 changes: 9 additions & 18 deletions examples/app_commands/slash_groups.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,22 @@
import discord

bot = discord.Bot()
bot = discord.Bot(debug_guilds=[...])

# If you use commands.Bot, @bot.slash_command should be used for
# slash commands. You can use @bot.slash_command with discord.Bot as well
# slash commands. You can use @bot.slash_command with discord.Bot as well.

math = bot.create_group("math", "Commands related to mathematics.") # create a slash command group
math = bot.create_group("math", "Commands related to mathematics.") # Create a slash command group

# Another way, creating the class manually:

@math.command(guild_ids=[...]) # create a slash command
async def add(ctx, num1: int, num2: int):
"""Get the sum of 2 integers."""
await ctx.respond(f"The sum of these numbers is **{num1+num2}**")


# another way, creating the class manually

from discord.commands import SlashCommandGroup
math = discord.SlashCommandGroup("math", "Commands related to mathematics.")

math = SlashCommandGroup("math", "Commands related to mathematics.")


@math.command(guild_ids=[...])
async def add(ctx, num1: int, num2: int):
...
@math.command() # Create a slash command under the math group
async def add(ctx: discord.ApplicationContext, num1: int, num2: int):
"""Get the sum of 2 integers."""
await ctx.respond(f"The sum of these numbers is **{num1+num2}**")


bot.add_application_command(math)

bot.run("TOKEN")
Loading

0 comments on commit e441641

Please sign in to comment.