Creating a ping command for a Discord bot

Hey everyone! I’m working on a Discord bot and I want to add a ping command. I’m not sure about the best way to do this.

I was thinking of using the difference between createdAt and the current time. But I’m confused about what createdAt actually represents. Does it show when the user sent the message or when the server got it?

The docs for discord.js aren’t very clear on this. Has anyone implemented a ping command before? What method did you use? Any tips or code snippets would be super helpful!

Here’s a basic structure I’m considering:

client.on('message', message => {
  if (message.content === '!ping') {
    const timeDiff = Date.now() - message.createdTimestamp;
    message.reply(`Pong! Latency is ${timeDiff}ms.`);
  }
});

Is this approach accurate? Or is there a better way to calculate ping? Thanks in advance for any help!

I’ve implemented ping commands in several Discord bots, and your approach is on the right track. However, for more precise latency measurement, I recommend using the WebSocket ping. Here’s an improved version:

client.on('message', message => {
  if (message.content === '!ping') {
    message.channel.send('Pinging...').then(sent => {
      const roundtrip = sent.createdTimestamp - message.createdTimestamp;
      const wsLatency = client.ws.ping;
      sent.edit(`Pong! Roundtrip: ${roundtrip}ms | WebSocket: ${wsLatency}ms`);
    });
  }
});

This method provides both the message roundtrip time and the WebSocket latency, giving users a more comprehensive view of the bot’s responsiveness. The WebSocket ping is generally more stable and reflective of actual network conditions.

hey zack, i’ve done this before! the createdTimestamp is when discord received the msg, not when u sent it. ur approach is fine for a basic ping cmd. if u want more accurate latency, try using client.ws.ping instead. it gives u the websocket heartbeat. hope this helps!

I’ve dabbled with Discord bots, and ping commands can be tricky. Your approach isn’t bad, but it might not give you the most accurate results. In my experience, using the WebSocket ping tends to be more reliable.

Here’s what I’ve found works well:

client.on('message', message => {
  if (message.content === '!ping') {
    const start = Date.now();
    message.channel.send('Pong!').then(m => {
      const latency = Date.now() - start;
      const apiLatency = Math.round(client.ws.ping);
      m.edit(`Pong! Latency: ${latency}ms. API Latency: ${apiLatency}ms`);
    });
  }
});

This method gives you both the message latency and the API latency, which I find more useful. It’s also more accurate because it measures the actual time it takes for the bot to receive and respond to a message. Just remember, network conditions can vary, so you might want to run it a few times to get a good average.