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

如何在discord.py的asyncio.sleep()期间实现倒计时显示?

实现两种倒计时展示(discord.py Cog版)

一、逐行输出「X秒剩余」

这种方式会每隔1秒发送一条新消息,清晰展示剩余时间,同时满足延迟5秒后执行成员移动的需求。

修正后的完整代码:

import asyncio
from discord.ext import commands

class YourCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def count_down_line(self, ctx, seconds):
        # 从指定秒数倒数到1,逐行发送消息
        for i in range(seconds, 0, -1):
            await ctx.send(f"{i}秒剩余")
            await asyncio.sleep(1)

    @commands.command()
    async def gather(self, ctx):
        # 假设你已经定义了lobby_vc和members变量
        if ctx.author.voice and ctx.author.voice.channel != lobby_vc:
            # 执行倒计时,完成后再移动成员
            await self.count_down_line(ctx, 5)
            for member in members:
                await member.move_to(lobby_vc)
        else:
            await ctx.send('已经在集合频道了')

async def setup(bot):
    await bot.add_cog(YourCog(bot))

二、覆盖上一条消息实时更新剩余秒数

这种方式不会刷屏,通过编辑同一条消息来实时更新剩余时间,体验更简洁。

修正后的完整代码:

import asyncio
from discord.ext import commands

class YourCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def count_down_update(self, ctx, seconds):
        # 发送初始倒计时消息
        msg = await ctx.send(f"{seconds}秒剩余")
        # 倒数更新消息内容
        for i in range(seconds-1, 0, -1):
            await asyncio.sleep(1)
            await msg.edit(content=f"{i}秒剩余")
        # 倒计时结束后提示完成
        await asyncio.sleep(1)
        await msg.edit(content="倒计时结束,开始移动成员!")

    @commands.command()
    async def gather(self, ctx):
        if ctx.author.voice and ctx.author.voice.channel != lobby_vc:
            await self.count_down_update(ctx, 5)
            for member in members:
                await member.move_to(lobby_vc)
        else:
            await ctx.send('已经在集合频道了')

async def setup(bot):
    await bot.add_cog(YourCog(bot))

关键修正说明

  • 修复range参数错误:原有代码range(4,0)不会生成任何数值,改为range(seconds, 0, -1)才能实现从指定秒数倒数到1的逻辑。
  • 增加语音状态判断:先检查ctx.author.voice是否存在,避免用户未进入语音频道时触发AttributeError。
  • 权限提示:确保机器人拥有发送/编辑消息、移动语音频道成员的对应权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:20:37