discord.py运行tempmute命令报MissingRequiredArgument缺少time参数问题
问题定位与修复方案
报错原因
这个报错有两个触发场景:
- 你执行命令时漏传了时长参数:该命令要求的输入格式为
!tempmute @被禁言用户 时长,例如!tempmute @测试用户 10m,如果没有输入时长部分就会直接触发参数缺失报错。 - 你的代码本身存在三处逻辑错误导致参数解析失败:
- Cog类中的命令方法第一个参数必须是
self,你当前的tempmute方法没有声明self参数,会导致参数顺序错位,discord.py会把后续的参数都判定为缺失。 time参数的类型注解错误:你写的是int类型,但后续代码需要取time的数字部分和单位部分,说明time应该是字符串类型。输入的10m这种带单位的内容无法被解析为int,会被discord.py判定为没有传入符合要求的time参数,进而触发报错。- 原有逻辑取数字部分仅用了
time[0],仅支持个位数时长,输入10m这类多位数时长会计算错误。
- Cog类中的命令方法第一个参数必须是
修复步骤
- 修正参数定义:补全
self参数,修改time的类型注解为str,可同时添加默认值做缺省提示 - 增加参数合法性校验,避免用户输入格式错误的时长
- 修正时长计算逻辑,用
time[:-1]取除最后一位单位外的所有数字字符,支持多位数字的时长
修正后的完整代码如下:
import discord import asyncio from discord.ext import commands class TempMute(commands.Cog): def __init__(self, client): self.client = client client.remove_command("tempmute") @commands.command() @commands.has_role("Staff") async def tempmute(self, ctx, member: discord.Member, time: str = None): # 缺省参数提示 if time is None: embed = discord.Embed(description="❌ 请指定禁言时长,格式示例:10m(10分钟)、2h(2小时)、1d(1天)", color=discord.Color.red()) await ctx.send(embed=embed, delete_after=5) return # 格式合法性校验 time_convert = {"s":1, "m":60, "h":3600,"d":86400} if not time[:-1].isdigit() or time[-1] not in time_convert: embed = discord.Embed(description="❌ 时长格式错误,正确格式:数字+单位,支持的单位:s(秒)、m(分钟)、h(小时)、d(天)", color=discord.Color.red()) await ctx.send(embed=embed, delete_after=5) return muted_role=discord.utils.get(ctx.guild.roles, name="Muted") tempmute_time = int(time[:-1]) * time_convert[time[-1]] await ctx.message.delete() await member.add_roles(muted_role) embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} 禁言成功**", color=discord.Color.green()) await ctx.send(embed=embed, delete_after=5) await asyncio.sleep(tempmute_time) await member.remove_roles(muted_role) def setup(client): client.add_cog(TempMute(client))
内容的提问来源于stack exchange,提问作者Cherie
相关产品推荐
相关产品推荐

