Latency command in Discord.py
Asked Answered
M

18

9

I've looked in a lot of places and I can't find a way to make a ping (latency) command using discord.py, something like this:

@client.command(pass_context=True)
async def pong(ctx):
    # Somehow find 'pingtime'
    await client.say(pingtime)
Manful answered 19/9, 2017 at 18:1 Comment(2)
What exactly are you attempting to do with this? Do you want the system to post a response as soon as it receives a certain input so that people are aware of their delays to the system or do you want a way to ping external sites from a command issues in discord?Honorable
When a message is sent it would respond with how long it took to get the messageManful
T
20

Really at this point you should be using the rewrite branch of discord.py

This would be my solution using the commands extension.

@bot.command()
async def ping(ctx):
    await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))
Thevenot answered 4/1, 2018 at 8:9 Comment(1)
To get ms multiply bot.latency by 1000.Declination
P
8

On the rewrite branch of discord.py, you can use the following:

@bot.command()
async def ping(ctx):
    await ctx.send(f'My ping is {bot.latency}!')

Of course, you'll need to change bot if you're using a different variable name.

Pelkey answered 25/10, 2019 at 5:22 Comment(1)
The ping will be a floating point. It would be best to round it.Declination
D
5

Use this code

@bot.command(pass_context=True)
async def ping(ctx):
    """ Pong! """
    await delete_message(ctx.message)
    before = time.monotonic()
    message = await ctx.send("Pong!")
    ping = (time.monotonic() - before) * 1000
    await message.edit(content=f"Pong!  `{int(ping)}ms`")
    print(f'Ping {int(ping)}ms')
Duct answered 30/4, 2018 at 15:52 Comment(0)
F
5

There is probably a million better lines of code to use for this but this is what i use

@client.command()
async def ping(ctx):
     await ctx.send(f'Pong! In {round(client.latency * 1000)}ms')
Forwards answered 16/6, 2020 at 10:0 Comment(0)
P
4

Most of the answers for this question don't round the ping, so I wrote a script that does.

Use this:

async def ping(ctx):
    await ctx.send(f'Pong! {round (bot.latency * 1000)} ms')
Pinkiepinkish answered 19/1, 2021 at 20:23 Comment(0)
P
2

This ping command give a response back from how long it took between the bot and discord

import discord 
import time
Client = commands.Bot(commands.when_mentioned_or('...'))


@Client.command(pass_context=True)
async def ping_ms(ctx):
    t = await Client.say('Pong!')
    ms = (t.timestamp-ctx.message.timestamp).total_seconds() * 1000
    await Client.edit_message(t, new_content='Pong! Took: {}ms'.format(int(ms)))
Polariscope answered 11/10, 2018 at 7:10 Comment(0)
R
1
import datetime

@client.command(pass_context=True)
async def ping(ctx):
    now = datetime.datetime.utcnow()
    delta = now - ctx.message.timestamp
    await client.say('{}ms'.format(delta(microseconds=1)))

This won't be super effective, let's be honest, there isn't really a way to test this as you can't run a script clientside to get the time. But this will test the time between your system clock when the script begins and when discord says they got the message. Not really a ping, not in any definition but it will give you a hint if your bot is slowed down.

Renfred answered 26/9, 2017 at 21:0 Comment(4)
Don't forget to import datetimeRenfred
Remember this isn't actually measuring the time the message took to sent, this is measuring the offset between the reported time and when the bot begins to process the response.Renfred
You could alternatively make it; measure the current time, send a message, measure the time of the sent message and compare those two times and send that as a message. Ideally editting the original message.Renfred
Don't copy paste code from Stack Overflow. This wasn't tested, I wrote this on my phone. What's the error?Renfred
P
1

Okay so previously i showed you how to do a simple one. Now i went and made it a bit better And it follows as

Import discord
Import time


@Client.command(pass_context=True)
async def ms_ping(ctx):
channel = ctx.message.channel   
try:
    t1 = time.perf_counter()
    await Client.send_typing(channel)
    ta = t1
    t2 = time.perf_counter()
    await Client.send_typing(channel)
    tb = t2
    ra = round((tb - ta) * 1000)
finally:
    pass
try:
    t1a = time.perf_counter()
    await Client.send_typing(channel)
    ta1 = t1a
    t2a = time.perf_counter()
    await Client.send_typing(channel)
    tb1 = t2a
    ra1 = round((tb1 - ta1) * 1000)
finally:
    pass
try:
    t1b = time.perf_counter()
    await Client.send_typing(channel)
    ta2 = t1b
    t2b = time.perf_counter()
    await Client.send_typing(channel)
    tb2 = t2b
    ra2 = round((tb2 - ta2) * 1000)
