You need to enable JavaScript to run this app. Discord.py 如何在Embed消息中添加实时倒计时功能
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py 如何在Embed消息中添加实时倒计时功能

基于Discord.py实现Embed内实时倒计时的可落地实现

现有代码的核心问题

  • 存在缩进错误,时间判断的逻辑块完全脱离了主循环的作用域,正常运行时根本不会触发发消息的分支
  • 字符串等值匹配时间的逻辑可靠性极低:只要主循环因为网络IO、任务调度稍有延迟,就会错过目标时间点,且没有触发标记,会在命中目标时间后的每一轮循环都重复发送新的Embed消息
  • 发送Embed时没有接收channel.send()的返回值,丢失了消息对象引用,后续根本没有权限修改对应消息的Embed内容
  • 主循环没有设置合理的休眠间隔,会无意义占满CPU算力
  • 倒计时计算没有锚定固定的时间终点,会出现计时漂移

核心实现思路

  • 将触发发消息的目标时间、倒计时的最终截止时间抽为常量,避免硬编码
  • 用时间差判断替代字符串匹配,确保只要到达目标时间区间就触发一次发消息逻辑,同时加触发标记避免重复发消息
  • 发送消息后留存消息引用,每次更新倒计时时直接复用原Embed对象,仅修改Timer字段的value值,通过Message.edit()方法更新原消息,不需要重新发送新内容
  • 主循环每轮休眠1秒,既保证倒计时精度,也不会触发Discord的API频率限制
  • 倒计时到点后停止刷新任务,减少无意义的API调用

修正后的完整参考代码

import discord
import datetime
import asyncio

# 自定义配置项
TRIGGER_SEND_TIME = datetime.time(hour=3, minute=9, second=0)  # 触发发消息的时间
COUNTDOWN_TARGET_TIME = datetime.datetime(2024, 12, 31, 23, 59, 59)  # 倒计时最终截止时间
AUTH_CHANNEL_ID = 123456789012345678  # 替换成你的目标频道ID
client = discord.Client()

@client.event
async def on_ready():
    print(f"机器人已登录:{client.user}")

async def background_countdown_task():
    await client.wait_until_ready()
    target_channel = client.get_channel(AUTH_CHANNEL_ID)
    has_sent_embed = False  # 标记是否已经触发过发消息逻辑,避免重复发送

    while not client.is_closed():
        now = datetime.datetime.now()
        # 判断是否到了触发发消息的时间
        current_time = now.time()
        if current_time >= TRIGGER_SEND_TIME and not has_sent_embed:
            # 构建初始Embed
            embed = discord.Embed(
                colour=discord.Colour.green(),
                title="test"
            )
            embed.set_image(url="(img)")
            embed.set_thumbnail(url="(img)")
            # 计算初始剩余时间
            remaining = COUNTDOWN_TARGET_TIME - now
            total_seconds = int(remaining.total_seconds())
            if total_seconds > 0:
                days, remainder = divmod(total_seconds, 86400)
                hours, remainder = divmod(remainder, 3600)
                minutes, seconds = divmod(remainder, 60)
                timer_str = f"{days}天 {hours:02d}:{minutes:02d}:{seconds:02d}"
            else:
                timer_str = "倒计时已结束"
            embed.add_field(name="Timer", value=timer_str, inline=True)
            embed.add_field(name="Location", value="adding later", inline=True)
            # 发送消息并留存引用
            sent_message = await target_channel.send(embed=embed)
            has_sent_embed = True

            # 进入倒计时刷新循环
            while has_sent_embed:
                now = datetime.datetime.now()
                remaining = COUNTDOWN_TARGET_TIME - now
                total_seconds = int(remaining.total_seconds())
                if total_seconds <= 0:
                    # 倒计时结束,更新最后一次内容后停止刷新
                    embed.set_field_at(0, name="Timer", value="倒计时已结束", inline=True)
                    await sent_message.edit(embed=embed)
                    break
                # 格式化剩余时间
                days, remainder = divmod(total_seconds, 86400)
                hours, remainder = divmod(remainder, 3600)
                minutes, seconds = divmod(remainder, 60)
                timer_str = f"{days}天 {hours:02d}:{minutes:02d}:{seconds:02d}"
                # 修改原Embed的Timer字段值
                embed.set_field_at(0, name="Timer", value=timer_str, inline=True)
                # 编辑原消息实现实时更新
                await sent_message.edit(embed=embed)
                # 休眠1秒再刷新,避免频率过高
                await asyncio.sleep(1)
        # 外层主循环休眠1秒
        await asyncio.sleep(1)

client.loop.create_task(background_countdown_task())
client.run("你的机器人Token")

关键注意点

  • 更新字段时请使用embed.set_field_at(索引, ...)方法定位原有Timer字段,不要重复调用add_field,否则会在Embed里生成多个重复的Timer字段,打乱排版
  • 不要在倒计时循环里重新构建全新的Embed对象,直接修改原有Embed的字段值再调用edit即可,减少不必要的内存消耗
  • 长时倒计时的计算逻辑用divmod拆分时间差,会自动处理天级的时间溢出问题,不需要额外写跨天判断
  • 如果担心触发Discord的API限频,可以将asyncio.sleep(1)调整为asyncio.sleep(2),在精度和限频风险之间做平衡

内容的提问来源于stack exchange,提问作者ibib4m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 22:06:04