您不能schedule.scheduleJob
在函数内部运行 fromclient.on
并期望消息仍然存在。Discord API 期望在超时之前的特定时间内对 webhook 做出响应。
此外,如果机器人在云服务上运行,它运行的节点可能会偶尔重新启动,这会弄乱内存中的数据,例如将 cron 作业附加到node-schedule
.
持久化数据
您可能应该得到用户的预定时间并将数据保存在某种数据库中。您应该使用数据库读\写来保存云提供商重启之间的数据(除非您有付费订阅)。
有一个全局 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 的代码示例。查看存储库以获取完整示例。他评论了他的代码,所以很容易理解。