【发布时间】:2021-12-06 23:43:52
【问题描述】:
我正在尝试为我的 discord 机器人创建一个 ping 命令。我的代码看起来很简单:
index.js:
require("dotenv").config();
const { Client, Intents, Collection } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const fs = require("fs");
client.commands = new Collection();
const commandFiles = fs
.readdirSync("./commands")
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
const eventFiles = fs
.readdirSync("./events")
.filter((file) => file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
client.on("interactionCreate", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);
messageCreate.js:
require("dotenv").config();
module.exports = {
name: "messageCreate",
on: true,
async execute(msg, client) {
// If message author is a bot, or the message doesn't start with the prefix, return.
if (msg.author.bot || !msg.content.startsWith(process.env.PREFIX)) return;
var command = msg.content.substring(1).split(" ")[0].toLowerCase();
// Remove the command from the args
var args = msg.content.substring().split(/(?<=^\S+)\s/)[1];
if (!client.commands.has(command)) return;
try {
await client.commands.get(command).execute(msg, args, client);
} catch (error) {
console.error(error);
await msg.reply({
content: "Error: Please check console for error(s)",
ephemeral: true,
});
}
},
};
ping.js:
const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(msg, args, client, interaction) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("???? Pong!")
.setDescription(
`Latency is ${
Date.now() - msg.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};
我正在传递我的 msg 参数,为什么它无法识别 ping.js 中的 msg.createdTimestamp?编辑:我更新了一些代码,更新了参数传递的方式。现在我的 ping.js 文件中出现 TypeError: Cannot read properties of undefined (reading 'reply') 错误。
【问题讨论】:
-
因为您将
args作为第二个参数传递,而不是msg。查看execute(msg, args)和execute(interaction, msg, client)之间的区别。 -
@ZsoltMeszaros 所以我更新了一些代码来解决你指出的问题,现在我从 ping.js 收到了一个
Cannot read properties of undefined (reading 'reply')错误。有什么想法吗? -
您可能忘记将交互传递给正确的参数。
-
@koloml 在我不必将交互作为参数传递给 ping 之前。如果我尝试将其添加为参数,则会收到“未定义交互”错误。我添加了我的 index.js 文件,以便您了解每个部分。
标签: javascript discord.js