interactions-py / interactions.py

A highly extensible, easy to use, and feature complete bot framework for Discord
https://interactions-py.github.io/interactions.py/
MIT License
840 stars 185 forks source link

[PROB] Error after update #1408

Closed AlexaCarra closed 1 year ago

AlexaCarra commented 1 year ago

Library Version

5.4.0

Describe the Bug

I run the code that worked on version 5.0.1 on the new version, and it throws me an error

Steps to Reproduce

-

Expected Results

-

Minimal Reproducible Code

import asyncio

import discord
from password_generator import PasswordGenerator

from db import DataBase

import interactions
from interactions import Client, UserSelectMenu
from interactions import Embed, Color, EmbedField
from interactions import OptionType, StringSelectMenu, ChannelType

from interactions import PermissionOverwrite, Permissions
from interactions import slash_command
from interactions import Intents
from interactions import listen, ComponentContext
from interactions import Modal, ModalContext
from interactions.client import utils
from interactions.models import User

db = DataBase()
bot = Client(intents=Intents.ALL)

color_error = '#e62309'
color_good = '#19e627'
color_default = '#960eeb'

coin_emoji = '<a:coin1:1098002431276761119>'

channels_ids = [1095355771673378966, 1095363510399143996, 1095378778995298304, 1095885357570064394]

clan_shop_items = [
    {'title':'Создать свой клан',
    'price': 150,
    'emoji': '<:ingot:1096513778385948783>',
    'descriptions': 'Создайте свой клан и пригласите в него друзей\nУ своего клана отдельный войс и текстовый чат'}
]

shop_items = [{
    'title':'Роль Diamond',
    'price': 75,
    'emoji': '<:diamond:1096511574920925214>',
    'descriptions': 'Просто роль',
    'role_id': 1096501153983905862},
    {'title':'Роль Platinum',
    'price': 50,
    'emoji': '<:ingot1:1096518002981212303>',
    'descriptions': 'Просто роль',
    'role_id': 1095730250840817805},
    {'title':'Роль Gold',
    'price': 45,
    'emoji': '<:ingot:1096513778385948783>',
    'descriptions': f'x1.5 {coin_emoji} за все активности',
    'role_id': 1096502240174411976}]

create_clan_cost = 100

@listen('on_ready')
async def on_ready():
    print('::: Wallets bot started :::')

#economy
@listen('MessageCreate')
async def on_message(event):
    message = event.message
    content = message.content

    if message.channel.id in channels_ids:
        msg = len(content)
        count = 0
        if msg >= 10:
            count = 0.01
        if msg >= 15:
            count = 0.04
        if msg >= 25:
            count = 0.06
        if msg >= 60:
            count = 0.09
        if msg >= 100:
            count = 0.2

        if count > 0:
            print(f'Начисленно {count}  (len:{msg})')
            db.add_cash(int(message.author.id), count)

@listen('VoiceUserMove')
async def on_voice_move(event):
    prev = event.previous_channel
    new = event.new_channel
    guild = new.guild
    user = event.author

    await unmute_from_room(user)

    if prev.category == 1098011369548292117 and prev.id != 1098014043131875448:
        if len(prev.voice_members) <= 1:
            await prev.delete()

    if new.id == 1098014043131875448:
        channel = await guild.create_channel(name=user.display_name, channel_type=ChannelType.GUILD_VOICE, category=1098011369548292117, reason='Создание приватной комнаты')
        perms = [PermissionOverwrite(id=544171273438363648, type=0, deny=Permissions.CONNECT),
                 PermissionOverwrite(id=user, type=1, allow=1024),
                 PermissionOverwrite(id=user, type=1, allow=Permissions.PRIORITY_SPEAKER)]
        await channel.edit(permission_overwrites=perms)
        await user.move(channel)

@slash_command(name="buy_role", description="testing", default_member_permissions=interactions.Permissions.ADMINISTRATOR)
async def buy_role_test(ctx):
    inputs = [interactions.ShortText(label="Введите название роли", custom_id="private_role_name", min_length=2,
                                     max_length=35),
              interactions.ShortText(label="Введите цвет роли (в формате #hex)", custom_id="private_role_color",
                                     min_length=3, max_length=10)]
    modal = Modal(
        title="Покупка персональной роли",
        custom_id="show_modal_buy_role")

    modal.add_components(inputs)
    await ctx.send_modal(modal)

