J Muzhen
J Muzhen

Reputation: 352

Calculate Time Difference Between Two Discord IDs/Snowflakes

The command timedif takes two message IDs and calculates the difference in time that they were sent, accurate to 2 decimal places.

This is what I have made:

@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)

I tested the bot but I encountered a problem: For this code, it can only fetch messages from the same channel as ‘ctx’. But if I am taking one of the IDs from another channel (ie. a DM channel), the bot cannot access it. Is there an algorithm/function that allows me to calculate the time difference of any 2 ID’s? I think it’s possible as a lot of bots have been doing it recently.

To clarify: for messages from ctx.channel, it works fine and is able to calculate the time diff. The only problem lies in it not able to fetch messages from other channels.

Upvotes: 3

Views: 2308

Answers (1)

Taku
Taku

Reputation: 33754

Calculating the time difference between any two Discord IDs doesn't require any API requests. Since the creation time of every snowflake object is encoded within that 19-21 digits. When read in binary, bit 22 and up is the timestamp.

For recent discord.py versions, there's already a helper method for you!

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

If this doesn't exist for your version yet, it's simple to implement snowflake_time():

import datetime

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

This method works for any Discord ID (message ID, channel ID, guild ID, category ID, audit log ID, etc)

Discord Snowflake Structure: https://discord.com/developers/docs/reference#snowflakes.

Upvotes: 2

Related Questions