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

如何用函数中断Discord.py 1.7.3计时器的while循环

问题原因及解决方案

核心问题分析

  1. 同步阻塞导致事件循环卡住:time.sleep(1)是同步阻塞函数,调用后会完全占用Discord.py的事件循环,导致机器人无法响应任何其他命令(包括!stop),直到循环强制结束。
  2. 变量作用域与命名错误:start命令内的isCounting = True创建的是局部变量,并未修改全局的isCounting;stop命令里写错了变量名(turnoAttivo应为isCounting),且同样未操作全局变量。

修复后的代码

import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix='!', intents=intents)

isCounting = False

@client.event
async def on_ready():
    print("The bot logged on")
    print("-----------------")

@client.command()
async def start(ctx):
    global isCounting
    if isCounting:
        await ctx.send("计时器已经在运行中")
        return
    await ctx.send("Stopwatch Started")
    isCounting = True
    seconds = 0
    while isCounting:
        seconds += 1
        print(seconds)
        # 使用异步sleep,不阻塞事件循环
        await asyncio.sleep(1)
    await ctx.send(f"计时器停止,总时长:{seconds}秒")

@client.command()
async def stop(ctx):
    global isCounting
    if not isCounting:
        await ctx.send("没有正在运行的计时器")
        return
    isCounting = False
    await ctx.send("The stopwatch Stopped")

# 替换为你的机器人Token
client.run("YOUR_BOT_TOKEN")

关键修改点

  • 替换同步sleep为异步sleep:用await asyncio.sleep(1)替代time.sleep(1),让事件循环在等待时能处理其他命令请求。
  • 修正变量作用域:在start和stop命令中添加global isCounting,确保操作的是全局状态变量。
  • 修复变量名错误:将stop命令内的turnoAttivo改为isCounting,匹配全局变量名。
  • 添加状态判断:避免重复启动计时器或停止未运行的计时器,提升交互合理性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:18:09