Discord机器人执行!number命令时wait_for报缺少event参数错误求助
解决Discord机器人wait_for报错及猜数字功能修复
核心错误原因
你遇到的TypeError: wait_for() missing 1 required positional argument: 'event',是因为直接调用了类方法commands.Bot.wait_for,而没有使用机器人实例的方法。在Cog类中,应该用初始化时保存的self.bot实例来调用wait_for。
完整修复代码
修复后的guess_the_number.py
# guess_the_number.py from random import randrange from discord.ext import commands class number_guesser(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def number(self, ctx): x = randrange(1001) # 生成0-1000的随机数(randrange左闭右开,写1001才能包含1000) print(f"random number: {x}") await ctx.send(f"Gib eine Zahl zwischen 0 und 1000 ein @ {ctx.author.name}!") # 修复check函数:仅接收命令发起者的输入,且内容是0-1000的有效数字 def check(m): if m.author != ctx.author or m.channel != ctx.channel: return False if not m.content.isdigit(): return False num = int(m.content) return 0 <= num <= 1000 # 使用机器人实例调用wait_for msg = await self.bot.wait_for('message', check=check) guess_num = int(msg.content) if guess_num == x: await ctx.send(f"{msg.content} ist richtig!") else: await ctx.send(f"{msg.content} ist leider falsch. {x} wär die Lösung!")
其他关键修复点
- 随机数范围修正:原代码
randrange(1000)生成0-999的数,改为randrange(1001)才能覆盖0-1000的要求范围 - 输入校验增强:check函数新增「仅允许命令发起者输入」和「数字范围检查」,避免其他用户干扰或输入无效值
- 类型转换修正:将用户输入的字符串转为整数后再和随机数比较,原代码直接用Message对象和数字比较永远不成立
主代码无需修改
你的bot.py代码逻辑正常,不需要调整。
内容的提问来源于stack exchange,提问作者NirvanaGirl
相关产品推荐
相关产品推荐

