Wolf_Yout
@Wolf_Yout

Что делать если dislash начал жаловаться на пропущеный аргумент ctx, хотя раньше этого не происходило?

Вот код НА ВСЕ слэш-команды:
class Music(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.voice_states = {}

    def get_voice_state(self, ctx: commands.Context):
        state = self.voice_states.get(ctx.guild.id)
        if not state:
            state = VoiceState(self.bot, ctx)
            self.voice_states[ctx.guild.id] = state

        return state

    def cog_unload(self):
        for state in self.voice_states.values():
            self.bot.loop.create_task(state.stop())

    def cog_check(self, ctx: commands.Context):
        if not ctx.guild:
            raise commands.NoPrivateMessage(
                'Эта команда не используется в ЛС (Личные сообщения)')

        return True

    async def cog_before_invoke(self, ctx: commands.Context):
        ctx.voice_state = self.get_voice_state(ctx)

    async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
        await ctx.send('Ошибка: {}'.format(str(error)))

    @slash_command(name="join",description="Войти в голосовой канал")
    async def _join(self, ctx: commands.Context):
        """Подключается к голосовому каналу."""
        ctx.voice_state = self.get_voice_state(ctx)

        destination = ctx.author.voice.channel
        if ctx.voice_state.voice:
            await ctx.voice_state.voice.move_to(destination)
            return

        ctx.voice_state.voice = await destination.connect()

    @slash_command(name='leave', description="Выйти из войс канала")
    async def _leave(self, ctx: commands.Context):
        """Очистить очередь и заставить бота уйти."""
        ctx.voice_state = self.get_voice_state(ctx)

        if not ctx.voice_state.voice:
            return await ctx.send('Бот и так не подключен. Зачем его кикать?')

        await ctx.voice_state.stop()
        await ctx.send('Пока!')
        del self.voice_states[ctx.guild.id]

    @slash_command(name='volume',description="Настроить громкость(После настройки введите replay)",options=[Option("volume", "Укажите значение.")])
    async def _volume(self, ctx: commands.Context, *, volume: int = None):
        """Изменить громкость. Возможные значения(0-200)"""
        ctx.voice_state = self.get_voice_state(ctx)

        if not volume:
            return await ctx.reply('Ошибка: Пропушен обязательный аргумент volume(Громкость)\nПримерное использование:\nm!volume 35')

        if not ctx.voice_state.is_playing:
            return await ctx.send('Сейчас музыка не играет. Можете включить.')

        if 0 > volume > 100:
            return await ctx.send('Volume must be between 0 and 100')

        ctx.voice_state.volume = volume / 100
        await ctx.send('Громкость изменена на {}%'.format(volume))

    @slash_command(name="now",description="Что сейчас играет?")
    async def _now(self, ctx: commands.Context):
        """Увидеть, какая песня играет прямо сейчас"""
        ctx.voice_state = self.get_voice_state(ctx)

        await ctx.send(embed=ctx.voice_state.current.create_embed())

    @slash_command(name='skip',description="Пропустить.")
    async def _skip(self, ctx: commands.Context):
        """Проголосуйте за то, чтобы пропустить песню. Запрашивающий может автоматически пропустить.
 Для пропуска песни необходимо 3 пропущенных голоса.Если вы админ то песня скипнетса сразу же.
        """
        ctx.voice_state = self.get_voice_state(ctx)

        if not ctx.voice_state.is_playing:
            return await ctx.send('Сейчас музыка не играет,зачем её пропускать? Можете включить.')

        if len(ctx.voice_state.songs) == 0:
            return await ctx.send('В очереди нет треков. Можете добавить.')

        if not ctx.voice_state.voice:
            await ctx.reply("Не удалось воспроизвести строку `if not ctx.voice_state.voice:`.")

        if (ctx.voice_state.current.requester):
            await ctx.message.add_reaction('⏭')
            ctx.voice_state.skip()

    @slash_command(name="queue",description="Посмотреть очередь.")
    async def _queue(self, ctx: commands.Context, *, page: int = 1):
        """Показывает очередь песен.
 Вы можете дополнительно указать страницу для отображения. Каждая страница содержит 10 элементов.
        """
        ctx.voice_state = self.get_voice_state(ctx)

        if len(ctx.voice_state.songs) == 0:
            return await ctx.send('В очереди нет треков. Можете добавить.')

        items_per_page = 10
        pages = math.ceil(len(ctx.voice_state.songs) / items_per_page)

        start = (page - 1) * items_per_page
        end = start + items_per_page

        queue = ''
        for i, song in enumerate(ctx.voice_state.songs[start:end], start=start):
            queue += '`{0}.` [**{1.source.title}**]({1.source.url})\n'.format(i + 1, song)

        embed = (discord.Embed(description='**{} tracks:**\n\n{}'.format(len(ctx.voice_state.songs), queue))
                 .set_footer(text='Viewing page {}/{}'.format(page, pages)))
        await ctx.send(embed=embed)

    @slash_command(name='remove',description='Удалить песню.')
    async def _remove(self, ctx: commands.Context, index: int = None):
        ctx.voice_state = self.get_voice_state(ctx)
        """Удалить песни из очереди по номеру.Использование:.remove <Какая песня по очереди>"""

        if not index:
            return await ctx.reply('Ошибка: Пропушен обязательный аргумент index(Айди песни)\nПримерное использование:\nm!remove 1')

        if len(ctx.voice_state.songs) == 0:
            return await ctx.send('В очереди нет треков. Можете добавить.')

        ctx.voice_state.songs.remove(index - 1)
        await ctx.message.add_reaction('✅')

    @slash_command(name='play', description="Воспроизвести.", options=[Option("search", "А что мне искать то?", required=True)])
    async def _play(self, ctx: commands.Context, *, search: str = None):
            ctx.voice_state = self.get_voice_state(ctx)

            if not search:
                return await ctx.reply('Ошибка: Пропушен обязательный аргумент search(URL/Текст)\nПримерное использование:\nm!play lum!x slowed reverb')

            if not ctx.voice_state.voice:
                await ctx.reply("Не удалось воспроизвести строку `if not ctx.voice_state.voice:`.\nВозможно поможет: Требуеться ввести сначала /join")

            try:
                source = await YTDLSource.create_source(ctx,
                                                        search,
                                                        loop=self.bot.loop)
            except YTDLError as e:
                await ctx.send('Ошибка: {}'.format(str(e)))
            else:
                song = Song(source)

                await ctx.voice_state.songs.put(song)
                # row_of_buttons = ActionRow(
                #     Button(style=ButtonStyle.red, label="Replay", custom_id="re"))
                await ctx.reply(f'Добавлено {source}')
                # while True:
                #     await bot.wait_for('button_click')

                #     try:
                #         source2 = await YTDLSource.create_source(ctx,
                #                                                 self.current.now_name(),
                #                                                 loop=self.bot.loop)
                #     except YTDLError as e:
                #         await ctx.send('Ошибка: {}'.format(str(e)))
                #     else:
                #         song2 = Song(source2)

                #         await ctx.voice_state.songs.put(song2)
                #         ctx.voice_state.skip()

    @slash_command(name="replay",description="Воспроизвести заново.")
    async def _re(self, ctx: commands.Context):
        ctx.voice_state = self.get_voice_state(ctx)
        try:
            source2 = await YTDLSource.create_source(ctx,
                                                    ctx.voice_state.current.now_name(),
                                                    loop=self.bot.loop)
        except YTDLError as e:
            await ctx.send('Ошибка: {}'.format(str(e)))
        else:
            song2 = Song(source2)

            await ctx.voice_state.songs.put(song2)
            ctx.voice_state.skip()
            await ctx.reply(f'<:succes_title:925401308813471845>')


Уточнение ошибки:
TypeError: _play() missing 1 required positional argument: 'ctx'
  • Вопрос задан
  • 52 просмотра
Пригласить эксперта
Ваш ответ на вопрос

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

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