有时间限制的静音命令

2024-04-19 11:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何使我的静音命令在一定时间内使某人静音。例如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}")

Tags: namenonesend静音awaitrolememberhas
2条回答

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

在回答中,我已经解释了如何编写一个完美的命令

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

我会把我的答案从那里复制粘贴到这里。请注意每一句话。:)

TEMPMUTE命令

步骤1:定义功能和权限

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

在使用此功能之前,您需要在代码中包含以下内容:

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一秒钟,1m一分钟,等等。你也可以用它来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)

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

谢谢D

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)

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

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

.tempmute @SomeUser 10s Because I said so!

相关问题 更多 >