You need to enable JavaScript to run this app. discord.py 提醒函数如何支持多时间单元组合的time参数输入?
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 提醒函数如何支持多时间单元组合的time参数输入?

多组合时间单元解析的代码调整方案

问题根源

当前代码的参数绑定逻辑完全受discord.py的命令解析规则限制:函数签名定义了reminder(ctx, time, *, reminder),解析器会按空格拆分用户输入的内容,把第一个片段绑定给time参数,从第二个片段开始的所有内容,因为reminder带了*前缀,会被整体塞进去。所以用户输入>reminder 1h 30m eat chocolate时,"30m"根本不会进入时间计算逻辑,直接被当成提醒文本的一部分。

核心调整方向

替换原来硬绑定单time参数的写法,改成全量接收所有输入片段,逐段识别符合时间格式的内容,拆分出时间累加值和纯提醒文本,完全绕开固定参数位置的限制。
具体修改点如下:

  • 把函数签名从async def reminder(ctx, time, *, reminder):改成async def reminder(ctx, *args):,让解析器把所有跟在命令后面的内容按空格拆成元组传入,不再提前固定哪个是时间、哪个是提醒内容。
  • 提前定义时间单位的换算映射表,不用写一堆重复的if分支,减少出错概率:
    TIME_UNITS = {
        "d": 24 * 60 * 60,  # 1天的总秒数
        "h": 60 * 60,       # 1小时的总秒数
        "m": 60,            # 1分钟的总秒数
        "s": 1              # 1秒的总秒数
    }
    
  • 逐段遍历传入的args元组:遇到开头是数字、结尾带时间单位的片段,就累加对应的秒数;一旦遇到第一个不符合时间格式的片段,就停止时间识别,把后面所有片段拼起来作为提醒文本。
  • 补充边界校验:检查累加的总秒数是不是大于0、提醒文本是不是为空,对应给出错误提示。
  • 顺手修复原代码里的遗留bug:原代码里几处ctx.send没有加await,运行时会抛协程未等待的警告,全部补上await;原来分散的if判断改成逻辑互斥的识别,避免重复计算时长;最后把总秒数反向换算成人类可读的时长字符串,替代原来单步赋值的counter变量,适配多单元累加的场景。

调整后的完整可运行代码

import asyncio
from discord.ext import commands

# 定义时间单位换算关系
TIME_UNITS = {
    "d": 24 * 60 * 60,
    "h": 60 * 60,
    "m": 60,
    "s": 1
}

@client.command(name = "reminder", brief = "I'll send a message to the future.",
                description = "State what I have to remind you, as well as when and in which channel and I'll do it! "
                             "Write d for days, h for hours, m for minutes and s for seconds after the number and then "
                              "what you want to be reminded of. For example: >reminder 1h 30m eat chocolate",
                aliases = ["remind", "remindme", "remindto"])
async def reminder(ctx, *args):
    user = ctx.author
    total_seconds = 0
    reminder_content = []
    is_parsing_time = True

    # 逐段拆分输入,先识别前置的时间单元
    for token in args:
        token_lower = token.lower()
        # 取最后一个字符判断是不是合法时间单位
        unit = token_lower[-1] if token_lower else ""
        if is_parsing_time and unit in TIME_UNITS:
            # 尝试把单位前面的部分转成数字
            try:
                value = float(token_lower[:-1])
                total_seconds += value * TIME_UNITS[unit]
            except ValueError:
                # 提取数字失败,说明这个token不是时间片段,后面全是提醒内容
                is_parsing_time = False
                reminder_content.append(token)
        else:
            is_parsing_time = False
            reminder_content.append(token)
    
    # 把拆分出来的提醒内容拼成完整字符串
    reminder_text = " ".join(reminder_content).strip()

    # 边界校验
    if total_seconds <= 0:
        await ctx.send("You need to provide a valid time! Use formats like 1d, 2h, 30m, 10s, and you can combine them like 1h 30m.")
        return
    if not reminder_text:
        await ctx.send("Please tell me what you want me to remind you about!")
        return

    # 生成人类可读的时长提示
    readable_time = []
    remaining = total_seconds
    # 按天、小时、分钟、秒的顺序换算成可读字符串
    day = remaining // (24*60*60)
    if day:
        readable_time.append(f"{int(day)} day{'s' if day !=1 else ''}")
        remaining -= day * 24*60*60
    hour = remaining // (60*60)
    if hour:
        readable_time.append(f"{int(hour)} hour{'s' if hour !=1 else ''}")
        remaining -= hour * 60*60
    minute = remaining // 60
    if minute:
        readable_time.append(f"{int(minute)} minute{'s' if minute !=1 else ''}")
        remaining -= minute *60
    if remaining:
        readable_time.append(f"{int(remaining)} second{'s' if remaining !=1 else ''}")
    time_str = " ".join(readable_time)

    await ctx.send(f"Alright, I will remind you about {reminder_text} in {time_str}.")
    await asyncio.sleep(total_seconds)
    await ctx.send(f"Hi <@{user.id}>, you asked me to remind you about {reminder_text} {time_str} ago.")

调整后的效果

这套逻辑可以兼容任意数量、任意顺序的时间单元组合,比如用户输入>reminder 1d 2h 15m 10s 提交作业,会正确计算总时长为1天2小时15分10秒,不会把时间片段误判为提醒内容。如果用户输入的片段不符合时间格式,程序会自动从那个位置开始把后续内容全部归为提醒文本,不会直接报错。同时解决了原代码的几个老问题:

  • 不会出现时间片段同时匹配多个if分支导致的重复计算
  • 所有send操作都正确加了await,不会触发协程警告
  • 时长提示会根据总秒数自动生成通顺的可读文本,不会出现多单元累加后计数错乱的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 14:54:05