如何使 discord.py 临时静音

时间:2021-04-28 13:44:11

标签: python discord discord.py bots

我已经有一个 tempmute 命令,但我不知道如何将时间从秒更改为分钟

我想要我的 tempmute 命令,所以我可以写“tempmute <@user> 30m(原因),我该怎么做才能使 s=seconds、m=minutes、h=hour 和 d=day。默认权限现在是秒

这是我现在的代码:

@client.command()
@commands.has_permissions(manage_messages=True)
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
    if reason == None:
        reason = "no reason provided"
    
    if member.id == ctx.author.id:
        await ctx.send(f"{ctx.author.mention}, you can't mute yourself")

    role = discord.utils.get(ctx.guild.roles, name="Muted")
    guild = ctx.guild

    if not role:
        role = await guild.create_role(name="Muted")

        for channel in guild.channels:
            await channel.set_permissions(role, speak=False, send_messages=False, read_message_history=True, read_messages=False)
    embed = discord.Embed(title="tempmuted", description=f"{member.mention} was tempmuted ", colour=discord.Colour.light_gray())
    embed.add_field(name="reason:", value=reason, inline=False)
    embed.add_field(name="time left for the mute:", value=f"{time}", inline=False)
    await member.add_roles(role)
    await ctx.send(embed=embed)
    await asyncio.sleep(time)
    await member.remove_roles(role)

2 个答案:

答案 0 :(得分:0)

你总是可以这样做:

async def tempmute(ctx, member: discord.Member, s=0, m=0, h=0, d=0, reason=None):
    time = s + 60*m + 60*60*h + 60*60*24*d
    ...

答案 1 :(得分:0)

不熟悉 discord 的 Python 库,但假设当您编写 50m 时,您的 time 参数是字符串 "50m"

@client.command()
@commands.has_permissions(manage_messages=True)
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
  mults = {"m": 60, "h": 60 * 60, "d": 60 * 60 * 24}
  try:
    seconds = int(time)
  except ValueError:
    seconds = int(time[:-1]) * mults.get(time[-1], 1)
  # ...

它会检查它是否可以将time解析为一个数字并将其视为秒,否则它将采用数字+乘数格式并在乘数字典中查找time的最后一个字符.

您可能需要捕捉一些带有无效值的边缘情况。