我做了一个Discord机器人,我希望它能够检查当前日期,如果当前日期是用户生日中的任何一个,它将标记他们并说生日快乐。我已经尝试使用Node.js的日期,例如
if(Date === "this or that")
但这似乎不起作用。因此,我需要帮助的是:
因为我们生日不多,所以我可能会硬编码所有生日(我知道这不是一个好习惯,但是我只是希望现在可以工作,以后可以完善)
如果有人可以帮助我,那就太好了。
这是我的index.js文件的外观(如果相关):
const discord = require("discord.js");
const config = require("./config.json");
const client = new discord.Client();
const prefix = '>';
const fs = require('fs');
const { time, debug } = require("console");
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);
}
client.once('ready', () =>
{
console.log(`${client.user.username} is online`);
})
client.on('message', message =>
{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
if(command === 'ping')
{
client.commands.get('ping').execute(message, args);
}else if(command === 'wololo')
{
client.commands.get('wololo').execute(message, args);
}
})
client.login('TOKEN')
编辑:
我知道我在“ client.on('message',message => {})”中写了“ if(date)”语句,因此除非您在特定时间写了一条命令,否则显然不会检查。我要使用什么功能?
您可以在此处查看Discord.js事件的完整列表。
Discord.js中没有基于计划的时间触发的内置事件。
为此,您可以构建一个时间系统,根据超时或间隔每天触发事件。或者...您可以使用诸如node-cron之类的库来为您执行此操作。
我将尝试举例说明您可以使用上述node-cron做到这一点的方法。
首先,您需要使用node-cron软件包,因此可以npm
像对discord.js本身一样使用。因此,在终端上粘贴并执行以下命令:
npm install node-cron
不幸的是,Discord.js无法为您提供获取用户生日日期的方法。因此,对生日进行硬编码(如您所说的还可以),对于本示例,您将发送祝贺消息的通用频道ID也可以这样:
const Discord = require('discord.js');
const cron = require('node-cron');
const client = new Discord.Client();
// Hard Coded Storing Birthdays in a Map
// With the key beeing the user ID
// And the value a simplified date object
const birthdays = new Map();
birthdays.set('User 1 Birthday Id', { month: 'Jan', day: 26 });
birthdays.set('User 2 Birthday Id', { month: 'Jun', day: 13 });
birthdays.set('User 3 Birthday Id', { month: 'Aug', day: 17 });
const setSchedules = () => {
// Fetch the general channel that you'll send the birthday message
const general = client.channels.cache.get('Your General Channels Id Go Here');
// For every birthday
birthdays.forEach((birthday, userId) => {
// Define the user object of the user Id
const user = client.users.cache.get(userId);
// Create a cron schedule
cron.schedule(`* * ${birthday.day} ${birthday.month} *`, () => {
general.send(`Today's ${user.toString()} birthday, congratulations!`);
});
});
};
client.on('ready', setSchedules);
client.login('Your Token Goes Here');
这不是经过优化的,只是打算给出如何实现的总体思路。请注意,尽管应该在设置任务之前实例化客户端,所以我建议像本例一样进行操作,并安排好计划。
无论如何,您始终可以使用已创建并经过测试的bot,例如Birthday Bot。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句