Trouble with Discord.js Ping Numbers
Asked Answered
M

6

6

So I recently decided to make a Discord bot, and had been going through some tutorials with no problem. However, when I tried to make a ping command (you know, the kind that says "Your ping is 137 ms"), I got numbers that didn't make sense.

Numbers such as -627 ms, 32 ms, 1001 ms, -10 ms, 238 ms. Basically anything and everything between -1000 and 1000.

Now correct me if I'm wrong, but I'm pretty sure that getting negative numbers means I'm sending the response before I even ask for it, and I'm almost certain I didn't write a precognitive bot :P

I spent some time online looking for a reason why I was getting strange ping numbers, but I came up with zilch. I thought to myself, "Hmmmm..... maybe I'm generating them wrong." So I looked at how other people generated their numbers with discord.js...

...aaaand I hit a wall. As far as I can tell, no one has ever tried generating ping numbers with discord.js. If they have, they haven't shared their precious findings online. At least, that's what it looks like to me. (if you have a link to such a tutorial or post, please send it to me)

I'm generating the numbers with ${Date.now() - message.createdTimestamp} This is the only way I have found to generate them, so if anyone has a better method, I would love to see it.

That snippet fits right in with the rest of my code (and yes, it is a very boring bot):

const Discord = require('discord.js');
const client = new Discord.Client();
const token = require('./token.json').token;

client.on('ready', () => {
    console.log('Bot is up and running!');
});

var prefix = "?"

client.on('message', message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;

    if (message.content.startsWith(prefix + 'ping')) {
        message.channel.sendMessage('Pong! Your ping is `' + `${Date.now() - message.createdTimestamp}` + ' ms`');
    }
});

client.login(token);

If anybody could give me a reason why I'm getting negative numbers, or give me a better way to generate them, I would be extremely grateful. Thanks in advance.

Maurist answered 19/4, 2017 at 17:6 Comment(0)
S
2

The variation in ping you're experiencing is due to the variation between between your clock and the remote clock as well as the message id's used to calculate the timestamp not being all that accurate.

Before you jump to one meaning for ping you have to decide what you want to measure. If you're looking to measure the round trip time to send a message and get that same message back frond discord, you could potentially send a discord message, start a timer. then when the promise resolves check how much time has passed.

You could also use .ping as suggested in another answer for the heartbeat ping.

You could also ping the api endpoint though you would probably only be measuring your delay to cloudflare...

Spinode answered 24/4, 2017 at 11:19 Comment(0)
E
1

You may getting different results, because the Date.now is based on your computer's clock and message.createdTimestamp comes from Discord server (not your computer) clock.

The reason nobody's sharing the ping feature is because it's just reading a client object property client.ws.ping.

https://discord.js.org/#/docs/main/stable/class/WebSocketManager?scrollTo=ping

Emblazonment answered 24/4, 2017 at 1:3 Comment(0)
H
1

You can not get the actual ping of another user. But you can get pretty close.

You know that using the system's clock won't work for you because it's out of sync with the actual server.

Your bot can send a message and edit it after that. Then you have two timestamps:

var resMsg = await msg.channel.send('Ping is being appreciated... :bar_chart:');
    resMsg.edit('Ping: ' + Math.round((resMsg.createdTimestamp - msg.createdTimestamp) - client.ws.ping))); //client.ping has been moved to the WebSocketManager under client.ws.ping

Subtracting the ping of the bot will remove it's latency to the API while submitting the message.

Hope I could help!

Hypothalamus answered 3/2, 2019 at 21:6 Comment(0)
S
0

Try this:

client.on('message', message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + 'ping')) {
    msg.channel.send({embed: {
        color: 0x2ed32e,
        fields: [{
            name: "Pong",
            value: "My Ping: " + Math.round(client.ws.ping) + ' ms' //client.ping has been moved to the WebSocketManager under client.ws.ping
      }
     ],
}
})
}})

I hope this will help c:

Solubility answered 23/11, 2018 at 16:21 Comment(0)
G
0
client.on('messageCreate', message => {
if (message.content === `${config.PREFIX}ping`) {
    message.channel.send("Calculating ...").then(m =>{
        var ping = Math.round((m.createdTimestamp - client.ws.ping) - message.createdTimestamp ); //more closer to discord ping
        setTimeout(() => {
            m.edit(`**Your Ping Is: **${ping}ms`);
        }, 3000);
    });
}) //DISCORD.JS V13
Garrulous answered 22/11, 2021 at 20:3 Comment(0)
H
-2

I'm sorry that you're facing this issue with your Discord bot. I used your code to analyse the issue and have come up with this solution. You see how you have:

${Date.now() - message.createdTimestamp}

Well, all you have to do is swap around "Date.now()" and "message.createdTimestamp" around

What you will achieve from this is:

${message.createdTimestamp - Date.now()}

I tried this method, and it worked fine. It gave me the most accurate results.

Hope this answer helped you!

Hypothec answered 4/3, 2018 at 3:48 Comment(1)
This won't work because the timestamp returned by discord could be different from your server's because of timezones.Factional

© 2022 - 2024 — McMap. All rights reserved.