如何实现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
相关产品推荐
相关产品推荐

