How to measure a Discord user's latency with a Python bot?

Hey everyone! I’m working on a Discord bot using Python and I’m stuck on something. Right now, my bot can check the ping to Google, but it’s only showing the ping from the computer where the bot is running. Not very useful, right?

I need the ping for the user who types the command. So, instead of the bot running on my machine, it should ideally grab the user’s ping. I’ve even tried using a ping snippet that uses subprocess, similar to this new version:

import subprocess

def check_ping(target='google.com'):
    result = subprocess.run(['ping', '-c', '1', target], capture_output=True, text=True)
    return result.stdout

But the code still runs on my side. Is there any method to execute this command on the user’s end? If not, can someone explain why that’s the case and suggest alternatives? Thanks for any guidance you can offer!

As someone who’s dabbled in Discord bot development, I can tell you that getting a user’s direct ping isn’t feasible. Discord’s architecture doesn’t allow bots to execute code on users’ machines - it’s a security measure.

However, there’s a workaround that might serve your purpose. You could implement a round-trip time measurement. When a user issues a command, have your bot immediately respond with a message, then edit that message with the time difference.

Here’s a rough idea:

@bot.command()
async def pingme(ctx):
    start_time = time.time()
    message = await ctx.send('Calculating ping...')
    end_time = time.time()
    await message.edit(content=f'Pong! Latency: {(end_time - start_time) * 1000:.2f}ms')

This method isn’t perfect, but it gives a decent approximation of the user’s latency to Discord’s servers. It’s more relevant than the bot’s ping to Google, at least.

hey swiftcoder42, i dont think u can get the user’s ping directly from their machine. discord bots run on ur server, not the user’s pc. maybe u could measure the time between when a user sends a message and when ur bot receives it? that might give u a rough idea of their latency.

I understand your desire to measure user latency, but unfortunately, what you’re trying to achieve isn’t possible through a Discord bot. The bot operates on the server side, not on individual users’ machines, meaning you can’t execute commands on their computers for security reasons.

An alternative is to use Discord’s API to measure the websocket heartbeat, which approximates the latency between the bot and Discord’s servers. While it isn’t a direct measurement of user ping, it provides useful insight into the connection quality. For example, you could implement this by calculating the latency as follows:

latency = bot.latency * 1000
await ctx.send(f'Ping: {latency:.2f}ms')