@slash_command(name="post_create_clan", description="dsad", default_member_permissions=interactions.Permissions.ADMINISTRATOR)
async def post_accept_rules(ctx):
    channel = ctx.channel

    embed_create = Embed(title='Создание клана', description=f"Если вы с друзьями ищите место для приятного времяпрепровождения, то создайте клан\n\nЦена создание клана: **{create_clan_cost}** <a:coin1:1098002431276761119>", color=Color().from_hex(color_default))
    embed_join = Embed(title='Вступить в клан', description=f"Для вступление в клан вам потребуется код клана. Его вы сможете попросить у создателя клана", color=Color().from_hex(color_default))
    b = [interactions.Button(style=interactions.ButtonStyle.GREY, label="Создать клан", custom_id=f"create_clan_button"),
         interactions.Button(style=interactions.ButtonStyle.GREY, label="Вступить в клан", custom_id=f"show_modal_clan")]
    await channel.send(embeds=[embed_create, embed_join], components=b)

@listen('VoiceUserLeave')
async def on_voice_leave(event):
    cur_channel = event.channel

    if cur_channel.category == 1098011369548292117 and cur_channel.id != 1098014043131875448:
        print(cur_channel.voice_members)
        if len(cur_channel.voice_members) <= 1:
            await cur_channel.delete()

@listen('VoiceUserJoin')
async def on_voice_join(event):
    cur_channel = event.channel
    guild = event.channel.guild
    user = event.author

    await unmute_from_room(user)

    if cur_channel.id == 1098014043131875448:
        channel = await guild.create_channel(name=user.display_name, channel_type=ChannelType.GUILD_VOICE, category=1098011369548292117, reason='Создание приватной комнаты')
        perms = [PermissionOverwrite(id=544171273438363648, type=0, deny=Permissions.CONNECT),
                 PermissionOverwrite(id=user, type=1, allow=1024),
                 PermissionOverwrite(id=user, type=1, allow=Permissions.PRIORITY_SPEAKER)]
        await channel.edit(permission_overwrites=perms)
        await user.move(channel)

@slash_command(name="give_cash",description="Выдача денег",default_member_permissions=interactions.Permissions.ADMINISTRATOR, options=[{"name": "member", "description": "Пользователь", "required": True, "type": OptionType.USER},
                                                                   {"name": "ammount", "description": "Количество", "required": True, "type": OptionType.NUMBER}])
async def give_cash(ctx, ammount, member: discord.Member):
    if db.is_user_exist(int(member.id)) is False:
        db.add_user(int(member.id))

    db.add_cash(int(member.id), ammount)

    await ctx.send(f'Пользователю {member} добавленно {ammount}', ephemeral=True)

@slash_command(name="take_cash",default_member_permissions=interactions.Permissions.ADMINISTRATOR, description="Забрать денеги", options = [{"name": "member", "description": "Пользователь", "required": True, "type": OptionType.USER},
                                                                        {"name": "ammount", "description": "Количество", "required": True, "type": OptionType.NUMBER}])
async def take_cash(ctx, ammount, member: discord.Member):
    if db.is_user_exist(int(member.id)) is False:
        db.add_user(int(member.id))

    db.minus_cash(int(member.id), ammount)
    await ctx.send(f'Пользователю {member} отминусовано {ammount}', ephemeral=True)

@slash_command(name="balance", description="Проверка баланса")
async def balance(ctx):
    if db.is_user_exist(int(ctx.author.id)) is False:
        db.add_user(int(ctx.author.id))

    author = ctx.author
    balance = db.get_balance(int(ctx.author.id))
    embed = Embed(title=f"Ваш текущий баланс {balance} <a:coin1:1098002431276761119>", color=Color.from_hex('#a516f2'))
    await ctx.send(embeds=[embed], ephemeral=True)

@slash_command(name="emb", description="Публикация эмбеда", options = [{"name": "title", "description": "Заголовок", "required": True, "type": OptionType.STRING},
                                                                       {"name": "desc", "description": "Описание", "required": True, "type": OptionType.STRING}])
async def post_emb(ctx, title, desc):
    # author = ctx.author
    embed = Embed(title=title, description=desc, color=Color.from_hex(color_good))
    await ctx.channel.send(embeds=[embed], content='<@&1100460046778892288>')

