Python Discord Bot用户交互问题:Pomodoro命令无法发送消息
问题分析与解决
首先,你的pomodoro命令没正常触发的核心原因有两个,咱们一步步拆解:
1. 重写on_message但未处理命令
当你自定义on_message事件后,Discord.py的命令系统默认不会自动识别装饰器定义的命令了。必须在on_message函数末尾添加一行代码,让机器人去处理这些命令:
@client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('>hello'): msg = 'Hello, {0.author.mention}!'.format(message) await message.channel.send(msg) # 关键:添加这行,让机器人处理用@client.command定义的命令 await client.process_commands(message)
2. pomodoro函数里的逻辑错误
ctx是Context对象,它根本没有content属性,你写的if ctx.content.startswith('>pomodoro')会直接抛出错误,导致命令还没发消息就中断了。- 另外,
check函数里type(msg.content)==int完全不对——用户发送的消息内容永远是字符串类型,哪怕输入数字,也是"25"这种字符串,这里得检查内容能不能转成整数。
修改后的pomodoro命令代码
@client.command(name="pomodoro") async def pomodoro(ctx): # 直接发送消息就行,命令已经通过前缀匹配了,不用再判断 await ctx.send("Let's grab some tomatoes! For how many minutes?") def check(msg): # 先验证发送者和频道匹配,再检查内容是否是有效数字 if msg.author != ctx.author or msg.channel != ctx.channel: return False # 尝试把内容转成整数,能成功就返回True try: int(msg.content) return True except ValueError: return False # 等待用户输入符合要求的消息 msg = await client.wait_for("message", check=check) # 把输入转成整数 study_minutes = int(msg.content) await ctx.send(f"Got it! We'll study for {study_minutes} minutes. Now tell me the break duration?") # 这里可以继续添加休息时长的输入逻辑,和上面的检查逻辑类似
额外小提示
- 命令函数名建议用小写(比如
pomodoro而非Pomodoro),符合Python命名规范,Discord.py也能正常识别。 - 用
ctx.send()比ctx.channel.send()更简洁,效果完全一样。 - 后续做计时器的时候,一定要用
asyncio.sleep(),别用普通的time.sleep()——后者会阻塞整个机器人,导致其他功能都没法用。
内容的提问来源于stack exchange,提问作者Kali
相关产品推荐
相关产品推荐