finally:
    pass
try:
    t1c = time.perf_counter()
    await Client.send_typing(channel)
    ta3 = t1c

    t2c = time.perf_counter()
    await Client.send_typing(channel)
    tb3 = t2c

    ra3 = round((tb3 - ta3) * 1000)
finally:
    pass
try:
    t1d = time.perf_counter()
    await Client.send_typing(channel)
    ta4 = t1d

    t2d = time.perf_counter()
    await Client.send_typing(channel)
    tb4 = t2d

    ra4 = round((tb4 - ta4) * 1000)
finally:
    pass

e = discord.Embed(title="Connection", colour = 909999)
e.add_field(name='Ping 1', value=str(ra))
e.add_field(name='Ping 2', value=str(ra2))
e.add_field(name='Ping 3', value=str(ra3))
e.add_field(name='Ping 4', value=str(ra4))
await Client.say(embed=e)

Here is the new verion and it is better and it is 100% working because i am using it myself in my bot

Polariscope answered 13/10, 2018 at 7:33 Comment(1)
Guys i ask one thing if you use my content.... Just add an comment in your file saying i helped in a way...... That will make me feel betterPolariscope
P
1

Updated answer for discord.py rewrite:

    async def latency(ctx):
        time_1 = time.perf_counter()
        await ctx.trigger_typing()
        time_2 = time.perf_counter()
        ping = round((time_2-time_1)*1000)
        await ctx.send(f"ping = {ping}")

await ctx.trigger_typing() makes the "Blank" is typing... text appear. By doing this we can semi-accurately get the ping of the bot based on how long it takes the bot to send ctx.trigger_typing(). Of course, you will need to import time and have the whole bot command defined.

Pace answered 15/9, 2019 at 18:39 Comment(0)
F
1

Simple Solution:

This is how to get the Bot's Latency in ms.

round(client.latency * 1000)

Full Code:

@client.command()
async def ping(ctx):
    await ctx.reply(f'Ping is {round(client.latency * 1000)} ms')
Fingerling answered 15/9, 2021 at 23:43 Comment(0)
Q
1

When using discord.app_commands package, this is what I use:

@bot.tree.command(name='ping', description='Pong!')
async def ping(interaction):
    await interaction.response.send_message(f'Pong! ||{round(bot.latency * 1000)}ms||') 
Quartz answered 18/12, 2023 at 12:13 Comment(0)
W
0

Discord.py async not REWRITE

With EMBED

@bot.command(pass_context=True)
async def ping(ctx):
    embed = discord.Embed(title="Pong! :ping_pong:")
    await bot.say(embed=embed)

Without EMBED

@bot.comand(pass_context=True)
async def ping(ctx):
    await bot.say(":ping_pong: Pong!")
Wenger answered 12/1, 2018 at 17:28 Comment(0)
E
0

you can use message.author.mention. For an example (this may not be how you code using async):

await client.send_message(message.channel, str(message.author.mention))

Just a basic example :D

Ectosarc answered 15/5, 2018 at 0:29 Comment(0)
C
0
@client.command(pass_context=True)
    async def ping(ctx):
        """Shows the Client Latency."""
        t = await client.say('Pong!')
        ms = (t.timestamp-ctx.message.timestamp).total_seconds() * 1000
        await client.edit_message(t, new_content='Pong! Client Latency: {}ms'.format(int(ms)))
Cogitable answered 9/5, 2019 at 6:14 Comment(0)
M
0
@client.command() #ping
async def ping(ctx):
    await ctx.send(f'Pong! In {round(client.latency * 1000)}ms')
Mirellamirelle answered 24/11, 2020 at 7:36 Comment(2)
Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Sinus
This code is 100% the same from Wild_Loli (https://mcmap.net/q/1116190/-latency-command-in-discord-py) except you have the ping command...Curio
T
0

The way I do it is just to get an average latency.

tests = 500 #the amount of tests to conduct
latency_list = [] #this is where the tests go
for x in range(tests): #this is the loop
    latency = client.latency() #this gathers the latency
    latency_list.append(latency) #puts the latency in the list
lavg = sum(latency_list)/test #averages the list out
print(lavg)

Although, the real star of the show is client.latency(), but I suggest using the code above.

Totter answered 1/12, 2020 at 0:31 Comment(0)
S
0

Umm insted of doing all that you could do something like the code bellow

@bot.command()
async def ping(ctx):
            await ctx.send(f"pong! my latency is {str(len(bot.latency))}")
Sherborn answered 24/12, 2020 at 9:2 Comment(0)
C
0
@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong! `{bot.latency * 1000}`ms')
Curet answered 15/1, 2021 at 6:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.