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

Discord.py报错:self是缺失的必填参数,求技术解决方案

解决Discord.py中about命令的MissingRequiredArgument错误

问题原因

你遇到的MissingRequiredArgument: self is a required argument that is missing错误,核心问题是你的about命令函数错误地添加了self参数。

当你直接使用commands.Bot创建机器人实例(如你的代码中bot = commands.Bot(...))时,普通命令函数不需要self参数——self是为继承commands.Cog的类中的命令方法设计的,用于引用类实例本身。而直接绑定在bot实例上的命令,第一个参数应该是ctx(命令上下文对象),用来关联命令执行的相关环境信息。

修改后的完整代码

@bot.command()
async def about(ctx):
    """Tells you information about the bot itself."""
    result = ['**About Me:**']
    result.append('- Author: AmusedGrape [ID: 401792058970603539]')
    result.append('- Library: discord.py (Python)')
    result.append('- Latest Change: 2.0 Update')
    result.append('- Uptime: {}'.format(get_bot_uptime()))
    result.append('- Servers: {}'.format(len(bot.servers)))
    result.append('- Commands Run: {}'.format(sum(bot.commands_used.values())))
    
    total_members = sum(len(s.members) for s in bot.servers)
    total_online = sum(1 for m in bot.get_all_members() if m.status != discord.Status.offline)
    unique_members = set(bot.get_all_members())
    unique_online = sum(1 for m in unique_members if m.status != discord.Status.offline)
    
    channel_types = Counter(c.type for c in bot.get_all_channels())
    voice = channel_types[discord.ChannelType.voice]
    text = channel_types[discord.ChannelType.text]
    
    result.append('- Total Members: {} ({} online)'.format(total_members, total_online))
    result.append('- Unique Members: {} ({} online)'.format(len(unique_members), unique_online))
    result.append('- {} text channels, {} voice channels'.format(text, voice))
    result.append('')
    result.append('Text server: https://discord.gg/~~~~~~')
    
    await bot.say('\n'.join(result))

关键修改点

  1. 将async def about(self):改为async def about(ctx)::移除了不必要的self参数,添加了命令必需的ctx参数(即使你在函数内部暂时没用到ctx,它也是直接绑定在bot上的命令函数的第一个必填参数)。
  2. 其余统计逻辑无需改动——你原来的功能实现是完全正常的,修正参数问题后命令就能正常执行。

补充说明

如果未来你想使用Cog(命令组/扩展)来更有条理地组织机器人命令,那么类中的命令方法就需要self参数,示例如下:

from discord.ext import commands
from collections import Counter
import discord

class AboutCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def about(self, ctx):
        # 这里需要self来引用Cog实例,进而调用self.bot相关方法
        result = ['**About Me:**']
        result.append('- Author: AmusedGrape [ID: 401792058970603539]')
        # 其余逻辑和你原来的代码一致,只需把bot替换为self.bot
        await ctx.send('\n'.join(result))

# 注册Cog到机器人实例
bot.add_cog(AboutCog(bot))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:30:33