我正在制作一个时间表 Discord.js 机器人,但它没有发送消息
I'm making a schedule Discord.js bot, but it's not sending a message
我正在制作一个 discord.js 调度机器人。我正在为此使用节点计划。它没有抛出任何错误,但仍然没有发送消息。我做错了什么,我该如何摆脱这个问题? (提前致谢)
我的代码是:
const Discord = require('discord.js');
const client = new Discord.Client();
const schedule = require('node-schedule');
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN IS HERE');
const rule = new schedule.RecurrenceRule();
rule.tz = 'EDT';
client.on('message', message => {
if (message.content === '!schedule 9pm meeting') {
message.channel.send('Alright. I will announce it for you, friend! :smiley:');
const job = schedule.scheduleJob('00 21 * * *', function () {
client.channels.cache.get("channel id is here").send("This is a test message. Does it work?");
});
}
});
您不能从 client.on
函数中 运行 schedule.scheduleJob
并期望消息仍然存在。 Discord API 期望在超时前的特定时间内对 webhook 做出响应。
此外,如果机器人 运行 在云服务上,它 运行 所在的节点可能会偶尔重新启动一次,这会弄乱 in-memory 数据,例如附加node-schedule
.
中的 cron 作业
持久化数据
您可能应该得到用户安排的时间并将数据保存在某种数据库中。您应该使用数据库 read\writes 以便在您的云提供商重新启动之间保存数据(除非您有付费订阅)。
有全局 cron 作业或间隔
由于您可能有数千个已安排的会议,因此在您的情况下,最好在特定时间间隔内检查会议并同时发送所有提醒。
假设用户不能给我们一个比特定分钟更具体的时间。然后我们可以每分钟检查一次提醒,知道我们会在会议开始前通知用户。
// Run checkForReminders every 60 seconds to scan DB for outstanding reminders
setInterval(checkForReminders, 60000);
// Parse reminder request, save to DB, DM confirmation to user
client.on('message', (msg) => {
createNewReminder(msg);
});
新提醒处理
const createNewReminder = (msg) => {
const formattedMessage = formatMessage(msg)
// If message isn't a remindme command, cease function execution
if (!formattedMessage.startsWith('!remindme')) {
return
}
// Determine if message contains a number to assign to intervalInteger
checkForNumbersInMessage(formattedMessage)
// Final format for message to be sent at reminderTime
const messageToDeliverToUser = formattedMessage.replace('!remindme', '')
// Set integer and verb values for moment.add() parameters
const intervalInteger = parseInt(checkForNumbersInMessage(formattedMessage))
const intervalVerb = setIntervalVerb(formattedMessage)
// Format time to send reminder to UTC timezone
const reminderTime = moment().utc().add(intervalInteger, intervalVerb).format('YYYY-MM-DD HH:mm:ss')
// Save reminder to DB
saveNewReminder(msg.author.id, msg.author.username, messageToDeliverToUser, reminderTime)
// Send embedded message to author & notify author in channel of remindertime request
const embed = createEmbed(messageToDeliverToUser, reminderTime)
msg.author.send(embed)
msg.channel.send(`${msg.author} - A reminder confirmation has been sent to your DMs. I will DM you again at the requested reminder time`)
}
稍后向公会或用户发送消息
为了稍后发送消息,将 userId
或 guildId
保存到数据库,然后从 discord 客户端检索用户或公会,并发送消息。
const checkForReminders = () => {
db.serialize(() => {
// Select all messages older than the current dateTime
db.each("SELECT id, reminderTime, userID, message FROM reminders WHERE reminderTime < DATETIME()", (error, row) => {
if (error || !row) {
return console.log('Error or no row found')
}
// If reminders are found, fetch userIDs, then send the requested reminder through DM
client.users.fetch(row.userID).then((user) => {
user.send(`Hi, you asked to be reminded "${row.message}" - That's right now!`).catch(console.error)
console.log(`Message delivered: ${row.message}`)
console.log(`Message deleted successfully`)
// Delete message after DMing to user
db.run("DELETE FROM reminders WHERE id = ?", [row.id])
console.log('Message sent and removed successfully')
})
})
})
}
取自 NathanDennis/discord-reminder-bot 的代码示例。查看存储库以获取完整示例。他对自己的代码进行了评论,因此很容易理解。
我正在制作一个 discord.js 调度机器人。我正在为此使用节点计划。它没有抛出任何错误,但仍然没有发送消息。我做错了什么,我该如何摆脱这个问题? (提前致谢)
我的代码是:
const Discord = require('discord.js');
const client = new Discord.Client();
const schedule = require('node-schedule');
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN IS HERE');
const rule = new schedule.RecurrenceRule();
rule.tz = 'EDT';
client.on('message', message => {
if (message.content === '!schedule 9pm meeting') {
message.channel.send('Alright. I will announce it for you, friend! :smiley:');
const job = schedule.scheduleJob('00 21 * * *', function () {
client.channels.cache.get("channel id is here").send("This is a test message. Does it work?");
});
}
});
您不能从 client.on
函数中 运行 schedule.scheduleJob
并期望消息仍然存在。 Discord API 期望在超时前的特定时间内对 webhook 做出响应。
此外,如果机器人 运行 在云服务上,它 运行 所在的节点可能会偶尔重新启动一次,这会弄乱 in-memory 数据,例如附加node-schedule
.
持久化数据
您可能应该得到用户安排的时间并将数据保存在某种数据库中。您应该使用数据库 read\writes 以便在您的云提供商重新启动之间保存数据(除非您有付费订阅)。
有全局 cron 作业或间隔
由于您可能有数千个已安排的会议,因此在您的情况下,最好在特定时间间隔内检查会议并同时发送所有提醒。
假设用户不能给我们一个比特定分钟更具体的时间。然后我们可以每分钟检查一次提醒,知道我们会在会议开始前通知用户。
// Run checkForReminders every 60 seconds to scan DB for outstanding reminders
setInterval(checkForReminders, 60000);
// Parse reminder request, save to DB, DM confirmation to user
client.on('message', (msg) => {
createNewReminder(msg);
});
新提醒处理
const createNewReminder = (msg) => {
const formattedMessage = formatMessage(msg)
// If message isn't a remindme command, cease function execution
if (!formattedMessage.startsWith('!remindme')) {
return
}
// Determine if message contains a number to assign to intervalInteger
checkForNumbersInMessage(formattedMessage)
// Final format for message to be sent at reminderTime
const messageToDeliverToUser = formattedMessage.replace('!remindme', '')
// Set integer and verb values for moment.add() parameters
const intervalInteger = parseInt(checkForNumbersInMessage(formattedMessage))
const intervalVerb = setIntervalVerb(formattedMessage)
// Format time to send reminder to UTC timezone
const reminderTime = moment().utc().add(intervalInteger, intervalVerb).format('YYYY-MM-DD HH:mm:ss')
// Save reminder to DB
saveNewReminder(msg.author.id, msg.author.username, messageToDeliverToUser, reminderTime)
// Send embedded message to author & notify author in channel of remindertime request
const embed = createEmbed(messageToDeliverToUser, reminderTime)
msg.author.send(embed)
msg.channel.send(`${msg.author} - A reminder confirmation has been sent to your DMs. I will DM you again at the requested reminder time`)
}
稍后向公会或用户发送消息
为了稍后发送消息,将 userId
或 guildId
保存到数据库,然后从 discord 客户端检索用户或公会,并发送消息。
const checkForReminders = () => {
db.serialize(() => {
// Select all messages older than the current dateTime
db.each("SELECT id, reminderTime, userID, message FROM reminders WHERE reminderTime < DATETIME()", (error, row) => {
if (error || !row) {
return console.log('Error or no row found')
}
// If reminders are found, fetch userIDs, then send the requested reminder through DM
client.users.fetch(row.userID).then((user) => {
user.send(`Hi, you asked to be reminded "${row.message}" - That's right now!`).catch(console.error)
console.log(`Message delivered: ${row.message}`)
console.log(`Message deleted successfully`)
// Delete message after DMing to user
db.run("DELETE FROM reminders WHERE id = ?", [row.id])
console.log('Message sent and removed successfully')
})
})
})
}
取自 NathanDennis/discord-reminder-bot 的代码示例。查看存储库以获取完整示例。他对自己的代码进行了评论,因此很容易理解。