如何修复Python中“missing 1 required positional argument: 'self'”报错?
Discord.py
on_message 函数添加self后报错解决方案 错误原因
self仅作为Python类实例方法的第一个必填参数存在,你当前使用@client.event装饰的是全局独立函数,不需要也不应该添加self参数- Discord.py触发
on_message事件时,只会给回调函数传入1个message位置参数,你额外添加了self参数后,调用时参数数量不匹配,就会抛出missing 1 required positional argument: 'self'报错 - 额外注意:原代码中
await message.channel.send('I rolled' , (n))的写法会把两个参数作为两条独立消息发送,建议用f-string格式化拼接成单个字符串发送
解决方案
方案1:使用常规全局函数写法(适合小型简单bot)
直接删除on_message参数列表中的self即可,修正后代码如下:
@client.event async def on_message(message): print(message) if message.author == client.user: return if message.content.startswith('-roll'): n = random.random() # 用f-string拼接内容,只会发送1条消息 await message.channel.send(f'I rolled {n}')
方案2:确实需要封装到类中使用(适合中大型功能复杂的bot)
需要使用Discord.py的Cog(扩展组件)规范编写,此时要把self放在参数列表第一位,同时把装饰器换成@commands.Cog.listener(),示例如下:
from discord.ext import commands import random # 自定义Cog类 class RollCog(commands.Cog): def __init__(self, bot): self.bot = bot # 类内的事件监听装饰器 @commands.Cog.listener() async def on_message(self, message): print(message) if message.author == self.bot.user: return if message.content.startswith('-roll'): n = random.random() await message.channel.send(f'I rolled {n}')
内容的提问来源于stack exchange,提问作者Vector
相关产品推荐
相关产品推荐

