You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pycord的Embed消息中添加时间戳?

解决Discord Embed日志添加时间戳的问题

要让Embed底部显示「bot_name • 今天晚上10:48」这样的格式,你可以通过格式化消息发送时间并拼接到footer文本中来实现,具体修改如下:

修改后的代码

import datetime
import discord

@bot.event
async def on_message(ctx):
    if ctx.author.bot:
        return
    
    log_msg = bot.get_channel(1023451687857442828)
    # 处理时间格式,区分今日和非今日
    today = datetime.date.today()
    msg_date = ctx.created_at.date()
    
    if msg_date == today:
        # 今日消息显示「今天上午/晚上XX:XX」
        time_segment = "上午" if ctx.created_at.hour < 12 else "晚上"
        time_str = f"今天{time_segment}{ctx.created_at.strftime('%I:%M')}"
    else:
        # 非今日显示完整日期和时段
        time_segment = "上午" if ctx.created_at.hour < 12 else "晚上"
        time_str = f"{ctx.created_at.strftime('%Y年%m月%d日')} {time_segment}{ctx.created_at.strftime('%I:%M')}"
    
    embed = discord.Embed(
        title="消息发送日志",
        description=f"""该消息由{ctx.author.mention}发送于{ctx.channel}
**消息内容:** "{ctx.content}" """,
        color=discord.Colour.green(),
    )
    embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar.url)
    # 拼接bot名称和时间作为footer文本
    embed.set_footer(text=f"bot_name • {time_str}")
    await log_msg.send(embed=embed)

关键说明

  • 时间格式化逻辑:通过ctx.created_at获取消息发送时间,判断是否为当日,分别生成对应格式的中文时间字符串
  • Footer拼接:将bot名称与格式化后的时间用「•」连接,直接设置到Embed的footer中
  • 细节优化:通过小时数判断时段(上午/晚上),让时间显示更贴合中文用户习惯

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:45:46