如何让JavaScript开发的Bot每日定时发消息并5小时后自动删除?
Hey there! Let's tackle those two bot features you need for your gaming guild—sounds like a fun little project to keep your community engaged. I'll walk you through implementing both using Discord.js v14 (the latest stable version) since it's the go-to library for Discord bot development.
1. Send a Message to a Specific Channel & Delete It After a Delay
This is straightforward with Discord.js's built-in methods and JavaScript's setTimeout function. Here's a reusable function you can drop into your code:
// Make sure your client is properly initialized and logged in first async function sendAndDeleteMessage(channelId, messageContent, delayMs) { try { // Fetch the target channel const channel = await client.channels.fetch(channelId); // Validate the channel is a text-based one if (!channel || !channel.isTextBased()) { console.error("Oops, that's not a valid text channel!"); return; } // Send the message const sentMessage = await channel.send(messageContent); // Schedule deletion after the specified delay setTimeout(() => { sentMessage.delete().catch(err => { console.error("Failed to delete message:", err); }); }, delayMs); } catch (err) { console.error("Something went wrong sending the message:", err); } } // Example usage: Send a message to channel ID "123456789" and delete after 10 minutes (600000 ms) sendAndDeleteMessage("123456789", "Reminder: Guild raid starts in 30 minutes! This message will vanish in 10 mins.", 600000);
Key Notes:
- Ensure your bot has the
SendMessagesandManageMessagespermissions in the target channel. - The
delayMsparameter is in milliseconds (e.g., 300000 = 5 minutes). - Error handling is included to catch issues like invalid channel IDs or missing permissions.
2. Daily Scheduled Message with Auto-Deletion After 5 Hours
For daily timing, using setInterval can lead to drift over time, so we'll use the reliable node-schedule library. First, install it:
npm install node-schedule
Then use this code to set up your daily task:
const schedule = require('node-schedule'); async function scheduleDailyMessage(channelId, messageContent, targetTime, deleteAfterHours = 5) { try { // Parse the target time (format: "HH:MM", e.g., "20:00" for 8 PM) const [hours, minutes] = targetTime.split(':').map(Number); // Create a recurrence rule for daily at the specified time const dailyRule = new schedule.RecurrenceRule(); dailyRule.hour = hours; dailyRule.minute = minutes; // Optional: Set a timezone if needed (e.g., "Europe/London") // dailyRule.tz = "Your/Timezone"; // Schedule the daily job schedule.scheduleJob(dailyRule, async () => { const channel = await client.channels.fetch(channelId); if (!channel || !channel.isTextBased()) { console.error("Invalid channel for daily message!"); return; } const sentMessage = await channel.send(messageContent); // Schedule deletion after 5 hours (convert to milliseconds) const deleteDelay = deleteAfterHours * 60 * 60 * 1000; setTimeout(() => { sentMessage.delete().catch(err => { console.error("Failed to delete daily message:", err); }); }, deleteDelay); console.log("Daily message sent successfully!"); }); console.log(`Daily message scheduled for every day at ${targetTime}!`); } catch (err) { console.error("Error setting up daily schedule:", err); } } // Example usage: Send a daily morning message at 9 AM, delete after 5 hours scheduleDailyMessage( "123456789", "Good morning, guild! Don't forget to claim your daily rewards. This message will be removed at 2 PM.", "09:00" );
Key Notes:
- If your bot restarts, the scheduled job will reset. For a hobby project, using a process manager like
pm2to auto-restart your bot (and reinitialize the schedule) is a simple fix. - Double-check the timezone if your guild is in a specific region—this ensures the message sends at the correct local time.
- Again, confirm the bot has
SendMessagesandManageMessagespermissions in the target channel.
If you run into specific snags (like permission errors or schedule timing issues), feel free to share more details and I can help troubleshoot further!
内容的提问来源于stack exchange,提问作者Felinephenom

