如何开发支持定时器指令的机器人?实现!timing命令触发@用户定时提醒功能的方法
Alright, let's tackle this timer command feature for your bot. I'll walk you through the core logic and provide a concrete example using Python with discord.py (one of the most popular bot frameworks), but the concepts apply to other platforms/languages too.
1. Parse & Validate the Timer Command
First, you need to listen for the !timing command and extract the time string in HH:MM:SS format. Use regex to validate the input format, then convert it into total seconds for scheduling.
- Handle invalid inputs (e.g., non-numeric values, wrong format) by sending a friendly error message back to the user.
2. Track Active Timers
Store details about each timer: the user who created it, the channel to send the reminder, and the scheduled task itself. For small bots, an in-memory dictionary works; for persistence across restarts, use a lightweight database like SQLite or Redis.
3. Schedule the Reminder
Use an asynchronous scheduler (critical for bot performance—you don't want to block the main thread) to wait the specified duration, then trigger the reminder. In async frameworks like discord.py, asyncio.sleep() is perfect for this.
4. Send the Targeted Reminder
Once the timer elapses, send a message mentioning the user directly using their mention tag (so they get a notification).
import discord from discord.ext import commands import asyncio import re # Initialize bot with required intents bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # In-memory storage for active timers: {task_object: (user_id, channel_id)} active_timers = {} @bot.command(name='timing') async def set_timer(ctx, time_str: str): # Validate HH:MM:SS format with regex time_pattern = re.compile(r'^(\d{2}):(\d{2}):(\d{2})$') match = time_pattern.match(time_str) if not match: await ctx.send("Oops, wrong format! Use `!timing 00:00:00`—for example, `!timing 00:05:30` sets a 5-minute 30-second timer.") return # Convert time components to total seconds hours, minutes, seconds = map(int, match.groups()) total_seconds = hours * 3600 + minutes * 60 + seconds if total_seconds <= 0: await ctx.send("Timer duration must be greater than 0 seconds!") return # Define the async reminder task async def send_reminder(): await asyncio.sleep(total_seconds) # Mention the user and send the reminder await ctx.send(f"{ctx.author.mention} 你设置的闹钟时间已到!") # Clean up the timer from storage del active_timers[current_task] # Start the task and track it current_task = asyncio.create_task(send_reminder()) active_timers[current_task] = (ctx.author.id, ctx.channel.id) await ctx.send(f"Timer set! I'll remind you in **{time_str}**.") @bot.event async def on_ready(): print(f"Logged in as {bot.user} (ID: {bot.user.id})") print("------") # Replace with your bot token bot.run("YOUR_BOT_TOKEN_HERE")
- Persistence: If you want timers to survive bot restarts, save timer details (user ID, channel ID, trigger timestamp) to a database. On startup, calculate remaining time for each unfinished timer and reschedule it.
- Cancel Timer: Add a
!canceltimercommand that lets users cancel their active timers. Iterate throughactive_timersto find tasks linked to the user's ID, cancel the task, and remove it from storage. - Timezone Support: If users want to set timers for specific wall-clock times (e.g.,
!timing 08:00:00for tomorrow morning), use thedatetimemodule to calculate the difference between the target time and current time (accounting for timezones). - Error Handling: Wrap the reminder message in a try/except block to handle cases where the bot can't send messages (e.g., kicked from the channel, missing permissions).
内容的提问来源于stack exchange,提问作者Paper

