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

如何用discord.py编写支持时分秒输入与显示的计时器命令?

Discord.py 计时器命令改造:支持时分秒显示

改造后完整代码

import re
import asyncio
from discord.ext import commands

@client.command()
async def timer(ctx, *, time_input):
    try:
        # 解析带单位的时间输入,支持h(小时)/m(分钟)/s(秒),无后缀默认秒
        time_units = {'h': 3600, 'm': 60, 's': 1}
        total_seconds = sum(int(num) * time_units[unit if unit else 's'] 
                           for num, unit in re.findall(r'(\d+)\s?(h|m|s)?', time_input))
        
        # 时间范围校验
        if total_seconds > 86400:
            await ctx.send("我不会给你设置超过一天的计时器!")
            return
        if total_seconds <= 0:
            await ctx.send("我可没法回到过去,输入正数时间!")
            return
        
        # 将总秒数格式化为时分秒的友好字符串
        def format_time(sec):
            hours = sec // 3600
            minutes = (sec % 3600) // 60
            seconds = sec % 60
            parts = []
            if hours > 0:
                parts.append(f"{hours}小时")
            if minutes > 0:
                parts.append(f"{minutes}分钟")
            if seconds > 0 or (hours == 0 and minutes == 0):
                parts.append(f"{seconds}秒")
            return ''.join(parts)
        
        # 发送初始计时器消息
        timer_msg = await ctx.send(f"计时器:{format_time(total_seconds)}")
        
        # 倒计时循环
        current_sec = total_seconds
        while current_sec > 0:
            await asyncio.sleep(1)
            current_sec -= 1
            await timer_msg.edit(content=f"计时器:{format_time(current_sec)}")
        
        # 倒计时结束提醒
        await timer_msg.edit(content=f"{ctx.author.mention},你的倒计时结束啦!")
        
    except ValueError:
        await ctx.send("输入格式错误!请输入类似 `!timer 2h30m`、`!timer 1小时10分` 或 `!timer 300`(默认秒)的格式")

关键改动说明

  • 输入兼容性提升:改用*, time_input参数,支持带空格的时间输入(比如!timer 1h 30m),更贴合用户使用习惯。
  • 时分秒格式化:新增format_time函数,自动将总秒数转换为中文友好的时分秒格式,会省略数值为0的单位(例如30秒仅显示“30秒”,1小时5分显示“1小时5分钟”)。
  • 倒计时精度修正:将原代码的0.75秒休眠改为1秒休眠,保证倒计时与实际时间同步,避免出现快进情况。
  • 错误提示优化:中文提示更明确,直接告知用户正确的输入格式。
  • 代码逻辑简化:移除不必要的异常抛出,改用return直接退出,代码结构更清晰。

使用示例

  • !timer 2h15m30s → 显示“计时器:2小时15分钟30秒”并开始倒计时
  • !timer 300 → 显示“计时器:300秒”(或可修改格式化函数显示为“5分钟”)
  • !timer 1h → 显示“计时器:1小时”

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:23:36