如何在discord.py中实现消息时间差超指定值时发送消息?
解决discord.py中时间差判断失效的问题
你的代码存在两个核心问题,导致判断逻辑无法生效:
- 无需将
message.created_at转为字符串再解析成datetime对象,它本身就是一个datetime实例,直接使用即可。 - 不能直接用字符串
00:01:00.000000与时间差(timedelta类型)做比较,必须用datetime.timedelta创建对应时长的对象来完成对比。
另外需要注意,message.created_at是UTC时间,建议用datetime.utcnow()获取当前UTC时间,避免时区差异造成的计算误差。
修正后的完整代码示例:
from datetime import datetime, timedelta import discord # 确保代码在异步函数内执行(比如事件监听或命令函数) async def check_message_age(message, target_channel): # 直接计算时间差,省略多余的字符串转换步骤 time_diff = datetime.utcnow() - message.created_at # 创建1分钟的时长阈值对象 threshold = timedelta(minutes=1) if time_diff > threshold: embed = discord.Embed(title="test.", color=0xf1c40f) await target_channel.send(embed=embed)
关键说明:
timedelta支持通过minutes、seconds、hours等参数灵活定义阈值,比如timedelta(hours=1, minutes=30)代表1小时30分钟的时长。- 必须保证代码运行在异步环境中,因为
await target_channel.send()是异步操作,需要在async def定义的函数内执行。 - 如果你的bot涉及时区本地化,需保持当前时间与
message.created_at的时区一致,优先使用UTC时间避免偏差。
内容的提问来源于stack exchange,提问作者user19599936
相关产品推荐
相关产品推荐

