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

discord.py async函数中如何设置带空格的触发指令?

问题原因

discord.py 内置的命令解析器默认以前缀后的第一个空格为分界,空格前的内容识别为命令名,后续内容全部视为参数。你当前定义的how_are_you函数默认对应触发指令为=how_are_you,当用户输入=how are you时,解析器仅会将how判定为命令名,自然无法匹配对应函数。

解决方法

方案1:直接定义带空格的命令名(最简单,推荐)

显式在命令装饰器中指定完整多词命令,同时可以开启全局大小写不敏感匹配,适配"How are You?"这类大小写混合的输入场景:

import discord
from discord.ext import commands
# 初始化时添加case_insensitive参数,开启大小写不敏感匹配
client = commands.Bot(command_prefix= '=', case_insensitive=True)

@client.event
async def on_ready():
    print('Bot is online')

@client.command()
async def hello(ctx):
    await ctx.send('hello')

# 用name参数指定完整的带空格命令名
@client.command(name="how are you")
async def how_are_you(ctx):
    await ctx.send('I am good')

client.run('token')

修改后输入=how are you、=How are You都可以正常触发指令。

方案2:命令组嵌套实现(兼容旧版本discord.py)

如果你的discord.py版本较低,不支持带空格的命令名,可以用嵌套命令组的方式实现:

import discord
from discord.ext import commands
client = commands.Bot(command_prefix= '=', case_insensitive=True)

@client.event
async def on_ready():
    print('Bot is online')

@client.command()
async def hello(ctx):
    await ctx.send('hello')

# 定义第一层命令组how
@client.group(invoke_without_command=True)
async def how(ctx):
    # 单独输入=how时的返回内容,不需要可以直接写pass
    await ctx.send("请输入完整指令")

# 定义第二层子命令组are
@how.group(invoke_without_command=True)
async def are(ctx):
    pass

# 定义第三层子命令you
@are.command()
async def you(ctx):
    await ctx.send('I am good')

client.run('token')

方案3:自定义消息事件处理(灵活度最高)

如果需要自定义更多匹配规则,可以直接重写on_message事件手动匹配指令:

import discord
from discord.ext import commands
client = commands.Bot(command_prefix= '=')

@client.event
async def on_ready():
    print('Bot is online')

@client.event
async def on_message(message):
    # 过滤机器人自身发送的消息,避免死循环
    if message.author == client.user:
        return
    # 自定义匹配规则,lower()处理后可以适配任意大小写输入
    if message.content.lower().startswith('=how are you'):
        await message.channel.send('I am good')
    # 保留原有命令的解析逻辑,不加这行之前定义的hello等命令会失效
    await client.process_commands(message)

@client.command()
async def hello(ctx):
    await ctx.send('hello')

client.run('token')

内容的提问来源于stack exchange,提问作者Md Sadman Muhtasim Billah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:06:04