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

Discord.py命令无响应求助:自定义命令无法触发

问题原因与解决方案

你遇到的命令无法触发的核心原因是:自定义了on_message事件但未调用bot.process_commands()方法。discord.py中,当你重写on_message事件时,会覆盖默认的命令处理流程,必须手动添加该方法来让框架解析并触发你的自定义命令。

修改方法

在on_message事件的末尾添加await bot.process_commands(message),确保命令框架能正常处理你的hello和calculate命令:

import discord
import asyncio
import ast
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='?', intents=intents)
    
@bot.event
async def on_ready():
    print(f'logged in baby {bot.user}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if 'nigg' in message.content or 'wigg' in message.content:
        author = message.author
        guild = message.guild
        await author.add_roles(discord.utils.get(guild.roles, name='Racist'))
        await message.delete()
    
    # 新增这一行,让命令框架处理消息中的命令
    await bot.process_commands(message)

@bot.command()
async def calculate(ctx, *, expression: str):
    await ctx.send(f'{expression} = {eval(expression)}')

@bot.command()
async def hello(ctx):
    print('hi')
    await ctx.send('hello guys')

bot.run('token')

额外提示

  • 注意await bot.process_commands(message)的位置,要放在所有自定义消息逻辑之后,确保消息先经过你的内容检测,再进入命令处理流程。
  • 另外,使用eval()处理用户输入存在安全风险,建议限制使用场景或添加输入校验逻辑,避免恶意代码执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:33:00