我在这里需要帮助,老实说不知道我哪里出错了,这里是完整的代码。我是新手,只是试图在消息中恢复提及用户和原因,而不是对这些信息做任何事情。
const { client, MessageEmbed } = require('discord.js');
const { prefix } = require("../config.json");
module.exports = {
name: "report",
description: "This command allows you to report a user for smurfing.",
catefory: "misc",
usage: "To report a player, do $report <discord name> <reason>",
async execute(message, client){
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<@') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
const offender = getUserFromMention(args[0]);
if (args.length < 2) {
return message.reply('Please mention the user you want to report and specify a reason.');
}
const reason = args.slice(1).join(' ');
message.reply("You reported",offender,"for reason:", reason)
}
}
如果我不提,我会得到 this
如果我提一下 this 我收到上述错误但没有反应。
(node:4044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
Index.js:
const fs = require('fs');
const Discord = require("discord.js");
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.prefix = prefix;
client.commands = new Discord.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.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.login(token);
答案 0 :(得分:0)
如果您已经在根文件中启动了一个新的客户端实例,为什么还要在命令文件中调用客户端?尝试从代码顶部删除客户端。希望有效
答案 1 :(得分:0)
您不必创建函数来从消息中获取提及,您可以使用 Message.mentions property 来获取提及,查看文档以获取有关它的其他信息。 这应该可以解决您的问题。
const { prefix } = require("../config.json");
module.exports = {
name: "report",
description: "This command allows you to report a user for smurfing.",
catefory: "misc",
usage: "To report a player, do $report <discord name> <reason>",
async execute(message, client) {
const args = message.content.slice(1).trim().split(/ +/);
const offender = message.mentions.users.first();
// users is a collection, so we use the first method to get the first element
// Docs: https://discord.js.org/#/docs/collection/master/class/Collection
if (args.length < 2 || !offender.username) {
return message.reply('Please mention the user you want to report and specify a reason.');
}
const reason = args.slice(1).join(' ');
message.reply(`You reported ${offender} for reason: ${reason}`);
}
}