@slash_command(name="reset_balance", description="Проверка баланса",default_member_permissions=interactions.Permissions.ADMINISTRATOR, options = [{"name": "member", "description": "Пользователь", "required": True, "type": OptionType.USER}])
async def reset_balance(ctx, member: discord.Member):
    embed = Embed(title=f"Баланс {member} был обнулен", color=Color.from_hex('#a516f2'))
    if db.is_user_exist(int(member.id)) is False:
        await ctx.send(embeds=[embed], ephemeral=True)
        return db.add_user(int(member.id))

    db.reset_user(int(member.id))
    await ctx.send(embeds=[embed], ephemeral=True)

@slash_command(name="check_balance", description="Проверка баланса",default_member_permissions=interactions.Permissions.ADMINISTRATOR, options = [{"name": "member", "description": "Пользователь", "required": True, "type": OptionType.USER}])
async def user_balance(ctx, member: discord.Member):
    if db.is_user_exist(int(member.id)) is False:
        db.add_user(int(member.id))

    balance = db.get_balance(int(member.id))
    embed = Embed(title=f"Баланс {member}: {balance} <a:coin1:1098002431276761119>", color=Color.from_hex('#a516f2'))
    await ctx.send(embeds=[embed], ephemeral=True)

@slash_command(name='post_shop', description='shope', default_member_permissions=interactions.Permissions.ADMINISTRATOR)
async def shop(ctx):
    embed = Embed(title=f"Магазин",description='Здесь вы сможете купить дополнительные услуги за <a:coin1:1098002431276761119>',
                          color=Color.from_hex('#a516f2'))
    options = []

    for items in shop_items:
        options.append(interactions.StringSelectOption(label=items['title'], value=f'item|{shop_items.index(items)}',description=f"Стоимость: {items['price']} коинов", emoji=items['emoji']))

    menu = StringSelectMenu(
        custom_id="shop_menu"
    )
    menu.options = options

    await ctx.channel.send(embeds=[embed], components=[menu])

