@Timoha0620

Как сделать применение кнопок и выпадающего списка к одному сообщению на disnake.py?

Я делаю discord бота и мне нужна применить кнопку и выпадающий список к одному сообщению, как показано ниже:
iHmED.jpg

Пытаюсь сделать так:

class MyModal(disnake.ui.Modal):
    def __init__(self):
        # The details of the modal, and its components
        components = [
            disnake.ui.TextInput(
                label="Изменение статуса",
                placeholder="Введите ваш новый статус",
                custom_id="customStatus",
                style=TextInputStyle.short,
                max_length=12,
            )
        ]
        super().__init__(title="Новый статус", components=components)

    async def callback(self, inter: disnake.ModalInteraction):
        customStatusName = str(inter.text_values['customStatus'])
        # print(status)
        cursor.execute('UPDATE users SET customStatus = "{}" WHERE id = {}'.format(f"{customStatusName}", inter.author.id))
        connection.commit()
        await inter.send("Вы успешно поменяли статус!", ephemeral=True)

class EditStatus(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.value: Optional[bool] = None

    @disnake.ui.button(label="Изменить статус", style=disnake.ButtonStyle.grey)
    async def cancel(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
        await inter.response.send_modal(modal=MyModal())
        self.value = False

class Dropdown(disnake.ui.StringSelect):
    def __init__(self):
        options = [
            disnake.SelectOption(label="Сюрикен", description='значок на баннере'),
            disnake.SelectOption(label="Мечи", description='значок на баннере'),
            disnake.SelectOption(label="Корона", description='значок на баннере'),
            disnake.SelectOption(label="Цветок", description='значок на баннере'),
            disnake.SelectOption(label="Звезда", description='значок на баннере'),
        ]
        
        super().__init__(
            placeholder="Выбрать значок...",
            min_values=1,
            max_values=1,
            options=options
        )

    async def callback(self, inter: disnake.MessageInteraction):
        if self.values[0] == 'Сюрикен':
            cursor.execute('UPDATE users SET customBadge = "{}" WHERE id = {}'.format('knife', inter.author.id))
            connection.commit()
        if self.values[0] == 'Мечи':
            cursor.execute('UPDATE users SET customBadge = "{}" WHERE id = {}'.format('fight', inter.author.id))
            connection.commit()
        if self.values[0] == 'Корона':
            cursor.execute('UPDATE users SET customBadge = "{}" WHERE id = {}'.format('crown', inter.author.id))
            connection.commit()
        if self.values[0] == 'Цветок':
            cursor.execute('UPDATE users SET customBadge = "{}" WHERE id = {}'.format('flower', inter.author.id))
            connection.commit()
        if self.values[0] == 'Звезда':
            cursor.execute('UPDATE users SET customBadge = "{}" WHERE id = {}'.format('star', inter.author.id))
            connection.commit()

        await inter.response.send_message(f'Вы успешно поменяли значок на **{self.values[0]}**', ephemeral=True)

class DropdownView(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(Dropdown())

@bot.slash_command()
async def profile(inter, участник: disnake.Member = None):
    """
    Профиль пользователя

    Parameters
    ----------
    участник: Участник, у которого вы хотите посмотреть профиль.
    """
    if участник == None:
        profileEmbed = disnake.Embed(
            title=f'Профиль — {inter.author}',
            description='```Lorem Ipsum```',
            color=0x2b2d31
        )

        profileEmbed.set_thumbnail(url=inter.author.avatar.url)
        view = DropdownView(), EditStatus()
        await inter.send(embed=profileEmbed, view=view)


Выдает ошибку:
Command raised an exception: AttributeError: 'tuple' object has no attribute 'to_components'
  • Вопрос задан
  • 751 просмотр
Решения вопроса 1
fenrir1121
@fenrir1121 Куратор тега discord.py
Начни с документации
Так же как по отдельности.

Помимо декоратора @button, никто не запрещает их передавать в View как компоненты
components=[
            disnake.ui.Button(label="Yes", style=disnake.ButtonStyle.success, custom_id="yes"),
            disnake.ui.Button(label="No", style=disnake.ButtonStyle.danger, custom_id="no"),
        ],


Открывайте примеры и документацию.

Что до ошибки по строчке view = DropdownView(), EditStatus() видно, что вы пытаетесь передать кортеж в inter.send() вместо disnake.ui.View, о чем вам явно указано в ошибке.

На будущее прикладывайте полные логи, а изображения и портянку кода убирайте в спойлер.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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