如何修复discord.py中ctx缺失的MissingRequiredArgument报错且保留类与self
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing修复方案 报错信息
Traceback (most recent call last):
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
问题原因
- 你在
__init__方法里用inspect手动遍历添加类内命令的逻辑错误,会把类方法的self参数识别为命令需要用户传入的参数,打乱了框架自动传入ctx的逻辑,最终导致框架判定ctx参数缺失 - 你使用了已经废弃的
pass_context=True参数,discord.py v1.5之后ctx会默认自动注入,不需要手动开启该参数 - 代码存在拼写错误:
reg方法内调用的self.embed()不存在,你定义的对应方法名为embed_channel
修复代码(保留原有类结构和self参数)
#!/usr/bin/python3 from discord.ext import commands import discord TOKEN = "你的机器人令牌" # 自行补充实际令牌值 class StarBot(commands.Bot): def __init__(self, command_prefix, **options): super().__init__(command_prefix, **options) async def setup_hook(self): # 官方推荐的类内命令注册方式,替换原来的inspect遍历逻辑 self.add_command(self.reg) async def on_ready(self): print('Logged on as {0}!'.format(self.user)) # 删除废弃的pass_context参数 @commands.command(name='reg', help='Для регистрации') async def reg(self, ctx): if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message': # 修正方法名拼写错误 await self.embed_channel(ctx.channel, "Начало регистрации") async def embed_channel(self, channel, title, string='', color=0xff9900): embed = discord.Embed(color=color, title=title, description=string) msg = await channel.send(embed=embed) return msg intents = discord.Intents.all() bot = StarBot(command_prefix='/', intents=intents) bot.run(TOKEN)
内容的提问来源于stack exchange,提问作者Phoenix