@listen('on_component')
async def selected(event:ComponentContext):
    # print(dir(event))

    custom_id = event.ctx.custom_id
    values = event.ctx.values
    author = event.ctx.author

    # b = [interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[0], custom_id=f"room_open"),
    #      interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[1], custom_id=f"room_close"),
    #      interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[2], custom_id=f"room_kick"),
    #      interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[3], custom_id=f"room_limit"),
    #      interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[4], custom_id=f"room_mute")]

    if custom_id == 'room_mute':
        if await is_user_creator_channel(author) and await is_private_room(author):
            menu = UserSelectMenu(
                custom_id="select_users_mute",
                placeholder='Выберите пользователя',
                min_values=1,
                max_values=1
            )
            await event.ctx.send(components=[menu], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'room_unmute':
        if await is_user_creator_channel(author) and await is_private_room(author):
            menu = UserSelectMenu(
                custom_id="select_users_unmute",
                placeholder='Выберите пользователя',
                min_values=1,
                max_values=1
            )
            await event.ctx.send(components=[menu], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'room_kick':
        if await is_user_creator_channel(author) and await is_private_room(author):

            # users_list = cur_channel.voice_members
            # for item in users_list:
            #     options.append(interactions.StringSelectOption(label=str(item), value=item.user.id))

            menu = UserSelectMenu(
                custom_id="select_users_kick",
                placeholder='Выберите пользователя',
                min_values=1,
                max_values=1
            )
            await event.ctx.send(components=[menu], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'select_users_kick':
        user = values[0]

        voice_state = user.voice
        print(dir(voice_state.member))
        print(await voice_state.member.move(1095382219125690419))

    if custom_id == 'select_users_mute':
        if await is_private_room(author) and await is_user_creator_channel(author):
            user = values[0]
            author_cur_channel = author.voice.channel
            if user.voice:
                user_cur_channel = user.voice.channel
            else:
                embed = Embed(title=f"Пользователь не в вашем приватном канале", color=Color.from_hex(color_error))
                return await event.ctx.send(embeds=[embed], ephemeral=True)

            if author_cur_channel.id == user_cur_channel.id:
                await user.edit(mute=True)
                perms = [PermissionOverwrite(id=user, type=1, deny=Permissions.SPEAK)]
                await user_cur_channel.edit(permission_overwrites=perms)

                embed = Embed(title=f"Вы запретили пользователю говорить в вашем канале", color=Color.from_hex(color_good))
                await event.ctx.send(embeds=[embed], ephemeral=True)
            else:
                embed = Embed(title=f"Пользователь не в вашем приватном канале", color=Color.from_hex(color_error))
                await event.ctx.send(embeds=[embed], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'select_users_unmute':
        if await is_private_room(author) and await is_user_creator_channel(author):
            user = values[0]
            author_cur_channel = author.voice.channel
            if user.voice:
                user_cur_channel = user.voice.channel
            else:
                embed = Embed(title=f"Пользователь не в вашем приватном канале", color=Color.from_hex(color_error))
                return await event.ctx.send(embeds=[embed], ephemeral=True)

            if author_cur_channel.id == user_cur_channel.id:
                await user.edit(mute=False)
                perms = [PermissionOverwrite(id=user, type=1, allow=Permissions.SPEAK)]
                await user_cur_channel.edit(permission_overwrites=perms)

                embed = Embed(title=f"Вы разрешили пользователю говорить в вашем канале", color=Color.from_hex(color_good))
                await event.ctx.send(embeds=[embed], ephemeral=True)
            else:
                embed = Embed(title=f"Пользователь не в вашем приватном канале", color=Color.from_hex(color_error))
                await event.ctx.send(embeds=[embed], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'room_open':
        if await is_user_creator_channel(author) and await is_private_room(author):
            channel = author.voice.channel
            perms = [PermissionOverwrite(id=544171273438363648, type=0, allow=Permissions.CONNECT)]

            await channel.edit(permission_overwrites=perms)
            embed = Embed(title=f"Вы открыли приватную комнату для всех!", color=Color.from_hex(color_good))
            await event.ctx.send(embeds=[embed], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'room_close':
        if await is_user_creator_channel(author) and await is_private_room(author):
            channel = author.voice.channel
            perms = [PermissionOverwrite(id=544171273438363648, type=0, deny=Permissions.CONNECT)]

            await channel.edit(permission_overwrites=perms)
            embed = Embed(title=f"Вы закрыли приватную комнату для всех!", color=Color.from_hex(color_good))
            await event.ctx.send(embeds=[embed], ephemeral=True)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'room_limit':
        if await is_user_creator_channel(author) and await is_private_room(author):
            inputs = [interactions.ShortText(label="Введите лимит (только целое число)", custom_id="room_limit_input")]
            modal = Modal(
                title="Изменить лимит участников комнаты",
                custom_id="room_limit_modal")

            modal.add_components(inputs)
            await event.ctx.send_modal(modal)
        else:
            embed = Embed(title=f"Вы не в войсе или вы не админ комнаты", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'show_modal_clan':
        inputs = [interactions.ShortText(label="код приглашения", custom_id="clan_code", min_length=5, max_length=5)]
        modal = Modal(
            title="Вступить в клан",
            custom_id="clan_invite_modal")

        modal.add_components(inputs)
        await event.ctx.send_modal(modal)

    if custom_id == 'buy_role':
        inputs = [interactions.ShortText(label="Введите название роли", custom_id="private_role_name", min_length=2, max_length=35),
                  interactions.ShortText(label="Введите цвет роли (в формате #hex)", custom_id="private_role_color", min_length=3, max_length=10)]
        modal = Modal(
            title="Покупка персональной роли",
            custom_id="show_modal_buy_role")

        modal.add_components(inputs)
        await event.ctx.send_modal(modal)

    if custom_id == 'shop_menu':
        button = list(values)[0]
        if 'item' in button:
            item = button.split('|')
            button_id = int(item[1])
            await send_information(event.ctx, button_id)

    if 'button_buy' in custom_id:
        item = custom_id.split('|')
        button_id = int(item[1])
        if db.is_user_exist(int(event.ctx.author.id)) is False:
            db.add_user(int(event.ctx.author.id))

        balance = db.get_balance(int(event.ctx.author.id))
        user = event.ctx.author

        if shop_items[button_id]['role_id'] in user.roles:
            embed = Embed(title=f"У вас уже есть эта роль!", color=Color.from_hex('#f21616'))
            return await event.ctx.send(embeds=[embed], ephemeral=True)

        if balance < int(shop_items[button_id]['price']):
            embed = Embed(title=f"Недостаточно средств. Баланс: {balance} <a:coin1:1098002431276761119>", color=Color.from_hex('#f21616'))
            return await event.ctx.send(embeds=[embed], ephemeral=True)

        db.minus_cash(int(event.ctx.author.id), shop_items[button_id]['price'])
        await user.add_role(shop_items[button_id]['role_id'], reason=f'Покупка {shop_items[button_id]["title"]}')
        embed = Embed(title=f"Роль успешно приобретена!", color=Color.from_hex(color_good))
        await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'create_clan_button':
        user_balance = db.get_balance(int(author.id))
        if user_balance >= create_clan_cost:
            inputs = [interactions.ShortText(label="Введите название клана", custom_id="clan_name", min_length=2, max_length=30)]
            modal = Modal(
                title="Создать клан",
                custom_id="clan_create_modal")

            modal.add_components(inputs)
            await event.ctx.send_modal(modal)
        else:
            embed = Embed(title=f"Недостаточно средств!", color=Color.from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

async def send_information(ctx, button):
    title, price, description = shop_items[button]['title'], \
                                shop_items[button]['price'], shop_items[button]['descriptions']

    fields =[EmbedField(
            name=f"Цена",
            value=f"{price} коинов"),
        EmbedField(
            name=f"Описание",
            value=description)]

    buttons = [
        interactions.Button(style=interactions.ButtonStyle.SUCCESS, label="Купить", custom_id=f"button_buy|{button}")
    ]

    embed = Embed(title=title, color=Color().from_hex('#a516f2'), fields=fields)
    await ctx.send(embeds=[embed], components=[buttons], ephemeral=True)

# @slash_command(name="create_clan",default_member_permissions=interactions.Permissions.ADMINISTRATOR, description="Создать клан", options = [{"name": "name", "description": "Название", "required": True, "type": OptionType.STRING}])
async def create_clan(ctx, name):
    clan_lead = ctx.author
    guild = ctx.guild

    role = await guild.create_role(name=name)
    clan_settings_channel_id = 1104343426641698886

    pw = PasswordGenerator()
    pw.maxlen = 5
    pw.minlen = 5
    pw.minschars = 0
    pw.minuchars = 0
    code = pw.generate()

    await clan_lead.add_role(role, reason='Создание клана')

    clan_settings_channel = bot.get_channel(clan_settings_channel_id)
    channel = await guild.create_channel(name=name, channel_type=ChannelType.GUILD_TEXT, category=1097490151862714459, reason='Создание клана')

    role_id = int(role.id)
    perms = [PermissionOverwrite(id=544171273438363648, type=0, deny=1024),
             PermissionOverwrite(id=role_id, type=0, allow=1024)]

    embed = Embed(title=f"Клан {name} был создан!",description=f'Создатель клана: <@{clan_lead.id}>\nКод-приглашение в клан: **{code}**',color=Color().from_hex(color_good))

    await channel.send(embeds=[embed])
    await channel.edit(permission_overwrites=perms)
    await clan_settings_channel.edit(permission_overwrites=[PermissionOverwrite(id=clan_lead, type=1, allow=Permissions.VIEW_CHANNEL)])

    channel_id = int(channel.id)
    db.minus_cash(int(clan_lead.id), create_clan_cost)
    db.create_clan(clan_name=name, clan_lead_id=int(clan_lead.id), code=code, chat_id=channel_id)

# @slash_command(name="post", description='12312', default_member_permissions=interactions.Permissions.ADMINISTRATOR)
# async def post_inv(ctx:InteractionContext):
#
#     embed = Embed(title=f"Вступление в клан",
#                   description=f'Для вступление в клан нажмите на кнопку',color=Color().from_hex('#f2e016'))
#
#     b = interactions.Button(style=interactions.ButtonStyle.SUCCESS, label="+", custom_id=f"show_modal_clan")
#     await ctx.channel.send(embeds=[embed], components=[b])

@slash_command(name="post_rooms", description="rooms", default_member_permissions=interactions.Permissions.ADMINISTRATOR)
async def post_rooms(ctx):
    print(ctx.author.voice)
    channel = ctx.channel

    buttons_emoji = ['<:lock1:1100538880173817957>', '<:unlock1:1100538856970920018>', '<:user_kick:1100548659277467658>',
                     '<:usersgroup1:1100537833485238354>', '<:mute1:1100546810881249400>', '<:unmute1:1100546833547268216>']

    embed = Embed(description=f"Настройки приватной комнаты\n\n\n" \
                              f"{buttons_emoji[1]} - **Открыть комнату**\n\n" \
                              f"{buttons_emoji[0]} - **Закрыть комнату**\n\n" \
                              f"{buttons_emoji[2]} - **Запретить пользователю вход в комнату**\n\n"
                              f"{buttons_emoji[3]} - **Изменить лимит пользователей**\n\n"
                              f"{buttons_emoji[4]} - **Замутить пользователя**\n\n"
                              f"{buttons_emoji[5]} - **Размутить пользователя**\n\n", color=Color().from_hex(color_default))

    b = [interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[1], custom_id=f"room_open"),
         interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[0], custom_id=f"room_close"),
         interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[2], custom_id=f"room_kick"),
         interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[3], custom_id=f"room_limit"),
         interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[4], custom_id=f"room_mute")]

    b2 = [interactions.Button(style=interactions.ButtonStyle.BLURPLE, emoji=buttons_emoji[5], custom_id=f"room_unmute")]

    await channel.send(embeds=[embed], components=[b,b2])

async def is_user_creator_channel(user):
    if user.voice:
        channel_create = 1098014043131875448
        private_category = 1098011369548292117  # private rooms
        current_channel = user.voice.channel
        perms = user.channel_permissions(current_channel)

        if current_channel.category == private_category and current_channel.id != channel_create:
            if perms.PRIORITY_SPEAKER:
                return True

    return False

async def unmute_from_room(user):
    if user.mute:
        current_channel = user.voice.channel
        perms = user.channel_permissions(current_channel)
        mute_role = 1100517295375261696

        if perms.SPEAK and user.has_role(mute_role) is False:
            await user.edit(mute=False)

async def is_private_room(user):
    if user.voice:
        channel_create = 1098014043131875448
        private_category = 1098011369548292117 #private rooms
        current_channel = user.voice.channel

        if current_channel.category == private_category and current_channel.id != channel_create:
            return True

    return False

@listen('ModalCompletion')
async def modals(event:ModalContext):
    # print(dir(event.ctx))
    guild = event.ctx.guild
    custom_id = event.ctx.custom_id
    user = event.ctx.author

    if custom_id == 'room_limit_modal':
        channel = user.voice.channel
        c = event.ctx.responses
        inp = int(c['room_limit_input'])
        if inp > 99:
            inp = 99

        await channel.edit(user_limit = inp)
        embed = Embed(description=f"Лимит пользователей изменен!",color=Color().from_hex(color_good))
        await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'clan_create_modal':
        c = event.ctx.responses
        clan_name = c['clan_name'].lower()
        clan = db.is_clan_exist(name=str(clan_name).lower())
        if clan:
            embed = Embed(description=f"Клан с таким название уже есть!", color=Color().from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)
        else:
            embed = Embed(title='Вы успешно создали клан', description=f"Для вашего клана созданно отдельный чат", color=Color().from_hex(color_good))
            await event.ctx.send(embeds=[embed], ephemeral=True)

            await create_clan(event.ctx, clan_name)

    if custom_id == 'show_modal_buy_role':
        resp = event.ctx.responses
        role_name = resp['private_role_name']
        role_color = str(resp['private_role_color']).strip()

        guild = event.ctx.guild
        role = await guild.create_role(name=role_name, hoist=True, color=Color().from_hex(role_color))
        await user.add_role(role)

        embed = Embed(title=f'Вы успешно создали роль {role_name}',color=Color().from_hex(color_good))
        await event.ctx.send(embeds=[embed], ephemeral=True)

    if custom_id == 'clan_invite_modal':
        c = event.ctx.responses
        invite_code = c['clan_code']
        clan = db.is_clan_exist(code=invite_code)
        if len(clan):

            role_name = clan[0][1]
            role = utils.get(guild.roles, name=role_name)

            if user.has_role(role):
                embed_error = Embed(title=f"Вы уже состоите в этом клане!", color=Color().from_hex(color_error))
                return await event.ctx.send(embeds=[embed_error], ephemeral=True)

            await user.add_role(role, reason='Вступление в клан')

            chat_id = clan[0][5]
            channel = bot.get_channel(chat_id)
            embed = Embed(description=f"<@{event.ctx.author.id}> присоеденился к клану!",color=Color().from_hex('#f2e016'))
            embed2 = Embed(title=f"Вы успешно вступили в клан {role_name}",color=Color().from_hex('#13ed67'))
            await channel.send(embeds=[embed])
            await event.ctx.send(embeds=[embed2], ephemeral=True)
        else:
            embed = Embed(title=f"Неверный код!", color=Color().from_hex(color_error))
            await event.ctx.send(embeds=[embed], ephemeral=True)

bot.start('***')

Traceback

GET::https://discord.com/api/v10/users/@me: 401 Traceback (most recent call last): File "D:\Proggs\Python10\lib\site-packages\interactions\api\http\http_client.py", line 533, in login result = await self.request(Route("GET", "/users/@me")) File "D:\Proggs\Python10\lib\site-packages\interactions\api\http\http_client.py", line 450, in request await self._raise_exception(response, route, result) File "D:\Proggs\Python10\lib\site-packages\interactions\api\http\http_client.py", line 471, in _raise_exception raise HTTPException(response, response_data=result, route=route) interactions.client.errors.HTTPException: HTTPException: 401|Unauthorized || 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "D:\Dev\python\SRC\DiscordWalletBot\MainBot.py", line 650, in bot.start('MTA5NjEzMTQ2MDQ4Nzk3MDg1Nw.GCs6XD.MqtnaXgXhWhnXAI3xzMvmJdEUrX-D65JzrarT8') File "D:\Proggs\Python10\lib\site-packages\interactions\client\client.py", line 977, in start asyncio.run(self.astart(token)) File "D:\Proggs\Python10\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "D:\Proggs\Python10\lib\asyncio\base_events.py", line 646, in run_until_complete return future.result() File "D:\Proggs\Python10\lib\site-packages\interactions\client\client.py", line 933, in astart await self.login(token) File "D:\Proggs\Python10\lib\site-packages\interactions\client\client.py", line 915, in login me = await self.http.login(self.token) File "D:\Proggs\Python10\lib\site-packages\interactions\api\http\http_client.py", line 537, in login raise LoginError("An improper token was passed") from e interactions.client.errors.LoginError: An improper token was passed Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0000024F69D99C30> Unclosed connector connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000024F69DB4B20>, 384162.046)]', '[(<aiohttp.client_proto.ResponseHandler object at 0x0000024F69DB4F40>, 384162.312)]'] connector: <aiohttp.connector.TCPConnector object at 0x0000024F69D98D00> Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000024F67B049D0> Traceback (most recent call last): File "D:\Proggs\Python10\lib\asyncio\proactor_events.py", line 116, in del File "D:\Proggs\Python10\lib\asyncio\proactor_events.py", line 108, in close File "D:\Proggs\Python10\lib\asyncio\base_events.py", line 750, in call_soon File "D:\Proggs\Python10\lib\asyncio\base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed Fatal error on SSL transport protocol: <asyncio.sslproto.SSLProtocol object at 0x0000024F69DE46A0> transport: <_ProactorSocketTransport fd=624 read=<_OverlappedFuture cancelled>> Traceback (most recent call last): File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 690, in _process_write_backlog self._transport.write(chunk) File "D:\Proggs\Python10\lib\asyncio\proactor_events.py", line 361, in write self._loop_writing(data=bytes(data)) File "D:\Proggs\Python10\lib\asyncio\proactor_events.py", line 397, in _loop_writing self._write_fut = self._loop._proactor.send(self._sock, data) AttributeError: 'NoneType' object has no attribute 'send' Exception ignored in: <function _SSLProtocolTransport.del at 0x0000024F67651990> Traceback (most recent call last): File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 321, in del File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 316, in close File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 599, in _start_shutdown File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 604, in _write_appdata File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 712, in _process_write_backlog File "D:\Proggs\Python10\lib\asyncio\sslproto.py", line 726, in _fatal_error File "D:\Proggs\Python10\lib\asyncio\proactor_events.py", line 151, in _force_close File "D:\Proggs\Python10\lib\asyncio\base_events.py", line 750, in call_soon File "D:\Proggs\Python10\lib\asyncio\base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed

Process finished with exit code 1

Checklist

Additional Information

No response

LordOfPolls commented 1 year ago

Please read the traceback interactions.client.errors.LoginError: An improper token was passed

LordOfPolls commented 1 year ago

In your previous issue, you leaked your token, so GitHub reported it to Discord who promptly invalidated it. You would have received an email about this image