DiscordJS Ping命令API Ping始终显示-1ms问题求助
Discord.js Ping命令API Ping显示-1ms问题解决
我用Discord.js开发Ping命令时遇到了问题:运行命令后,Bot Ping显示正常,但API Ping始终显示为-1ms。我刚接触JavaScript和Discord.js,找不到问题原因,求帮忙。
相关代码
Ping命令代码
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('See the ping of the bot.'), async execute(interaction) { const embedPinging = new EmbedBuilder() .setTitle(`Ping`) .setDescription(`Pinging...`) .setColor(`#ff00c3`) const sent = await interaction.reply({ embeds: [embedPinging], fetchReply: true }) const embedPing = new EmbedBuilder() .setTitle(`Ping`) .setDescription(` Bot: ${sent.createdTimestamp - interaction.createdTimestamp}ms API: ${interaction.client.ws.ping}ms`) .setColor(`#ff00c3`) interaction.editReply({ embeds: [embedPing] }) }, };
index.js代码
const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, ], }); client.commands = new Collection(); const foldersPath = path.join(__dirname, 'commands'); const commandFolders = fs.readdirSync(foldersPath); for (const folder of commandFolders) { const commandsPath = path.join(foldersPath, folder); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); if ('data' in command && 'execute' in command) { client.commands.set(command.data.name, command); } else { console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); } } } const eventsPath = path.join(__dirname, 'events'); const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js')); for (const file of eventFiles) { const filePath = path.join(eventsPath, file); const event = require(filePath); if (event.once) { client.once(event.name, (...args) => event.execute(...args)); } else { client.on(event.name, (...args) => event.execute(...args)); } } client.login(token);
InteractionCreate事件代码
const { Events } = require('discord.js'); module.exports = { name: Events.InteractionCreate, async execute(interaction) { if (!interaction.isChatInputCommand()) return; const command = interaction.client.commands.get(interaction.commandName); if (!command) { console.error(`No command matching ${interaction.commandName} was found.`); return; } try { await command.execute(interaction); } catch (error) { console.error(`Error executing ${interaction.commandName}`); console.error(error); } }, };
问题原因
你使用的interaction.client.ws.ping是Discord网关的心跳延迟,只有当客户端完全连接到Discord网关后,这个值才会被正确更新。如果机器人刚启动、连接还没稳定,或者网关连接出现临时问题,这个值就会返回-1。
解决方法
有两种可行的修复方式:
方式一:改用REST请求测量API延迟
直接调用Discord API来计算延迟,这种方式更准确,也不会受网关连接状态影响:
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('查看机器人延迟'), async execute(interaction) { const embedPinging = new EmbedBuilder() .setTitle(`Ping`) .setDescription(`正在测试延迟...`) .setColor(`#ff00c3`) const sent = await interaction.reply({ embeds: [embedPinging], fetchReply: true }) // 测量API延迟 const apiStartTime = Date.now(); // 调用Discord API的根端点 await interaction.client.rest.get('/'); const apiPing = Date.now() - apiStartTime; const embedPing = new EmbedBuilder() .setTitle(`Ping`) .setDescription(` Bot延迟: ${sent.createdTimestamp - interaction.createdTimestamp}ms API延迟: ${apiPing}ms`) .setColor(`#ff00c3`) await interaction.editReply({ embeds: [embedPing] }) }, };
方式二:检查网关连接状态
如果坚持要用client.ws.ping,可以先检查值是否为-1,避免显示异常:
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('See the ping of the bot.'), async execute(interaction) { const embedPinging = new EmbedBuilder() .setTitle(`Ping`) .setDescription(`Pinging...`) .setColor(`#ff00c3`) const sent = await interaction.reply({ embeds: [embedPinging], fetchReply: true }) // 检查网关ping值 const wsPing = interaction.client.ws.ping === -1 ? '网关未就绪' : `${interaction.client.ws.ping}ms`; const embedPing = new EmbedBuilder() .setTitle(`Ping`) .setDescription(` Bot: ${sent.createdTimestamp - interaction.createdTimestamp}ms API: ${wsPing}`) .setColor(`#ff00c3`) interaction.editReply({ embeds: [embedPing] }) }, };
内容的提问来源于stack exchange,提问作者Claudia García
相关产品推荐
相关产品推荐

