'How do I make an optional parameter in a slash command (Pycord)
I have a slash command in my Pycord bot. Here is the code:
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name):
await ctx.send('Hello ' + name + '!')
How would I make "name" an optional parameter? I tried setting name=None, but it doesn't work.
Solution 1:[1]
you could find examples from pycord repo examples/app_commands
# example.py
import discord
import json
from discord.ext import commands
from discord.commands.context import ApplicationContext
from discord.commands import Option
from discord.file import File
import os
# example for getting image
def get_image_paths():
file_paths = []
for fn in os.listdir('./img'):
file_paths.append(os.path.join(os.getcwd(), 'img', fn))
return file_paths
async def images(ctx : ApplicationContext):
imgs = get_image_paths()
files = [File(path) for path in imgs]
await ctx.respond(files=files)
async def say_hello(ctx : ApplicationContext):
await ctx.respond(f"hello")
# guild_ids are optional, but for fast registration I recommand it
# name (optional) : if not provided, your command name will shown as function name; this case "my_command"
@commands.slash_command(
name = "my_command",
description= "This is sample command",
guild_ids = [ <your guild(server) id> ],
)
async def sample_command(
ctx : ApplicationContext,
opt: Option(str,
"reaction you want",
choices=["Hi", "image"],
required=True)
):
if opt == "Hi":
await say_hello(ctx)
if opt == "image":
await images(ctx)
it will look like :
import this script as from example import library_command
and don't forget to add commands
# at main.py
...
bot.add_application_command(library_command)
...
bot.run(<your token>)
you must send as 'respond' not 'send' or discord will count as "failed to reply"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ccppoo |



