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

如何用Python编写Discord超时(mute)命令?调试问题求助

问题修复方案

核心问题分析

你的代码存在两个关键错误:

  1. str.replace()方法不会修改原字符串,而是返回新字符串,必须重新赋值给变量才会生效
  2. 处理后的时间是字符串类型,而timedelta的参数需要整数/数值类型,直接传入会报错

修复后的完整代码

import datetime
import discord
from discord.ext import commands

@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, time_str, *, reason="无理由"):
    # 禁止用户禁言自己
    if ctx.author.id == member.id: 
        await ctx.channel.send(":x: 不能禁言自己!")
        return
    
    time_num = None
    timeout_delta = None
    
    # 处理小时格式
    if time_str.endswith("h"):
        try:
            time_num = int(time_str.replace("h", ""))
            timeout_delta = datetime.timedelta(hours=time_num)
        except ValueError:
            await ctx.channel.send(":x: 时间格式错误!请输入类似`7h`或`3d`的格式")
            return
    # 处理天数格式
    elif time_str.endswith("d"):
        try:
            time_num = int(time_str.replace("d", ""))
            timeout_delta = datetime.timedelta(days=time_num)
        except ValueError:
            await ctx.channel.send(":x: 时间格式错误!请输入类似`7h`或`3d`的格式")
            return
    # 不合法的时间后缀
    else:
        await ctx.channel.send(":x: 时间格式错误!请输入类似`7h`或`3d`的格式")
        return
    
    # 执行禁言操作并处理异常
    try:
        # 使用discord标准UTC时间计算截止时间
        await member.timeout(until=discord.utils.utcnow() + timeout_delta, reason=reason)
        # 发送结果嵌入消息
        embed = discord.Embed(title=f":white_check_mark: {member.name} 已成功被禁言")
        embed.add_field(name="时长", value=f"{time_num}{'小时' if time_str.endswith('h') else '天'}")
        embed.add_field(name="理由", value=reason)
        await ctx.send(embed=embed)
    except discord.Forbidden:
        await ctx.channel.send(":x: 我没有权限执行该操作!")
    except Exception as e:
        await ctx.channel.send(f":x: 执行出错:{str(e)}")

额外优化说明

  • 用endswith()替代in判断后缀,避免误判h7这类错误格式
  • 在reason参数前加*,支持带空格的多字符理由输入
  • 增加异常处理:覆盖时间转换失败、机器人权限不足、未知错误等场景
  • 嵌入消息补充时长和理由展示,信息更清晰
  • 使用discord.utils.utcnow()计算截止时间,符合Discord的UTC时间标准

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:05:26