所以我完成了我的静音命令,然后我在一个人身上测试了它并且它起作用了。但是当涉及到对不同的人静音时,它却没有。我让一个人静音 1 分钟,另一个人静音 10 秒。因为我先做了 1m 静音,它先做了那个静音,然后我对另一个人做了 10 秒静音。它一直等到一分钟静音结束后才进行 10 秒静音。如何阻止这种情况发生? 这是我的代码:
@client.command()
@commands.has_role("Mod")
async def mute(ctx, user : discord.Member, duration = 0,*, unit = None):
roleobject = discord.utils.get(ctx.message.guild.roles, id=730016083871793163)
await ctx.send(f":white_check_mark: Muted {user} for {duration}{unit}")
await user.add_roles(roleobject)
if unit == "s":
wait = 1 * duration
time.sleep(wait)
elif unit == "m":
wait = 60 * duration
time.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
没有错误。
您正在使用
time.sleep(wait)
,这将停止所有其他代码,直到 wait
时间段结束。当您使用 time.sleep
python 不接受任何其他输入,因为它仍在“忙”睡觉。
你应该看看 coroutines 来解决这个问题。
这篇文章很好地说明了您要实现的目标:我需要帮助在 discord py 中制作一个 discord py temp mute 命令
我认为这个编辑应该有效:
#This should be at your other imports at the top of your code
import asyncio
async def mute(ctx, user : discord.Member, duration = 0,*, unit = None):
roleobject = discord.utils.get(ctx.message.guild.roles, id=730016083871793163)
await ctx.send(f":white_check_mark: Muted {user} for {duration}{unit}")
await user.add_roles(roleobject)
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
自 discord.py 2.0 发布以来,您应该使用
discord.Member.timeout
。我编写了一个 app_command
超时指定的成员,在给定的参数中,时间。
代码:
@app_commands.command(name="mute", description="mutes specified member.")
@app_commands.default_permissions(moderate_members=True)
async def timeout(self, ctx, member: discord.Member, seconds: int = 0, minutes: int = 0, hours: int = 0, days: int = 0, weeks: int = 0, reason: str = None):
duration = datetime.timedelta(seconds=seconds, minutes=minutes, hours= hours, days=days, weeks=weeks)
await member.timeout(duration, reason=reason)
await ctx.response.send_message(f"{member.mention} has been muted until <t:{duration}:R>.")