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

Discord.py自定义Bot子类中test命令无法识别ctx参数

问题原因

你在自定义commands.Bot子类时,手动调用self.add_command(self.test)注册命令,而@commands.command装饰器已经将test方法包装为Command对象,且Bot父类的初始化流程会自动扫描并注册带有该装饰器的方法。手动注册绑定后的实例方法会导致命令调用时参数传递错误:discord.py尝试将ctx作为第一个参数传入,但test作为实例方法需要self作为第一个参数,最终引发缺少ctx的错误。

解决方案

删除__init__方法中的self.add_command(self.test)代码,让Bot父类自动完成命令注册即可。

修改后的完整代码:

import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
from typing import Coroutine, Any

os.system("clear")

load_dotenv()
TOKEN = os.environ["TOKEN"]

class Bot(commands.Bot):
    # Bot setup
    def __init__(self, activity: discord.Game, command_prefix: str, intents: discord.Intents, *args, **kwargs) -> None:
        super().__init__(activity=activity, command_prefix=command_prefix, intents=intents, **kwargs)
        # 移除手动注册命令的代码
    
    def set_channel(self, channel_id: int) -> None:
        self.channel_id = channel_id
        self.channel = super().get_channel(channel_id)

    async def on_ready(self) -> None:
        print(f"Logged in as {self.user}!")
    
    async def on_message(self, message: discord.Message) -> None:
        print(f"Message from {message.author}: {message.content}")
        await self.process_commands(message)
    
    async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> Coroutine[Any, Any, None]:
        return await super().on_error(event_method, *args, **kwargs)
    
    @commands.command()
    async def test(self, ctx) -> None:
        await ctx.send("Testing...")

if __name__ == "__main__":
    # Bot configuration setup
    intents: discord.Intents = discord.Intents.default()
    intents.message_content = True
    channel_name: str = "general"
    channel_id: int = 0

    # Setting up bot
    bot = Bot(activity=discord.Game(name="with you"), command_prefix="/", intents=intents)
    for c in bot.get_all_channels():
        if c.name == channel_name:
            channel_id = c.id
            bot.set_channel(channel_id)

    bot.run(TOKEN)
补充说明
  1. 当你在commands.Bot子类中定义方法并使用@commands.command装饰时,父类的初始化逻辑会自动识别这些方法并注册为命令,无需手动调用add_command。
  2. 自定义on_message方法时,必须调用await self.process_commands(message),否则命令不会被触发,这部分你已经正确实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:55:58