@MARCUS27

Непонятная ошибка KeyError, как исправить?

При попытке вывести новую песню в очередь вылазит ошибка
Connected
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Usersарина\Desktop\python\lib\site-packages\discord\ext\commands\cor
e.py", line 85, in wrapped
ret = await coro(args, **kwargs)
File "C:\Usersарина\Desktop\workбот\1-тестер\musicAV.py", line 76, in play
queue_len = len(self.song_queue[ctx.guild.id])
KeyError: 902227097647468664

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

Traceback (most recent call last):
File "C:\Usersарина\Desktop\python\lib\site-packages\discord\ext\commands\bot
.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Usersарина\Desktop\python\lib\site-packages\discord\ext\commands\cor
e.py", line 863, in invoke
await injected(ctx.args, **ctx.kwargs)
File "C:\Usersарина\Desktop\python\lib\site-packages\discord\ext\commands\cor
e.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Key
Error: 902227097647468664
Task exception was never retrieved
future: at C:\Users\арина\Desktop\work\бот\1-тестер\musicAV.py:23> exception=KeyError(90
2227097647468664)>
Traceback (most recent call last):
File "C:\Usersарина\Desktop\workбот\1-тестер\musicAV.py", line 24, in check
queue
if len(self.song_queue[ctx.guild.id]) > 0:
KeyError: 902227097647468664

async def check_queue(self, ctx):
        if len(self.song_queue[ctx.guild.id]) > 0:
            await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
            self.song_queue[ctx.guild.id].pop(0)


@commands.command()
    async def play(self, ctx, *, song=None):
        if song is None:
            return await ctx.send("You must include a song to play.")

        if ctx.voice_client is None:
            return await ctx.send("I must be in a voice channel to play a song.")

        # handle song where song isn't url
        if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
            await ctx.send("Searching for song, this may take a few seconds.")

            result = await self.search_song(1, song, get_url=True)

            if result is None:
                return await ctx.send("Sorry, I could not find the given song, try using my search command.")

            song = result[0]

        if ctx.voice_client.source is not None:
            queue_len = len(self.song_queue[ctx.guild.id])

            if queue_len < 10:
                self.song_queue[ctx.guild.id].append(song)
                return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")

            else:
                return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")

        await self.play_song(ctx, song)
        await ctx.send(f"Now playing: {song}")
  • Вопрос задан
  • 1221 просмотр
Пригласить эксперта
Ответы на вопрос 1
Vindicar
@Vindicar
RTFM!
queue_len = len(self.song_queue[ctx.guild.id])
KeyError: 902227097647468664

Число выглядит как id в дискорде. KeyError обычно случается, когда пытаешься обратиться к несуществующему ключу в словаре. В указанной строке кода есть кусочек, который выглядит как обращение к словарю: self.song_queue[ctx.guild.id]
Вывод: в словаре self.song_queue нет ключа для того сервера (ctx.guild) с которого пришла команда боту. А вот почему его там нет, и почему нет логики, предусматривающей этот сценарий - это уже вопрос к вам.
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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