Skip to content

Commit e441641

Browse files
baronkobamaLulalabyDorukyum
authored
Update repository examples (#1389)
* 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>
1 parent a2dd302 commit e441641

37 files changed

+683
-521
lines changed

examples/app_commands/context_menus.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
1+
# This example requires the 'members' privileged intent to use the Member converter.
2+
13
import discord
24

3-
bot = discord.Bot()
5+
intents = discord.Intents.default()
6+
intents.members = True
7+
8+
bot = discord.Bot(debug_guilds=[...], intents=intents)
9+
# Remove debug_guilds and set guild_ids in the slash command decorators
10+
# to restrict specific commands to the supplied guild IDs.
411

512

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

1017

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

1623

examples/app_commands/info.py

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,46 @@
1-
import discord
2-
from discord.ext import commands
1+
# This example requires the 'members' privileged intent to use the Member converter.
32

4-
# imports
3+
import discord
54

6-
intents = discord.Intents(
7-
guilds=True,
8-
members=True,
9-
messages=True,
10-
)
5+
intents = discord.Intents.default()
6+
intents.members = True
117

12-
bot = commands.Bot(
13-
command_prefix="/",
14-
description="An example to showcase how to extract info about users",
8+
bot = discord.Bot(
9+
debug_guilds=[...],
10+
description="An example to showcase how to extract info about users.",
1511
intents=intents,
1612
)
1713

1814

19-
@bot.slash_command(name="userinfo", description="gets the info of a user")
20-
async def info(ctx, user: discord.Member = None):
21-
user = user or ctx.author # if no user is provided it'll use the the author of the message
22-
e = discord.Embed()
23-
e.set_author(name=user.name)
24-
e.add_field(name="ID", value=user.id, inline=False) # user ID
25-
e.add_field(
26-
name="Joined",
27-
value=discord.utils.format_dt(user.joined_at, "F"),
28-
inline=False,
29-
) # When the user joined the server
30-
e.add_field(
31-
name="Created",
32-
value=discord.utils.format_dt(user.created_at, "F"),
33-
inline=False,
34-
) # When the user's account was created
35-
colour = user.colour
36-
if colour.value: # if user has a role with a color
37-
e.colour = colour
38-
39-
if isinstance(user, discord.User): # checks if the user in the server
40-
e.set_footer(text="This member is not in this server.")
41-
42-
await ctx.respond(embed=e) # sends the embed
43-
44-
45-
bot.run("your token")
15+
@bot.slash_command(name="userinfo", description="Gets info about a user.")
16+
async def info(ctx: discord.ApplicationContext, user: discord.Member = None):
17+
user = user or ctx.author # If no user is provided it'll use the author of the message
18+
embed = discord.Embed(
19+
fields=[
20+
discord.EmbedField(name="ID", value=str(user.id), inline=False), # User ID
21+
discord.EmbedField(
22+
name="Created",
23+
value=discord.utils.format_dt(user.created_at, "F"),
24+
inline=False,
25+
), # When the user's account was created
26+
],
27+
)
28+
embed.set_author(name=user.name)
29+
embed.set_thumbnail(url=user.display_avatar.url)
30+
31+
if user.colour.value: # If user has a role with a color
32+
embed.colour = user.colour
33+
34+
if isinstance(user, discord.User): # Checks if the user in the server
35+
embed.set_footer(text="This user is not in this server.")
36+
else: # We end up here if the user is a discord.Member object
37+
embed.add_field(
38+
name="Joined",
39+
value=discord.utils.format_dt(user.joined_at, "F"),
40+
inline=False,
41+
) # When the user joined the server
42+
43+
await ctx.respond(embeds=[embed]) # Sends the embed
44+
45+
46+
bot.run("TOKEN")

examples/app_commands/slash_autocomplete.py

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import discord
22
from discord.commands import option
33

4-
bot = discord.Bot()
4+
bot = discord.Bot(debug_guilds=[...])
55

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

@@ -86,14 +86,19 @@
8686
"yellowgreen",
8787
]
8888

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

9191

9292
async def color_searcher(ctx: discord.AutocompleteContext):
93-
"""Returns a list of matching colors from the LOTS_OF_COLORS list
94-
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.
93+
"""
94+
Returns a list of matching colors from the LOTS_OF_COLORS list.
95+
96+
In this example, we've added logic to only display any results in the
97+
returned list if the user's ID exists in the BASIC_ALLOWED list.
98+
9599
This is to demonstrate passing a callback in the discord.utils.basic_autocomplete function.
96100
"""
101+
97102
return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED]
98103

99104

@@ -116,7 +121,7 @@ async def get_animals(ctx: discord.AutocompleteContext):
116121
elif picked_color == "blue":
117122
return ["blue jay", "blue whale"]
118123
elif picked_color == "indigo":
119-
return ["eastern indigo snake"] # needs to return an iterable even if only one item
124+
return ["eastern indigo snake"] # Needs to return an iterable even if only one item
120125
elif picked_color == "violet":
121126
return ["purple emperor butterfly", "orchid dottyback"]
122127
else:
@@ -131,9 +136,17 @@ async def autocomplete_example(
131136
color: str,
132137
animal: str,
133138
):
134-
"""Demonstrates using ctx.options to create options that are dependent on the values of other options.
135-
For the `color` option, a callback is passed, where additional logic can be added to determine which values are returned.
136-
For the `animal` option, the callback uses the input from the color option to return an iterable of animals"""
139+
"""
140+
Demonstrates using ctx.options to create options
141+
that are dependent on the values of other options.
142+
143+
For the `color` option, a callback is passed, where additional
144+
logic can be added to determine which values are returned.
145+
146+
For the `animal` option, the callback uses the input
147+
from the color option to return an iterable of animals
148+
"""
149+
137150
await ctx.respond(f"You picked {color} for the color, which allowed you to choose {animal} for the animal.")
138151

139152

@@ -155,11 +168,20 @@ async def autocomplete_basic_example(
155168
color: str,
156169
animal: str,
157170
):
158-
"""This demonstrates using the discord.utils.basic_autocomplete helper function.
159-
For the `color` option, a callback is passed, where additional logic can be added to determine which values are returned.
171+
"""
172+
This demonstrates using the discord.utils.basic_autocomplete helper function.
173+
174+
For the `color` option, a callback is passed, where additional
175+
logic can be added to determine which values are returned.
176+
160177
For the `animal` option, a static iterable is passed.
161-
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
162-
Note that the basic_autocomplete function itself will still only return a maximum of 25 items."""
178+
179+
While a small amount of values for `animal` are used in this example,
180+
iterables of any length can be passed to discord.utils.basic_autocomplete
181+
182+
Note that the basic_autocomplete function itself will still only return a maximum of 25 items.
183+
"""
184+
163185
await ctx.respond(f"You picked {color} as your color, and {animal} as your animal!")
164186

165187

examples/app_commands/slash_basic.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,39 @@
1+
# This example requires the 'members' privileged intent to use the Member converter.
2+
13
import discord
24

3-
bot = discord.Bot()
5+
intents = discord.Intents.default()
6+
intents.members = True
47

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

6-
# Note: If you want you can use commands.Bot instead of discord.Bot
7-
# Use discord.Bot if you don't want prefixed message commands
13+
# Note: If you want you can use commands.Bot instead of discord.Bot.
14+
# Use discord.Bot if you don't want prefixed message commands.
815

916
# With discord.Bot you can use @bot.command as an alias
10-
# of @bot.slash_command but this is overridden by commands.Bot
17+
# of @bot.slash_command but this is overridden by commands.Bot.
1118

1219

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

2128

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

2833

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

examples/app_commands/slash_cog.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
1-
from discord.commands import ( # Importing the decorator that makes slash commands.
2-
slash_command,
3-
)
1+
# This example demonstrates a standalone cog file with the bot instance in a separate file.
2+
3+
import discord
44
from discord.ext import commands
55

66

77
class Example(commands.Cog):
88
def __init__(self, bot):
99
self.bot = bot
1010

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

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

1919

2020
def setup(bot):
2121
bot.add_cog(Example(bot))
22+
23+
24+
# The basic bot instance in a separate file should look something like this:
25+
# bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"))
26+
# bot.load_extension("slash_cog")
27+
# bot.run("TOKEN")
Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1+
# This example requires the 'members' privileged intent to use the Member converter.
2+
13
import discord
2-
from discord.commands import CommandPermission, SlashCommandGroup
4+
from discord.commands import SlashCommandGroup
35
from discord.ext import commands
46

5-
bot = discord.Bot(debug_guilds=[...], owner_id=...) # main file
7+
intents = discord.Intents.default()
8+
intents.members = True
9+
10+
bot = discord.Bot(debug_guilds=[...], intents=intents, owner_id=...) # Main file
611

712

813
class Example(commands.Cog):
9-
def __init__(self, bot):
10-
self.bot = bot
14+
def __init__(self, bot_: discord.Bot):
15+
self.bot = bot_
1116

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

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

2227
@greetings.command()
23-
async def hello(self, ctx):
28+
async def hello(self, ctx: discord.ApplicationContext):
2429
await ctx.respond("Hello, this is a slash subcommand from a cog!")
2530

2631
@international_greetings.command()
27-
async def aloha(self, ctx):
32+
async def aloha(self, ctx: discord.ApplicationContext):
2833
await ctx.respond("Aloha, a Hawaiian greeting")
2934

3035
@secret_greetings.command()
31-
async def secret_handshake(self, ctx, member: discord.Member):
36+
async def secret_handshake(self, ctx: discord.ApplicationContext, member: discord.Member):
3237
await ctx.respond(f"{member.mention} secret handshakes you")
3338

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

35-
bot.add_cog(Example(bot)) # put in a setup function for cog files
36-
bot.run("TOKEN") # main file
47+
bot.add_cog(Example(bot)) # Put in a setup function for cog files
48+
bot.run("TOKEN") # Main file

examples/app_commands/slash_groups.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,22 @@
11
import discord
22

3-
bot = discord.Bot()
3+
bot = discord.Bot(debug_guilds=[...])
44

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

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

10+
# Another way, creating the class manually:
1011

11-
@math.command(guild_ids=[...]) # create a slash command
12-
async def add(ctx, num1: int, num2: int):
13-
"""Get the sum of 2 integers."""
14-
await ctx.respond(f"The sum of these numbers is **{num1+num2}**")
15-
16-
17-
# another way, creating the class manually
18-
19-
from discord.commands import SlashCommandGroup
12+
math = discord.SlashCommandGroup("math", "Commands related to mathematics.")
2013

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

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

2820

2921
bot.add_application_command(math)
30-
3122
bot.run("TOKEN")

0 commit comments

Comments
 (0)