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

Discord机器人报错:missing required positional argument 'ctx' 解决方法

解决Discord机器人报错:missing required positional argument 'ctx'

错误成因

你将DiscordBot类中的hello实例方法直接通过add_command挂载到commands.Bot实例上,但类的实例方法第一个参数必须是self,而@commands.command装饰器生成的命令逻辑会把ctx作为第一个参数传入,导致参数匹配完全错位:原本应该接收self的位置被ctx占用,真正需要的ctx没有对应的参数位置,最终触发missing required positional argument 'ctx'错误。

此外,你的on_ready事件方法也没有被正确注册到bot上,无法触发。

修复方案

方案一:使用官方推荐的Cog机制(最规范)

Discord.py提供了commands.Cog用于组织类形式的命令和事件,能自动处理类实例方法的参数传递:

import discord
import os
from dotenv import load_dotenv
from discord.ext import commands
import logging


class DiscordBot(commands.Cog):
    def __init__(self, bot) -> None:
        self.bot = bot

    # 用Cog装饰器注册事件
    @commands.Cog.listener()
    async def on_ready(self):
        print("Bot is ready.")
    
    @commands.command()
    async def hello(self, ctx):
        await ctx.channel.send('Hello!')
        print("HELLO!")


if __name__ == '__main__':
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN_KEY')

    logging.basicConfig(level=logging.DEBUG)
    # 创建Bot实例并配置权限
    bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
    
    # 异步添加Cog
    async def setup():
        await bot.add_cog(DiscordBot(bot))
    
    bot.loop.run_until_complete(setup())
    bot.run(TOKEN)

说明:

  • 让DiscordBot继承commands.Cog,事件方法用@commands.Cog.listener()装饰
  • 实例化Cog时传入Bot实例,确保内部能访问bot对象
  • discord.Intents.all()已经包含所有权限,无需重复单独设置messages等属性

方案二:调整类方法定义(快速临时修复)

如果不想用Cog,可以将hello改为静态方法,避免self参数的影响,同时手动注册事件:

import discord
import os
from dotenv import load_dotenv
from discord.ext import commands
import logging


class DiscordBot:
    def __init__(self) -> None:
        self.intents = discord.Intents.all()
        self.bot = commands.Bot(command_prefix='$', intents=self.intents)

    async def on_ready(self):
        print("Bot is ready.")
    
    # 改为静态方法,移除self参数
    @staticmethod
    @commands.command()
    async def hello(ctx):
        await ctx.channel.send('Hello!')
        print("HELLO!")


if __name__ == '__main__':
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN_KEY')

    logging.basicConfig(level=logging.DEBUG)
    bot = DiscordBot()
    bot.bot.add_command(bot.hello)
    # 手动注册on_ready事件
    bot.bot.event(bot.on_ready)
    
    bot.bot.run(TOKEN)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:00:14