我是使用 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 });
}
},
};
uj5u.com熱心網友回復:
獲取客戶端.client在物件上使用,Interaction在本例中為
const command = interaction.client.commands.get(interaction.commandName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418436.html
標籤:
