【发布时间】:2022-01-22 02:41:08
【问题描述】:
我是使用 Discord.js 的新手,在浏览了基本指南/文档后,我仍然对如何允许事件和/或命令文件访问主客户端实例感到困惑。例如,我可能想在事件文件中调用 client.database 以使用 CRUD 操作。
我自己进行了一些挖掘,我看到有人通过删除每个事件文件中的 .execute 函数并将 event.bind(null, client) 传递给 client.on( )。不过我不是很明白:
https://github.com/KSJaay/Alita/blob/fe2faf3c684227e29fdef228adaae2ee1c87065b/Alita.js https://github.com/KSJaay/Alita/blob/master/Events/guildMemberRemove.js
我的主文件:
require("dotenv").config();
const fs = require('fs');
util = require('util');
readdir = util.promisify(fs.readdir);
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const mongoose = require('mongoose');
client.events = new Collection();
client.commands = new Collection();
//client.database = require('./src/db/index.js')
async function init() {
const eventFiles = fs.readdirSync('./src/discord/events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
const eventName = file.split(".")[0];
if (event.once) {
client.once(eventName, (...args) => event.execute(...args));
} else {
client.on(eventName, (...args) => event.execute(...args));
}
}
const commandFiles = await readdir('./src/discord/commands')
commandFiles.filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
mongoose.connect(process.env.DB_CONNECT, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB')
}).catch((err) => {
console.log('Unable to connect to MongoDB Database.\nError: ' + err)
})
await client.login(process.env.TOKEN);
}
init();
我的示例活动:
module.exports = {
name: 'interactionCreate',
async execute(interaction) {
console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
},
};
【问题讨论】:
标签: javascript node.js discord.js