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

Discord.py机器人静音命令:如何将时长转换为分钟/小时?

如何让Discord机器人静音命令支持分钟/小时等时长单位

嘿,你已经把静音命令的核心逻辑跑通了,就差处理带单位的时长参数对吧?我来给你搞定这个——咱们可以让命令支持像10m(10分钟)、2h(2小时)这样的参数,把它们转换成程序需要的秒数,同时在消息里显示友好的时长格式。

实现思路

  1. 把原来的mute_time : int参数改成str类型,这样能接收带单位的字符串
  2. 写一个解析函数,用正则匹配数字和单位(支持s秒、m分钟、h小时、d天,无单位默认按秒算),转换成总秒数的同时生成友好的显示文本
  3. 加入错误处理,比如用户输入无效格式时给出提示
  4. 替换原代码中mute_time的使用逻辑,用解析后的秒数执行延时,用友好文本显示时长

完整代码示例

import discord
from discord.ext import commands
import asyncio
import re

@client.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, mute_time : str, *, reason=None):
    # 定义时长解析函数
    def parse_duration(duration_str):
        duration_str = duration_str.lower()
        # 单位对应秒数的映射
        unit_map = {
            's': 1,
            'm': 60,
            'h': 3600,
            'd': 86400
        }
        # 用正则匹配数字+单位的格式
        match = re.match(r'^(\d+)([smhd]?)$', duration_str)
        if not match:
            return None, None
        
        amount = int(match.group(1))
        unit = match.group(2) or 's'  # 无单位默认按秒算
        if unit not in unit_map:
            return None, None
        
        total_seconds = amount * unit_map[unit]
        # 生成友好的显示文本
        unit_name_map = {
            's': '秒',
            'm': '分钟',
            'h': '小时',
            'd': '天'
        }
        display_text = f"{amount} {unit_name_map[unit]}"
        return total_seconds, display_text

    # 解析用户输入的时长
    total_seconds, display_duration = parse_duration(mute_time)
    if total_seconds is None:
        await ctx.send("无效的时长格式!请使用类似 `10s`(秒)、`5m`(分钟)、`2h`(小时)、`1d`(天)的格式。")
        return

    # 检查静音角色是否存在
    role = discord.utils.get(ctx.guild.roles, name="[Muted]")
    if not role:
        await ctx.send("找不到名为`[Muted]`的静音角色,请先创建该角色!")
        return

    # 执行静音操作
    await member.add_roles(role)
    # 发送服务器通知
    await ctx.send(f'**Muted** {member.mention}\n**Reason: **{reason or "无"}\n**Duration:** {display_duration}')
    # 发送用户私信通知(处理无法发送的情况)
    embed = discord.Embed(color=discord.Color.green())
    embed.add_field(
        name=f"You've been **Muted** in {ctx.guild.name}.",
        value=f"**Action By: **{ctx.author.mention}\n**Reason: **{reason or "无"}\n**Duration:** {display_duration}"
    )
    try:
        await member.send(embed=embed)
    except discord.Forbidden:
        await ctx.send(f"无法给{member.mention}发送私信,对方可能关闭了私信功能。")

    # 等待时长后自动解除静音
    await asyncio.sleep(total_seconds)
    await member.remove_roles(role)
    await ctx.send(f"**Unmuted {member.mention}**")

代码关键点说明

  • 正则表达式确保只匹配数字+合法单位的格式,避免无效输入
  • 加入了静音角色不存在的检查,避免程序报错
  • 处理了无法发送私信的异常情况,提升用户体验
  • 支持无单位输入(比如输入30默认是30秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 09:33:12