使用Python+Discord API开发AlarmBot时datetime.strptime()报ValueError
解决Discord Bot中datetime.strptime()的ValueError异常
问题现象
开发Discord AlarmBot时,!remind命令始终触发datetime.strptime()的ValueError。输入!remind 06/18/2023 21:07 this is a test时,机器人输出Reminder set: 21:07 this is a test,说明时间参数的21:07被错误识别为提醒内容的一部分,而非时间的组成部分。
问题根源
- 参数解析错误:Discord.py的命令参数规则中,原定义
async def remind(ctx, time: str, *, reminder: str)里,time: str只会捕获第一个空格前的内容(即06/18/2023),21:07被归入了可变参数* reminder,导致传入strptime()的字符串缺少时间部分,触发格式不匹配的ValueError。 - 变量作用域问题:
then变量定义在try块内部,若触发异常,后续代码访问then会引发未定义错误。 - 单提醒限制:原
reminders字典用用户ID作为键,只能存储一个提醒,无法支持多提醒需求。
修复方案
1. 调整命令参数解析
将日期和时间拆分为两个独立参数,合并后再解析,确保时间的两部分都被正确捕获:
2. 修正核心代码逻辑
将时间计算、延迟提醒等逻辑移入try块内,避免访问未定义变量;同时优化提醒存储结构,支持多提醒。
修改后的remind命令代码:
@client.command() async def remind(ctx, date: str, time: str, *, reminder: str): reminder_message = f"{ctx.author.mention}, Here's your reminder: {reminder}" full_time = f"{date} {time}" format = "%m/%d/%Y %H:%M" try: then = datetime.strptime(full_time, format) now = datetime.now() time_diff = (then - now).total_seconds() if time_diff < 0: await ctx.send("设置的时间早于当前时间,请输入未来的时间。") return # 存储提醒(支持多提醒,用列表存储用户的所有提醒) if ctx.author.id not in reminders: reminders[ctx.author.id] = [] reminders[ctx.author.id].append((reminder_message, then)) await ctx.send(f"提醒已设置: {reminder}") await asyncio.sleep(time_diff) # 检查并触发提醒(避免已取消的提醒发送) if ctx.author.id in reminders: # 匹配对应的提醒并移除 for idx, (msg, t) in enumerate(reminders[ctx.author.id]): if t == then and msg == reminder_message: del reminders[ctx.author.id][idx] await ctx.send(msg) # 无剩余提醒时删除用户键 if not reminders[ctx.author.id]: del reminders[ctx.author.id] break except ValueError: await ctx.send("请按照正确格式输入时间:`MM/DD/YYYY HH:MM`")
3. 调整提醒存储结构
将原字典修改为支持多提醒的结构:
reminders = {} # 结构:{用户ID: [(提醒消息, 提醒时间), ...]}
4. 优化取消命令(支持清空多提醒)
@client.command() async def cancel(ctx): if ctx.author.id in reminders and reminders[ctx.author.id]: reminders[ctx.author.id].clear() del reminders[ctx.author.id] await ctx.send("你的所有提醒已取消") else: await ctx.send("未找到任何提醒")
测试验证
输入!remind 06/18/2023 21:07 this is a test,机器人会正确解析完整时间,设置提醒并在指定时间发送通知,不再触发ValueError。
内容的提问来源于stack exchange,提问作者BoppingPeople
相关产品推荐
相关产品推荐

