Discord Bot开发:运行时实时更新倒计时日期时间
解决Discord Bot倒计时实时更新的问题
核心问题在于你只在脚本启动时获取了一次当前时间,后续计算一直复用这个固定值。解决方法很直接:每次需要计算倒计时的时候,重新获取最新的当前时间,而不是提前存储。
基础命令式实现(用户触发时更新)
用户发送命令时才计算并返回最新的倒计时,适合按需查询的场景:
import datetime import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # 提前定义目标日期,无需重复创建 TARGET_DATE = datetime.datetime(2024, 12, 31, 23, 59, 59) @bot.command(name='countdown') async def send_countdown(ctx): # 每次调用命令时,实时获取当前时间 current_time = datetime.datetime.now() if current_time > TARGET_DATE: await ctx.send("目标日期已经过去了!") return remaining = TARGET_DATE - current_time days = remaining.days hours, remainder = divmod(remaining.seconds, 3600) minutes, seconds = divmod(remainder, 60) await ctx.send(f"剩余时间:{days}天 {hours}小时 {minutes}分钟 {seconds}秒") bot.run('你的Bot令牌')
自动定时刷新实现(无需用户触发)
如果需要Bot自动每隔一段时间发送最新倒计时,使用Discord.py官方的tasks.loop模块,避免自定义循环阻塞Bot事件处理:
import datetime import discord from discord.ext import commands, tasks bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) TARGET_DATE = datetime.datetime(2024, 12, 31, 23, 59, 59) # 替换成你要发送倒计时的频道ID COUNTDOWN_CHANNEL_ID = 123456789012345678 @bot.event async def on_ready(): print(f"已登录:{bot.user}") # Bot启动后自动启动定时任务(每60秒执行一次) auto_countdown.start() @tasks.loop(seconds=60) async def auto_countdown(): channel = bot.get_channel(COUNTDOWN_CHANNEL_ID) if not channel: print("未找到指定频道,定时任务终止") auto_countdown.stop() return current_time = datetime.datetime.now() if current_time > TARGET_DATE: await channel.send("目标日期已经过去了!") auto_countdown.stop() return remaining = TARGET_DATE - current_time days = remaining.days hours, remainder = divmod(remaining.seconds, 3600) minutes, seconds = divmod(remainder, 60) await channel.send(f"实时倒计时:{days}天 {hours}小时 {minutes}分钟 {seconds}秒") # 手动启停定时任务的命令 @bot.command(name='start_auto') async def start_auto_countdown(ctx): if not auto_countdown.is_running(): auto_countdown.start() await ctx.send("自动倒计时已启动!") else: await ctx.send("自动倒计时已经在运行了!") @bot.command(name='stop_auto') async def stop_auto_countdown(ctx): if auto_countdown.is_running(): auto_countdown.stop() await ctx.send("自动倒计时已停止!") else: await ctx.send("自动倒计时没有在运行!") bot.run('你的Bot令牌')
关键注意点
- 绝不提前固定
current_time,必须在每次计算时调用datetime.datetime.now() - 禁止自己写
while True循环,会阻塞Discord Bot的事件循环,导致Bot无法响应其他命令或事件 - 定时任务优先使用
tasks.loop,这是Discord.py官方推荐的兼容事件循环的实现方式
内容的提问来源于stack exchange,提问作者Mankitsu
相关产品推荐
相关产品推荐

