You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中将变量的值作为命令名称使用

解决方法

现有代码问题

现有代码直接将函数名定义为command_name,discord.py默认会使用函数名作为命令触发名,因此无法读取提前输入存储在command_name变量里的自定义名称。

修改方案

discord.py 提供两种方式动态设置命令名称:

方式1:使用装饰器的name参数

在@bot.command()中传入name参数,直接赋值为你提前获取的command_name变量即可,函数名可以随意设置为不重复的通用名称:

print('Please paste your token:  ')
token = input()
print('Please input your prefix:  ')
prefix = input()
print('Command name:  ')
command_name = input()
print('What would you like to reply with:  ')
command_reply = input()
bot = commands.Bot(command_prefix=prefix)

@bot.event
async def  on_ready():
    print("Ready !")

@bot.command()
async def ping(ctx):
    await ctx.send('**pong**')

# 这里用name参数指定命令名为变量存储的值
@bot.command(name=command_name)
async def _dynamic_command(ctx):
  await ctx.send(command_reply)

bot.run(token)

方式2:使用add_command方法动态注册

如果需要批量注册多个动态命令,可以用Bot.add_command()方法更灵活地实现:

# 前面获取token、prefix、command_name、command_reply的代码不变
bot = commands.Bot(command_prefix=prefix)

@bot.event
async def  on_ready():
    print("Ready !")

@bot.command()
async def ping(ctx):
    await ctx.send('**pong**')

# 动态创建命令函数
async def dynamic_cmd(ctx):
    await ctx.send(command_reply)
# 注册命令,指定名称
bot.add_command(commands.Command(dynamic_cmd, name=command_name))

bot.run(token)

可选优化

可以加重复命令判断,避免输入的命令名和已有的ping命令重名导致报错:

if command_name in bot.all_commands:
    print(f"错误:已存在名为{command_name}的命令")
    exit()
# 再执行命令注册逻辑

内容的提问来源于stack exchange,提问作者Benni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:36:08