【问题标题】:Mute Command with Time Limit有时间限制的静音命令
【发布时间】:2021-05-24 01:19:42
【问题描述】:

我想知道如何让我的静音命令将某人静音一段时间。例如,p/mute @User 1h 会将某人静音 1 小时。

@client.command()
@commands.has_permissions(manage_roles = True)
async def mute(ctx, member : discord.Member = None):
  if member == None:
    await ctx.send("Please mention a user to mute")
  else:
    user = member
    role = discord.utils.get(ctx.guild.roles, name="Muted")
    if role is None:
      await ctx.send("Please make a muted role name `Muted` or make sure to name the role `Muted` and not `muted` or `MUTED`")
    else:
      await user.add_roles(role)
      await ctx.send(f"{member.name} has been muted by {ctx.author.name}")

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    This site 有一个示例,说明了这样做的一种方法,但是我发现它需要一些轻微的修改才能工作 - 在我编辑之前它在某些地方给了我错误。下面的代码在我的服务器上工作:

    @client.command(aliases=['tempmute'])
    @commands.has_permissions(manage_messages=True)
    async def mute(ctx, member: discord.Member=None, time=None, *, reason=None):
        if not member:
            await ctx.send("You must mention a member to mute!")
            return
        elif not time:
            await ctx.send("You must mention a time!")
            return
        else:
            if not reason:
                reason="No reason given"
            #Now timed mute manipulation
        try:
            time_interval = time[:-1] #Gets the numbers from the time argument, start to -1
            duration = time[-1] #Gets the timed manipulation, s, m, h, d
            if duration == "s":
                time_interval = time_interval * 1
            elif duration == "m":
                time_interval = time_interval * 60
            elif duration == "h":
                time_interval = time_interval * 60 * 60
            elif duration == "d":
                time_interval = time_interval * 86400
            else:
                await ctx.send("Invalid duration input")
                return
        except Exception as e:
            print(e)
            await ctx.send("Invalid time input")
            return
        guild = ctx.guild
        Muted = discord.utils.get(guild.roles, name="Muted")
        if not Muted:
            Muted = await guild.create_role(name="Muted")
            for channel in guild.channels:
                await channel.set_permissions(Muted, speak=False, send_messages=False, read_message_history=True, read_messages=False)
        else:
            await member.add_roles(Muted, reason=reason)
            muted_embed = discord.Embed(title="Muted a user", description=f"{member.mention} Was muted by {ctx.author.mention} for {reason} to {time}")
            await ctx.send(embed=muted_embed)
            await asyncio.sleep(int(time_interval))
            await member.remove_roles(Muted)
            unmute_embed = discord.Embed(title='Mute over!', description=f'{ctx.author.mention} muted to {member.mention} for {reason} is over after {time}')
            await ctx.send(embed=unmute_embed)
    

    这应该在您的服务器中创建一个名为“已静音”的新角色(如果它尚不存在),将目标成员移动到所述角色中指定的时间,然后在时间到期后将其从角色中删除。

    使用代码的示例命令(. 的前缀):

    .tempmute @SomeUser 10s Because I said so!

    【讨论】:

      【解决方案2】:

      我有一个非常简单的方法来做到这一点。这将是有效的并且需要更少的代码。我已经在我的机器人中使用它很长时间了。我在这里回答了一位用户的另一个问题:Bot unmuting member when use tempmute command

      在答案中,我已经解释了如何编写完美的命令。

      这个命令完全是另一个命令。您不必修改您的 mute 命令。但只需创建一个名为 tempmute 的新命令。

      我会将我的答案从那里复制并粘贴到这里。请注意每一个陈述。 :)

      TEMPMUTE 命令。

      第一步:定义功能和权限

      我们将定义函数,对使用有一些权限限制。具有权限的人指定权限。

      在你使用它之前,你的代码中需要有以下内容:

      from discord.ext import commands
      

      (有的话请忽略)

      方法如下:

      @bot.command()
      @commands.has_permissions(manage_roles=True)
      async def tempmute(ctx, member: discord.Member, time, *, reason=None):
      

      您可以根据需要添加更多权限,并使用 True 或 False 来允许或拒绝。

      第2步:制定角色寻找条件。如果角色不存在则创建一个静音角色,如果存在则使用它。

      所以我正在为角色是否存在创造条件。它将检查角色是否存在。如果它存在,那么我们将简单地使用它,但如果它不存在,我们将创建一个具有特定权限的。

      方法如下:

      if discord.utils.get(ctx.guild.roles, name="Muted"):
          mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
      else:
          perms = discord.Permissions(send_messages=False, add_reactions=False, connect=False, speak=False)
          await bot.create_role(name="Muted", permissions=perms)
          mute_role = discord.utils.get(ctx.guild.roles, name="Muted") 
      

      第 3 步:检查某人是否静音。

      现在我正在创建成员是否静音的条件。我们将通过成员的角色进行检查。

      方法如下:

      if mute_roles in member.roles:
          await ctx.channel.send(f"{member.mention} is already muted!")
      else:
          # code here (more steps will explain how)
      

      第 4 步:添加条件并将成员静音。

      现在我们将为此命令添加限制权限。谁不能让所有人静音,谁都可以。

      首先我们添加我们的第一个条件,即管理员不能被静音。 方法如下:

      if member.guild_permissions.administrator:    
          isadminembed=discord.Embed(title="Tempmute", description=f"Hi {ctx.author.mention}, you can't mute {member.mention} as they are a Server Administrator.", color=discord.Colour.red())
          isadminembed.set_author(name="Bot")
          await ctx.channel.send(embed=isadminembed)
      

      现在我们将添加else 条件,即除管理员之外的所有其他成员都可以静音。 方法如下:

      else:
          time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800, "M": 2419200, "y": 29030400}
          mute_time = int(time[:-1]) * time_conversion[time[-1]]
      
          await member.add_roles(mute_role)
          mutedembed=discord.Embed(title="Tempmute", description=f"The member, {member.mention} has been muted by the moderator {ctx.author.mention}. \n \nTime: {mute_time} seconds \nReason: {reason}", color=discord.Colour.random())
          mutedembed.set_author(name="Bot")
          await ctx.channel.send(embed=mutedembed)
      
          await asyncio.sleep(mute_time)
          await member.remove_roles(mute_role)
          await ctx.channel.send(f"{member.mention} has been unmuted!")
      

      我在这里添加了时间转换。时间输入必须是:

      1s 1 秒,1m 1 分钟等。您也可以将其用于years


      Tempmute 命令编译完成

      这是所有编译成命令的代码。

      @bot.command()
      @commands.has_permissions(manage_roles=True)
      async def tempmute(ctx, member: discord.Member, time, *, reason=None):
          if discord.utils.get(ctx.guild.roles, name="Muted"):
              mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
          else:
              perms = discord.Permissions(send_messages=False, add_reactions=False, connect=False, speak=False)
              await bot.create_role(name="Muted", permissions=perms)
              mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
      
          if mute_roles in member.roles:
              await ctx.channel.send(f"{member.mention} is already muted!")
          
          else:
              if member.guild_permissions.administrator:    
                  isadminembed=discord.Embed(title="Tempmute", description=f"Hi {ctx.author.mention}, you can't mute {member.mention} as they are a Server Administrator.", color=discord.Colour.red())
                  isadminembed.set_author(name="Bot")
                  await ctx.channel.send(embed=isadminembed)
              
              else:
                  time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800, "M": 2419200, "y": 29030400}
                  mute_time = int(time[:-1]) * time_conversion[time[-1]]
      
                  await member.add_roles(mute_role)
                  mutedembed=discord.Embed(title="Tempmute", description=f"The member, {member.mention} has been muted by the moderator {ctx.author.mention}. \n \nTime: {mute_time} seconds \nReason: {reason}", color=discord.Colour.random())
                  mutedembed.set_author(name="Bot")
                  await ctx.channel.send(embed=mutedembed)
      
                  await asyncio.sleep(mute_time)
                  await member.remove_roles(mute_role)
                  await ctx.channel.send(f"{member.mention} has been unmuted!")
      

      TEMPMUTE 命令错误处理

      第 1 步:将函数定义为事件。

      我们将脚本中的函数定义为 tempmute 命令的错误,并将其声明为错误。

      方法如下:

      @bot.error
      async def tempmute_error(ctx, error):
      

      第 2 步:添加错误实例。

      我们现在将为错误添加一个条件。我们的错误将是:MissingRequiredArgument 错误,因为该命令可能缺少必要的参数。

      所以isinstance 将检查错误,然后执行相关操作。

      方法如下:

      if isinstance(error, discord.ext.commands.MissingRequiredArgument):
          tempmuteerrorembed=discord.Embed(title=f"Missing Argument! {error}", description=f"Hello {ctx.author.mention}! You have not entered the needed argument. \n Either you forgot to **mention the member** or you forgot to **enter the time of the mute** you want. \n \n Please check this again and add the necessary argument in the command. \n \nThis is the syntax: \n```!tempmute <mention member> <time: 1s, 2h, 4y etc..> <reason (optional)>```", color=discord.Colour.red())
          tempmuteerrorembed.set_author(name="Bot")
          await ctx.send(embed=tempmuteerrorembed)
      

      这将适用于MissingRequiredArguement,并显示错误以及其中的语法,以便命令正确使用。


      TEMPMUTE 命令错误处理已编译

      这里是TEMPMUTE命令错误处理的编译代码。

      @bot.error
      async def tempmute_error(ctx, error):
          if isinstance(error, discord.ext.commands.MissingRequiredArgument):
              tempmuteerrorembed=discord.Embed(title=f"Missing Argument! {error}", description=f"Hello {ctx.author.mention}! You have not entered the needed argument. \n Either you forgot to **mention the member** or you forgot to **enter the time of the mute** you want. \n \n Please check this again and add the necessary argument in the command. \n \nThis is the syntax: \n```!tempmute <mention member> <time: 1s, 2h, 4y etc..> <reason (optional)>```", color=discord.Colour.red())
              tempmuteerrorembed.set_author(name="Bot")
              await ctx.send(embed=tempmuteerrorembed)
      

      我希望我能够向您解释答案以及如何编写命令。如果出现任何问题,请在 cmets 中询问。

      谢谢! :D

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 2021-10-31
        • 2023-01-19
        • 2021-01-16
        • 2021-04-25
        • 1970-01-01
        • 2021-09-02
        相关资源
        最近更新 更多