Skip to content

Commit 7e4dcfd

Browse files
committed
Merge branch 'slash' of https://github.com/Pycord-Development/pycord into slash
2 parents fd40793 + e8ba894 commit 7e4dcfd

23 files changed

+347
-213
lines changed

examples/app_commands/context_menus.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@
22

33
bot = discord.Bot()
44

5+
56
@bot.user_command(guild_ids=[...]) # create a user command for the supplied guilds
6-
async def mention(ctx, member: discord.Member): # user commands return the member
7+
async def mention(ctx, member: discord.Member): # user commands return the member
78
await ctx.respond(f"{ctx.author.name} just mentioned {member.mention}!")
89

10+
911
# user commands and message commands can have spaces in their names
10-
@bot.message_command(name='Show ID') # creates a global message command
11-
async def show_id(ctx, message: discord.Message): # message commands return the message
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
1214
await ctx.respond(f"{ctx.author.name}, here's the message id: {message.id}!")
1315

16+
1417
bot.run("TOKEN")

examples/app_commands/slash_basic.py

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

3-
bot = discord.Bot()
3+
bot = discord.Bot()
44

5-
# If you use commands.Bot, @bot.slash_command should be used for
5+
# If you use commands.Bot, @bot.slash_command should be used for
66
# slash commands. You can use @bot.slash_command with discord.Bot aswell
77

88

99
@bot.command(guild_ids=[...]) # create a slash command for the supplied guilds
1010
async def hello(ctx):
11-
"""Say hello to the bot""" # the command description can be supplied as the docstring
11+
"""Say hello to the bot""" # the command description can be supplied as the docstring
1212
await ctx.send(f"Hello {ctx.author}!")
1313

14-
@bot.command(name='hi') # Not passing in guild_ids creates a global slash command (might take an hour to register)
15-
async def global_command(ctx, num: int): # Takes one integer parameter
14+
15+
@bot.command(
16+
name="hi"
17+
) # Not passing in guild_ids creates a global slash command (might take an hour to register)
18+
async def global_command(ctx, num: int): # Takes one integer parameter
1619
await ctx.send(f"This is a global command, {num}!")
1720

21+
1822
@bot.command(guild_ids=[...])
19-
async def joined(ctx, member: discord.Member = None): # Passing a default value makes the argument optional
20-
user = member or ctx.author
21-
await ctx.send(f'{user.name} joined at {discord.utils.format_dt(user.joined_at)}')
23+
async def joined(
24+
ctx, member: discord.Member = None
25+
): # Passing a default value makes the argument optional
26+
user = member or ctx.author
27+
await ctx.send(f"{user.name} joined at {discord.utils.format_dt(user.joined_at)}")
28+
2229

30+
# To learn how to add descriptions, choices to options check slash_options.py
2331
bot.run("TOKEN")
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import discord
2+
from discord.app import Option
3+
4+
bot = discord.Bot()
5+
6+
# If you use commands.Bot, @bot.slash_command should be used for
7+
# slash commands. You can use @bot.slash_command with discord.Bot aswell
8+
9+
10+
@bot.command(guild_ids=[...])
11+
async def hello(
12+
ctx,
13+
name: Option(str, "Enter your name"),
14+
gender: Option(str, "Choose your gender", choices=["Male", "Female", "Other"]),
15+
age: Option(int, "Enter your age", required=False, default=18),
16+
):
17+
await ctx.send(f"Hello {name}")

examples/background_task.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import discord
44

5+
56
class MyClient(discord.Client):
67
def __init__(self, *args, **kwargs):
78
super().__init__(*args, **kwargs)
@@ -13,18 +14,19 @@ def __init__(self, *args, **kwargs):
1314
self.my_background_task.start()
1415

1516
async def on_ready(self):
16-
print(f'Logged in as {self.user} (ID: {self.user.id})')
17-
print('------')
17+
print(f"Logged in as {self.user} (ID: {self.user.id})")
18+
print("------")
1819

19-
@tasks.loop(seconds=60) # task runs every 60 seconds
20+
@tasks.loop(seconds=60) # task runs every 60 seconds
2021
async def my_background_task(self):
21-
channel = self.get_channel(1234567) # channel ID goes here
22+
channel = self.get_channel(1234567) # channel ID goes here
2223
self.counter += 1
2324
await channel.send(self.counter)
2425

2526
@my_background_task.before_loop
2627
async def before_my_task(self):
27-
await self.wait_until_ready() # wait until the bot logs in
28+
await self.wait_until_ready() # wait until the bot logs in
29+
2830

