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

如何实现Discord命令并以时间戳格式展示消息发送时间?

问题分析与解决方案
  • 问题根源:你定义的message_timestamp是在脚本初始化时就计算好的固定值,并非每次执行/test命令时实时获取的当前时间,所以显示的永远是机器人启动时的时间。

  • 修正方案:将获取时间戳的逻辑移到命令函数内部,确保每次调用命令时都获取当前时间。

修正后的代码:

from datetime import datetime
import discord

@bot.tree.command(name="test", description="test")
async def test(ctx: discord.Interaction):
    # 每次执行命令时实时获取当前时间戳(转成整数适配Discord格式)
    message_timestamp = int(datetime.now().timestamp())
    embed = discord.Embed(title="", description=f"hello world, <t:{message_timestamp}:R>", color=discord.Color.green())
    await ctx.response.send_message(embed=embed)

额外说明:datetime.now().timestamp()返回的是浮点数,Discord的时间戳语法要求传入整数,所以转换为int类型可以避免格式解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:32:07