所以我正在制作一个命令,当用户加入时向频道发送消息,但由于我缓存数据的方式,我无法从主文件访问它。
那么有什么方法可以在使用 Commando 的命令中使用客户端事件,还是我需要找到一种方法来缓存在我的主文件中?
const { CommandoClient } = require("discord.js-commando");
const path = require("path");
const mongo = require("./mongo");
const { token, mongoPath } = require("./config.json");
const cache = {};
const welcomeSchema = require('./models/welcomeSchema')
const client = new CommandoClient({
commandPrefix: ";",
owner: ["769231300472995840", "701561771529470074"],
invite: "https://discord.gg/GJRC4cnU4j",
});
client.registry
.registerDefaultTypes()
.registerGroups([
["moderation", "Moderation Commands"],
["general", "General Commands"],
["misc", "Misc Commands"],
["server-config", "Server Config Commands"],
["economy", "Economy Commands"],
["testing", "Testing Commands"],
])
.registerDefaultGroups()
.registerDefaultCommands()
.registerCommandsIn(path.join(__dirname, "commands"));
client.once("ready", async () => {
console.log(`Logged in as ${client.user.tag}! (${client.user.id})`);
const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
while (0 == 0) {
await delay(10000);
client.user
.setActivity(`${client.guilds.cache.size} servers`, { type: "WATCHING" })
.catch(console.error);
await delay(10000);
client.user.setActivity(`;help`, { type: "WATCHING" }).catch(console.error);
}
});
const onJoin = async (member) => {
const { guild } = member;
let data = cache[guild.id];
if (!data) {
console.log("FETCHING FROM DATABASE");
await mongo().then(async (mongoose) => {
try {
const result = await welcomeSchema.findOne({ _id: guild.id });
cache[guild.id] = data = [result.channelId, result.text];
} finally {
mongoose.connection.close();
}
});
}
const channelId = data[0];
const text = data[1];
const channel = guild.channels.cache.get(channelId);
channel.send(text.replace(/<@>/g, `<@${member.id}>`));
};
client.on('guildMemberAdd', (member) => {
onJoin(member)
})
client.on("error", console.error);
client.login(token);
const { Command } = require('discord.js-commando');
const mongo = require('../../mongo');
const WelcomeSchema = require('../../models/welcomeSchema');
const cache = {}
module.exports = class WelcomeSetCommand extends Command {
constructor(client) {
super(client, {
name: 'setwelcome',
group: 'server-config',
memberName: 'setwelcome',
description: 'A command that sets a welcome message.',
userPermissions: ['ADMINISTRATOR'],
args: [
{
key: 'message',
prompt: 'What do want to say when a new user joins?',
type: 'string'
}
]
})
}
async run (msg, { message }) {
const { channel, guild } = msg;
cache[guild.id] = [channel.id, message]
await mongo().then(async (mongoose) => {
try{
await WelcomeSchema.findOneAndUpdate({
_id: guild.id
}, {
_id: guild.id,
channelId: channel.id,
text: message
}, {
upsert: true
})
} finally{
mongoose.connection.close()
}
})
}
}