2931
client = MyClient()
30-
client.run('token')
32+
client.run("token")

examples/background_task_asyncio.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import discord
22
import asyncio
33

4+
45
class MyClient(discord.Client):
56
def __init__(self, *args, **kwargs):
67
super().__init__(*args, **kwargs)
@@ -9,18 +10,18 @@ def __init__(self, *args, **kwargs):
910
self.bg_task = self.loop.create_task(self.my_background_task())
1011

1112
async def on_ready(self):
12-
print(f'Logged in as {self.user} (ID: {self.user.id})')
13-
print('------')
13+
print(f"Logged in as {self.user} (ID: {self.user.id})")
14+
print("------")
1415

1516
async def my_background_task(self):
1617
await self.wait_until_ready()
1718
counter = 0
18-
channel = self.get_channel(1234567) # channel ID goes here
19+
channel = self.get_channel(1234567) # channel ID goes here
1920
while not self.is_closed():
2021
counter += 1
2122
await channel.send(counter)
22-
await asyncio.sleep(60) # task runs every 60 seconds
23+
await asyncio.sleep(60) # task runs every 60 seconds
2324

2425

2526
client = MyClient()
26-
client.run('token')
27+
client.run("token")

examples/basic_bot.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,53 +4,60 @@
44
from discord.ext import commands
55
import random
66

7-
description = '''An example bot to showcase the discord.ext.commands extension
7+
description = """An example bot to showcase the discord.ext.commands extension
88
module.
99
10-
There are a number of utility commands being showcased here.'''
10+
There are a number of utility commands being showcased here."""
1111

1212
intents = discord.Intents.default()
1313
intents.members = True
1414

15-
bot = commands.Bot(command_prefix='?', description=description, intents=intents)
15+
bot = commands.Bot(command_prefix="?", description=description, intents=intents)
16+
1617

1718
@bot.event
1819
async def on_ready():
19-
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
20-
print('------')
20+
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
21+
print("------")
22+
2123

2224
@bot.command()
2325
async def add(ctx, left: int, right: int):
2426
"""Adds two numbers together."""
2527
await ctx.send(left + right)
2628

29+
2730
@bot.command()
2831
async def roll(ctx, dice: str):
2932
"""Rolls a dice in NdN format."""
3033
try:
31-
rolls, limit = map(int, dice.split('d'))
34+
rolls, limit = map(int, dice.split("d"))
3235
except Exception:
33-
await ctx.send('Format has to be in NdN!')
36+
await ctx.send("Format has to be in NdN!")
3437
return
3538

36-
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
39+
result = ", ".join(str(random.randint(1, limit)) for r in range(rolls))
3740
await ctx.send(result)
3841

39-
@bot.command(description='For when you wanna settle the score some other way')
42+
43+
@bot.command(description="For when you wanna settle the score some other way")
4044
async def choose(ctx, *choices: str):
4145
"""Chooses between multiple choices."""
4246
await ctx.send(random.choice(choices))
4347

48+
4449
@bot.command()
45-
async def repeat(ctx, times: int, content='repeating...'):
50+
async def repeat(ctx, times: int, content="repeating..."):
4651
"""Repeats a message multiple times."""
4752
for i in range(times):
4853
await ctx.send(content)
4954

55+
5056
@bot.command()
5157
async def joined(ctx, member: discord.Member):
5258
"""Says when a member joined."""
53-
await ctx.send(f'{member.name} joined in {member.joined_at}')
59+
await ctx.send(f"{member.name} joined in {member.joined_at}")
60+
5461

5562
@bot.group()
5663
async def cool(ctx):
@@ -59,11 +66,13 @@ async def cool(ctx):
5966
In reality this just checks if a subcommand is being invoked.
6067
"""
6168
if ctx.invoked_subcommand is None:
62-
await ctx.send(f'No, {ctx.subcommand_passed} is not cool')
69+
await ctx.send(f"No, {ctx.subcommand_passed} is not cool")
6370

64-
@cool.command(name='bot')
71+
72+
@cool.command(name="bot")
6573
async def _bot(ctx):
6674
"""Is the bot cool?"""
67-
await ctx.send('Yes, the bot is cool.')
75+
await ctx.send("Yes, the bot is cool.")
76+
6877

69-
bot.run('token')
78+
bot.run("token")

examples/basic_voice.py

