Ping Command

Example Ping command using our setup command structure.

Here we will be making an example command for our Discord bot. This command will be an advanced ping command that replies with the latency of our bot, and the message latency.

First thing we want to do is create a new file inside our commands directory. For this example, we will be calling this file ping.js.

We then need to create the structure of our command. We will add this structure now:

const { EmbedBuilder, SlashCommandBuilder } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
  run: async ({ client, interaction }) => {},
};

After the parenthesis in data, we can go ahead and structure our Slash Command data. We will add the following lines:

const { EmbedBuilder, SlashCommandBuilder } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Returns the bot latency."),
  run: async ({ client, interaction }) => {},
};

After doing this we can define our functions for run, so we will add the following lines inside the run parentheses:

const { EmbedBuilder, SlashCommandBuilder } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Returns the bot latency."),
  run: async ({ client, interaction }) => {
    interaction.deferReply();

    const messageReply = await interaction.fetchReply();
    const ping = messageReply.createdTimestamp - interaction.createdTimestamp;

    await interaction.editReply(`Pong 🏓
- Message Ping: ${ping}ms
- Bot Ping: ${client.ws.ping}ms`);
  },
};

This command will defer a reply from the bot, or make it wait for all the command to be completed. It will then subtract the timestamps from each other to get our bot ping.

The ping is returned in milliseconds, but you can always convert it to seconds by dividing your ping variable by 1000.

To do this with the Bot Ping, we need to first save the client.ws.ping value in a variabe, then we can do the same with out ping variable and divide it by 1000.

Last updated