【问题标题】:Calculate Time Difference Between Two Discord IDs/Snowflakes计算两个 Discord ID/雪花之间的时间差
【发布时间】:2021-10-25 21:01:53
【问题描述】:

timedif 命令采用两个消息 ID 并计算它们发送的时间差,精确到小数点后 2 位。

这是我做的:

@bot.command(name='timedif', help='', aliases=['snowflake', 'timediff'])
async def timedif(ctx, id1, id2):
    try:
        id1 = int(id1)
        id2 = int(id2)
        
    except:
        await ctx.reply("Check your message ID's! They are incorrect!")
    
    msg1 = await ctx.fetch_message(id1)
    msg2 = await ctx.fetch_message(id2)
        
    time1 = msg1.created_at
    time2 = msg2.created_at
    
    ts_diff = time2 - time1
    secs = abs(ts_diff.total_seconds())
    days,secs=divmod(secs,secs_per_day:=60*60*24)
    hrs,secs=divmod(secs,secs_per_hr:=60*60)
    mins,secs=divmod(secs,secs_per_min:=60)
    secs=round(secs, 2)
    answer='{} secs'.format(secs)
    
    if secs > 60:
        answer='{} mins and {} secs'.format(int(mins),secs)
        if mins > 60:
            answer='{} hrs, {} mins and {} secs'.format(int(hrs),int(mins),secs)
            if hrs > 24:
                answer='{} days, {} hrs, {} mins and {} secs'.format(int(days),int(hrs),int(mins),secs)
    
    embed = discord.Embed(title="**Time Difference**", description=f"""IDs: {id1}, {id2}
Time difference between the 2 IDs: 
{answer}""")
    await ctx.reply(embed=embed)

我测试了机器人,但遇到了一个问题: 对于此代码,它只能从与“ctx”相同的通道中获取消息。但是,如果我从另一个频道(即 DM 频道)获取其中一个 ID,则机器人无法访问它。是否有算法/函数可以让我计算 any 2 个 ID 的时间差?我认为这是可能的,因为最近很多机器人都在这样做。

澄清一下:对于来自ctx.channel 的消息,它工作正常并且能够计算时间差异。唯一的问题是它无法从其他渠道获取消息。

【问题讨论】:

  • 您不能从 DM 中获取 ID。此外,请确保您启用了意图。

标签: python discord discord.py


【解决方案1】:

计算任意两个 Discord ID 之间的时间差不需要任何 API 请求。由于每个雪花对象的创建时间都在这 19-21 位数字内编码。以二进制形式读取时,第 22 位及以上为时间戳。

对于最近的 discord.py 版本,已经为您提供了一个辅助方法!

time1 = discord.utils.snowflake_time(int(id1))
time2 = discord.utils.snowflake_time(int(id2))
ts_diff = time2 - time1
secs = abs(ts_diff.total_seconds())

如果您的版本尚不存在此功能,实现snowflake_time() 很简单:

import datetime

def snowflake_time(id):
    return datetime.datetime.utcfromtimestamp(((id >> 22) + 1420070400000) / 1000)

此方法适用于任何 Discord ID(消息 ID、频道 ID、公会 ID、类别 ID、审核日志 ID 等)

Discord 雪花结构:https://discord.com/developers/docs/reference#snowflakes.

【讨论】:

  • 嗨!我试过了,还是不行:discord.ext.commands.errors.CommandInvokeError: Command raise an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
  • @JMuzhen 你好。只需在我的回答中使用第一个代码 sn-p,它不涉及任何 Discord 请求。
  • 所以你需要去掉 msg1 = await ctx.fetch_message(id1)msg2 = await ctx.fetch_message(id2) 行。
  • 好的,谢谢!我做到了,正在等待结果。
  • @JMuzhen 没问题,让我知道它是怎么回事 :) 另外作为旁注,对于您的尝试除外,当 ID 不是时,不要忘记在您的 except 块中“返回”整数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
相关资源
最近更新 更多