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

运行discord.py代码报错on_ready()缺少必填位置参数self如何解决

discord.py on_ready() 缺少self参数报错修复方案

错误根源

该报错是因为你混用了discord.py的两种事件注册模式,导致on_ready的参数定义和调用逻辑不匹配:

  • 如果你给on_ready加了self参数,但该函数不是自定义Bot/Client子类的成员方法,discord.py触发事件时不会自动传入self,就会抛出缺少required positional argument: 'self'错误
  • 如果你移除self参数,但函数内部还在使用self.user这类调用,普通函数作用域不存在self变量,就会触发变量未定义报错

修复方案

根据你使用的编码模式二选一即可:

方案1:使用子类化Bot模式(需要保留self参数)

将on_ready作为自定义Bot子类的成员方法,框架会自动传入实例本身作为self参数:

import discord
from discord.ext import commands

# 自定义Bot子类
class CustomBot(commands.Bot):
    def __init__(self):
        # 按需配置命令前缀和intents,discord.py 2.0+必须显式声明intents
        super().__init__(command_prefix="!", intents=discord.Intents.all())
    
    # 类成员方法必须带self参数
    async def on_ready(self):
        print(f"机器人登录成功,当前账号为:{self.user}")
        # 你原来的on_ready逻辑直接放在这里即可

# 实例化并运行
bot = CustomBot()
bot.run("你的机器人TOKEN")

方案2:使用装饰器注册事件模式(不需要self参数)

如果你是直接实例化Bot对象用@bot.event注册事件,不需要加self参数,直接用你定义的bot实例变量访问用户信息即可:

import discord
from discord.ext import commands

# 实例化Bot,必须显式声明intents
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)

# 装饰器注册的事件是普通函数,不要加self参数
@bot.event
async def on_ready():
    # 用bot变量代替self访问实例属性
    print(f"机器人登录成功,当前账号为:{bot.user}")
    # 你原来的on_ready逻辑直接放在这里即可,把所有self替换成bot即可

bot.run("你的机器人TOKEN")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:06:03