Lines changed: 43 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,24 @@
66
from discord.ext import commands
77

88
# Suppress noise about console usage from errors
9-
youtube_dl.utils.bug_reports_message = lambda: ''
9+
youtube_dl.utils.bug_reports_message = lambda: ""
1010

1111

1212
ytdl_format_options = {
13-
'format': 'bestaudio/best',
14-
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
15-
'restrictfilenames': True,
16-
'noplaylist': True,
17-
'nocheckcertificate': True,
18-
'ignoreerrors': False,
19-
'logtostderr': False,
20-
'quiet': True,
21-
'no_warnings': True,
22-
'default_search': 'auto',
23-
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
13+
"format": "bestaudio/best",
14+
"outtmpl": "%(extractor)s-%(id)s-%(title)s.%(ext)s",
15+
"restrictfilenames": True,
16+
"noplaylist": True,
17+
"nocheckcertificate": True,
18+
"ignoreerrors": False,
19+
"logtostderr": False,
20+
"quiet": True,
21+
"no_warnings": True,
22+
"default_search": "auto",
23+
"source_address": "0.0.0.0", # bind to ipv4 since ipv6 addresses cause issues sometimes
2424
}
2525

26-
ffmpeg_options = {
27-
'options': '-vn'
28-
}
26+
ffmpeg_options = {"options": "-vn"}
2927

3028
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
3129

@@ -36,19 +34,21 @@ def __init__(self, source, *, data, volume=0.5):
3634

3735
self.data = data
3836

39-
self.title = data.get('title')
40-
self.url = data.get('url')
37+
self.title = data.get("title")
38+
self.url = data.get("url")
4139

4240
@classmethod
4341
async def from_url(cls, url, *, loop=None, stream=False):
4442
loop = loop or asyncio.get_event_loop()
45-
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
43+
data = await loop.run_in_executor(
44+
None, lambda: ytdl.extract_info(url, download=not stream)
45+
)
4646

47-
if 'entries' in data:
47+
if "entries" in data:
4848
# take first item from a playlist
49-
data = data['entries'][0]
49+
data = data["entries"][0]
5050

51-
filename = data['url'] if stream else ytdl.prepare_filename(data)
51+
filename = data["url"] if stream else ytdl.prepare_filename(data)
5252
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
5353

5454

@@ -70,29 +70,35 @@ async def play(self, ctx, *, query):
7070
"""Plays a file from the local filesystem"""
7171

7272
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
73-
ctx.voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)
73+
ctx.voice_client.play(
74+
source, after=lambda e: print(f"Player error: {e}") if e else None
75+
)
7476

75-
await ctx.send(f'Now playing: {query}')
77+
await ctx.send(f"Now playing: {query}")
7678

7779
@commands.command()
7880
async def yt(self, ctx, *, url):
7981
"""Plays from a url (almost anything youtube_dl supports)"""
8082

8183
async with ctx.typing():
8284
player = await YTDLSource.from_url(url, loop=self.bot.loop)
83-
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
85+
ctx.voice_client.play(
86+
player, after=lambda e: print(f"Player error: {e}") if e else None
87+
)
8488

85-
await ctx.send(f'Now playing: {player.title}')
89+
await ctx.send(f"Now playing: {player.title}")
8690

8791
@commands.command()
8892
async def stream(self, ctx, *, url):
8993
"""Streams from a url (same as yt, but doesn't predownload)"""
9094

9195
async with ctx.typing():
9296
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
93-
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
97+
ctx.voice_client.play(
98+
player, after=lambda e: print(f"Player error: {e}") if e else None
99+
)
94100

95-
await ctx.send(f'Now playing: {player.title}')
101+
await ctx.send(f"Now playing: {player.title}")
96102

97103
@commands.command()
98104
async def volume(self, ctx, volume: int):
@@ -123,13 +129,18 @@ async def ensure_voice(self, ctx):
123129
elif ctx.voice_client.is_playing():
124130
ctx.voice_client.stop()
125131

126-
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"),
127-
description='Relatively simple music bot example')
132+
133+
bot = commands.Bot(
134+
command_prefix=commands.when_mentioned_or("!"),
135+
description="Relatively simple music bot example",
136+
)
137+
128138

129139
@bot.event
130140
async def on_ready():
131-
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
132-
print('------')
141+
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
142+
print("------")
143+
133144

134145
bot.add_cog(Music(bot))
135-
bot.run('token')
146+
bot.run("token")

0 commit comments

Comments
 (0)