Discord.Py上的KeyError

问题描述 投票:0回答:1
@client.command(description="Pauses the current playing track. Can be resumed with `!resume`.", 
brief="Pauses current track.",aliases=['PAUSE'])
async def pause(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].pause()

@client.command(description="Resumes the current playing track. Can only be used if current track has 
been paused.",
    brief="Resumes current track.",
    aliases=['RESUME','continue','CONTINUE'])
async def resume(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].resume()

@client.command(description="Stops the current playing track.",
     brief="Stops current track.",
     aliases=['STOP'])
async def stop(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].stop()

[当我尝试使用暂停,停止和恢复命令时,它给了我KeyError。触发该错误的整个代码就在这里。错误像这样出现:

忽略命令停止中的异常:追溯(最近一次通话):文件“ C:\ Users \ emirs \ PycharmProjects \ discordmasterbot \ venv \ lib \ site-packages \ discord \ ext \ commands \ core.py”,第83行,已包装ret =等待coro(* args,** kwargs)在停止位置的文件“ C:/Users/emirs/PycharmProjects/discordmasterbot/MASTERBOT.py”,第163行玩家[guild_id] .stop()KeyError:708748879079932016

还有另一种错误类型:

追踪(最近通话):调用中的文件“ C:\ Users \ emirs \ PycharmProjects \ discordmasterbot \ venv \ lib \ site-packages \ discord \ ext \ commands \ bot.py”,行892等待ctx.command.invoke(ctx)调用中的文件“ C:\ Users \ emirs \ PycharmProjects \ discordmasterbot \ venv \ lib \ site-packages \ discord \ ext \ commands \ core.py”,行797等待注入(* ctx.args,** ctx.kwargs)文件“ C:\ Users \ emirs \ PycharmProjects \ discordmasterbot \ venv \ lib \ site-packages \ discord \ ext \ commands \ core.py”,第92行,已包装从ex引发CommandInvokeError(exc)discord.ext.commands.errors.CommandInvokeError:命令引发了异常:KeyError:708748879079932016

python discord.py keyerror
1个回答
1
投票

KeyError表示找不到该对象的密钥。在这种情况下,行会ID 708748879079932016players中不存在。

尝试在此处添加一个try / except块来捕获任何一个。

@client.command(description="Pauses the current playing track. Can be resumed with `!resume`.", 
brief="Pauses current track.",aliases=['PAUSE'])
async def pause(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].pause()
    except KeyError:
        # do something that adds the guild ID to players #

@client.command(description="Resumes the current playing track. Can only be used if current track has 
been paused.",
    brief="Resumes current track.",
    aliases=['RESUME','continue','CONTINUE'])
async def resume(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].resume()
    except KeyError:
        # do something that adds the guild ID to players #

@client.command(description="Stops the current playing track.",
     brief="Stops current track.",
     aliases=['STOP'])
async def stop(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].stop()
    except KeyError:
        # do something that adds the guild ID to players #
© www.soinside.com 2019 - 2024. All rights reserved.