@DierLL

Временный мут на discord.py?

Приветствую. Проблема с кодом, роль мута не снимается спустя время. Как исправить?

@bot.command()
@commands.has_permissions(view_audit_log = True)
@commands.cooldown(1, 3, commands.BucketType.guild)
async def mute(ctx, member: discord.Member = None, duration = None, *, reason = None):
    mute_role = discord.utils.get(ctx.guild.roles, name = "Muted")

    if not mute_role:
        mute_role = await ctx.guild.create_role(name = "Muted")
        for channel in ctx.guild.channels:
            await channel.set_permissions(mute_role, send_messages=False, connect=False)

    await member.add_roles(mute_role)
    
    if duration:
        duration = duration.lower()
        time_parts = {"y": 31536000, "mon": 2592000, "w": 604800, "d": 86400, "h": 3600, "min": 60, "s": 1}
        duration_seconds = sum(int(num) * time_parts[unit] for num, unit in zip(duration.split()[:-1:2], duration.split()[1::2]))
        unmute_time = datetime.datetime.utcnow() + timedelta(seconds=duration_seconds)
        await member.add_roles(mute_role)
        emb0 = discord.Embed(
            title = f'<:muted:1126853362999111740> Participant has been successfully muted.',
            description = f'<:warn:1121741505548267520> The participant has been assigned the mute role, and their ability to send messages has been blocked.',
            color = 0x0089FF
        )
        emb0.add_field(
            name = f'<:moderator:1121741479216427088> Moderator:',
            value = f'{ctx.author.mention}',
            inline = True
        )
        emb0.add_field(
            name = f'<:user:1121742132089212998> Muted:',
            value = f'{member.mention}',
            inline = True
        )
        emb0.add_field(
            name = f'<:info:1121741519540453386> Reason:',
            value = f'{reason}',
            inline = False
        )
        emb0.add_field(
            name = f'<:timeout:1121741499986616330> Duration:',
            value = f'{duration}',
            inline = False
        )
        emb0.set_author(
            name = f'Turo Team',
            icon_url = 'https://media.discordapp.net/attachments/1056666785484636230/1121768764267048980/Frame_5.png?width=384&height=384'
        )
        await ctx.send(embed=emb0)
        await unmute(member, mute_role, unmute_time)

    else:
        await member.add_roles(mute_role, reason=reason)
        
        emb1 = discord.Embed(
            title = f'<:muted:1126853362999111740> Participant has been successfully muted.',
            description = f'<:warn:1121741505548267520> The participant has been assigned the mute role, and their ability to send messages has been blocked.',
            color = 0x0089FF
        )
        emb1.add_field(
            name = f'<:moderator:1121741479216427088> Moderator:',
            value = f'{ctx.author.mention}',
            inline = True
        )
        emb1.add_field(
            name = f'<:user:1121742132089212998> Muted:',
            value = f'{member.mention}',
            inline = True
        )
        emb1.add_field(
            name = f'<:info:1121741519540453386> Reason:',
            value = f'{reason}',
            inline = False
        )
        emb1.add_field(
            name = f'<:timeout:1121741499986616330> Duration:',
            value = f'The time is not specified',
            inline = False
        )
        emb1.set_author(
            name = f'Turo Team',
            icon_url = 'https://media.discordapp.net/attachments/1056666785484636230/1121768764267048980/Frame_5.png?width=384&height=384'
        )
        await ctx.send(embed=emb1)

async def unmute(member, mute_role, unmute_time):
    while datetime.datetime.utcnow() < unmute_time:
        await asyncio.sleep((unmute_time - datetime.datetime.utcnow()).total_seconds())

    if mute_role in member.roles:
        await member.remove_roles(mute_role)
  • Вопрос задан
  • 194 просмотра
Пригласить эксперта
Ответы на вопрос 3
fenrir1121
@fenrir1121 Куратор тега discord.py
Начни с документации
Вероятно вы выключали бота в этом случае логика никогда не отработает.
Необходимо хранить подобную информацию в БД. Кроме того для есть discord.ext.tasks, чтобы периодически в фоне запускать что-либо.
Ответ написан
Zagir-vip
@Zagir-vip
Web dev, Game dev, app dev, Разработчик на Python!
@bot.command()
async def mute(ctx, member: discord.Member, duration: str, *, reason: str):
	try:
		await ctx.message.delete()

		duration_mute = int(duration[:1]) # duration = 1h. [0:] = 1
		duration_time = str(duration[1:]) # duration = 1h. [:0] = h
		duration_timer = None # timedelta

		if any(map(duration_time.lower().startswith, ['s', 'с'])):
			duration_timer = datetime.datetime.utcnow() + datetime.timedelta(hours=3, seconds=int(duration_mute))
		if any(map(duration_time.lower().startswith, ['m', 'м'])):
			duration_timer = datetime.datetime.utcnow() + datetime.timedelta(hours=3, minutes=int(duration_mute))
		if any(map(duration_time.lower().startswith, ['h', 'ч'])):
			duration_timer = datetime.datetime.utcnow() + datetime.timedelta(hours=int(duration_mute)+3)
		if any(map(duration_time.lower().startswith, ['d', 'д'])):
			duration_timer = datetime.datetime.utcnow() + datetime.timedelta(hours=3, days=int(duration_mute))

		a = await member.timeout(duration_timer.astimezone(pytz.timezone("Europe/Moscow")), reason=reason)

		embed = discord.Embed(
			title="Пользователь замучен",
			color=discord.Color.red(),
			description=f"Наказан: {member.mention}\nЗамучен: {ctx.author.mention}\nСрок: {duration} мин\nОкончание: {end_time_str}\nПричина: {reason}"
		)

		await ctx.send(embed=embed)

		
	except discord.Forbidden:
		embed = discord.Embed(
				title="Ошибка",
				color=discord.Color.red(),
				description="У меня недостаточно прав для выполнения этой команды."
		)
		await ctx.send(embed=embed)

	except commands.MissingRequiredArgument:
		embed = discord.Embed(
				title="Ошибка",
				color=discord.Color.red(),
				description="Некоторые обязательные аргументы отсутствуют. Используйте команду в следующем формате: !mute @пользователь срок_мута(в минутах) причина."
		)
		await ctx.send(embed=embed)

	except commands.BadArgument:
		embed = discord.Embed(
				title="Ошибка",
				color=discord.Color.red(),
				description="Неверный формат аргумента. Пожалуйста, проверьте правильность введенных данных."
		)
		await ctx.send(embed=embed)


Нельзя указывать таймаут больше 28 дней.

Код нужно немного доработать.
Ответ написан
@Grefin_193
@bot.command()
@commands.has_guild_permissions(administrator=True)
async def mute(ctx, member: discord.Member, duration: str, reason):
guild = bot.get_guild(975494474098679869)
role = guild.get_role(975494474480369721)
channel = guild.get_channel(975494474719461431)
time = {"s": 1, "m": 60, "h": 3600, "d": 86400}
duration_seconds = int(duration[:-1]) * time[duration[-1]]
await member.add_roles(role)
await channel.send(f"{member.mention} Был замьучен на {duration}, по причине {reason}!")
await asyncio.sleep(duration_seconds)
await member.remove_roles(role)
await channel.send(f"С {member.mention} был снят мут!")
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы