You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py如何编写命令停止正在运行的reminder定时提醒任务

解决方案

核心实现逻辑为用全局字典存储每个用户对应的提醒异步任务,需要停止时直接取消对应任务即可,修改后完整代码如下:

from asyncio import sleep as s, CancelledError

# 全局字典存储用户对应的提醒任务,key为用户ID,value为asyncio.Task对象
user_reminder_tasks = {}

@client.command()
async def reminder(ctx, time: int, *, msg):
    # 如果该用户已有运行中的提醒,先停止之前的
    if ctx.author.id in user_reminder_tasks:
        user_reminder_tasks[ctx.author.id].cancel()
        await ctx.send("已停止您之前运行的提醒任务,将启动新的提醒")
    
    # 定义内部的提醒循环协程
    async def reminder_loop():
        try:
            while True:
                await s(time)
                await ctx.send(f'{msg}, {ctx.author.mention}')
        except CancelledError:
            # 捕获任务取消异常,避免控制台报错
            await ctx.send("您的提醒任务已成功停止")
    
    # 创建任务并存入字典
    task = client.loop.create_task(reminder_loop())
    user_reminder_tasks[ctx.author.id] = task
    await ctx.send(f"已启动提醒,将每隔{time}秒给您发送提醒消息")

@client.command()
async def stop_reminder(ctx):
    if ctx.author.id not in user_reminder_tasks:
        await ctx.send("您当前没有运行中的提醒任务")
        return
    
    # 取消任务并删除存储记录
    user_reminder_tasks[ctx.author.id].cancel()
    del user_reminder_tasks[ctx.author.id]

功能说明

  • 每个用户同一时间仅可运行一个提醒任务,重复调用reminder命令会自动终止旧任务后启动新任务
  • 调用stop_reminder命令即可停止当前用户自己的运行中提醒,不会影响其他用户的任务
  • 代码已内置任务取消异常捕获逻辑,不会在服务端抛出未处理报错

内容的提问来源于stack exchange,提问作者Crazy Jaguar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:45:04