File "main.py", line 98 channel_to_delete = list(filter(lambda channel: channel.name == f'ticket - {user}', user.guild.text_channels))[0]

Рейтинг: -1Ответов: 1Опубликовано: 11.03.2023

я не сильно шарю в написании ботов на питоне, и когда пытаюсь сделать систему тикетов он не хочет удалять канал, не знаю почему. Помогите пожалуйста! Я понимаю в чем заключается ошибка но не понимаю как её исправить.

ошибка:

File "main.py", line 98
    channel_to_delete = list(filter(lambda channel: channel.name == f'ticket - {user}', user.guild.text_channels))[0]
                                                                                                                    ^
IndentationError: unindent does not match any outer indentation level

Код:

# -*- coding: utf-8 -*-
import discord
import asyncio
from discord.ext import commands


TOKEN='token'

intents = discord.Intents.all()

bot = commands.Bot(command_prefix="!", intents=intents)

client = discord.Client(intents=intents)

#kick

@bot.command()
async def kick(ctx, user: discord.Member, *, reason="причина не указана"):
        await user.kick(reason=reason)
        kick = discord.Embed(title=f"👢пользователь {user.name} Кикнут!", description=f"Причина: {reason}\nкто: {ctx.author.mention}", colour = discord.Color.green())
        await ctx.message.delete()
        await ctx.channel.send(embed=kick)
        await user.send(embed=kick)

#ban

@bot.command()
async def ban(ctx, user: discord.Member, *, reason="причина не указана"):
        await user.ban(reason=reason)
        ban = discord.Embed(title=f"🔨пользователь {user.name} забанен!", description=f"Причина: {reason}\nкто: {ctx.author.mention}", colour = discord.Color.green())
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

#help
@bot.command()
async def Help(ctx):
    embed = discord.Embed(
            title="команды модерации",
            description="• !Kick @пользователь причина - выгнать пользователя с сервера\n• !ban @пользователь причина - заблокировать пользователя на сервре\n• !mute @пользователь время прична - замутить пользователя\n• !clear кол-во - очищение сообщений (макс. 10.000)", colour = discord.Color.blue()
        )
    sent = await ctx.send(embed=embed)

#clear
@bot.command()
async def clear(ctx, amount: int = 10000):
    await ctx.channel.purge(limit = amount)
    em = discord.Embed(
            title="🧹Чат отчищен",
            description=f"отчищено {amount} сообщений, модераторм {ctx.author.mention} ", colour = discord.Color.green()
        )
    sent = await ctx.send(embed=em)

#mute
@bot.command()
async def mute(ctx, user: discord.Member, time: int,*, reason):
    role = user.guild.get_role(1083116096464375989) # айди роли которую будет получать юзер
    emb = discord.Embed( title = '🔇Пользователь замьючен', description=f"Пользователю {user} выдали мьют!\nВремя пробывания в мьюте: {time} минут\nПричина выдачи мьюта: {reason}!", colour = discord.Color.green())
    emb.set_footer(text = 'Действие выполнено модератором/админом - ' + ctx.author.name)
    await ctx.send( embed = emb)
    await user.add_roles(role) #выдает мьют роль
    await asyncio.sleep(time * 60) #ждет нужное кол-во секунд умноженных на 60(вы выдаете мут на минуты. Допустим time = 10, то вы выдали мут на 10 минут)
    await user.remove_roles(role) #снимает мьют роль

#тикеты
@bot.command(pass_context=True)
async def ticket(ctx):
    user = ctx.author
    guild = ctx.guild
    embed = discord.Embed(
        title = 'Система Тикетов',
        description = 'Нажми 📩 что бы создать тикет.',
        color = 0
    )
    embed.set_footer(text="ticket system")
    msg = await ctx.send(embed=embed)
    await msg.add_reaction("📩")
    def check(reaction, user):
        return str(reaction) == '📩' and ctx.author == user
    await bot.wait_for("reaction_add", check=check)
    chan = await user.guild.create_text_channel(name=f'ticket - {user}')
    role = discord.utils.get(user.guild.roles, name="@everyone")
    await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False)
    await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)

    embed = discord.Embed(
        title="Тикеты",
        description="Нажмите :lock: что бы закрыть тикет",
        color=0x00FFFF
    )
    embed.set_footer(text="Система тикетов")
    msg = await chan.send(embed=embed)
    await msg.add_reaction("🔒")

    await msg.add_reaction("🔒")
    def check(reaction, user):
        return str(reaction) == '🔒' and ctx.author == user
      channel_to_delete = list(filter(lambda channel: channel.name == f'ticket - {user}', user.guild.text_channels))[0]
await channel_to_delete.delete()


bot.run(TOKEN)

Ответы

▲ 0

В Вашей команде ticket(ctx) имеются неверные отступы:

    def check(reaction, user):
        return str(reaction) == '🔒' and ctx.author == user
      channel_to_delete = list(filter(lambda channel: channel.name == f'ticket - {user}', user.guild.text_channels))[0]
await channel_to_delete.delete()

Неверный отступ с переменной channel_to_delete и самим действием await channel_to_delete.delete().

Исправленный код:

@bot.command(pass_context=True)
async def ticket(ctx):
    user = ctx.author
    guild = ctx.guild
    embed = discord.Embed(
        title = 'Система Тикетов',
        description = 'Нажми 📩 что бы создать тикет.',
        color = 0
    )
    embed.set_footer(text="ticket system")
    msg = await ctx.send(embed=embed)
    await msg.add_reaction("📩")
    def check(reaction, user):
        return str(reaction) == '📩' and ctx.author == user
    await bot.wait_for("reaction_add", check=check)
    chan = await user.guild.create_text_channel(name=f'ticket - {user}')
    role = discord.utils.get(user.guild.roles, name="@everyone")
    await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False)
    await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)

    embed = discord.Embed(
        title="Тикеты",
        description="Нажмите :lock: что бы закрыть тикет",
        color=0x00FFFF
    )
    embed.set_footer(text="Система тикетов")
    msg = await chan.send(embed=embed)
    await msg.add_reaction("🔒")

    await msg.add_reaction("🔒")
    def check(reaction, user):
        return str(reaction) == '🔒' and ctx.author == user
    channel_to_delete = list(filter(lambda channel: channel.name == f'ticket - {user}', user.guild.text_channels))[0]
    await channel_to_delete.delete()