【问题标题】:discord py 'keyerror' (discord components, slash commands)discord py 'keyerror'(不和谐组件,斜线命令)
【发布时间】:2021-09-08 15:51:05
【问题描述】:

我正在尝试通过添加斜杠命令和按钮来使用机器人。这一次,斜杠命令按预期工作。但是每次我运行命令时,我都会收到这样的警告。我不确定问题是什么。这是代码的一部分。

    Ignoring exception in on_socket_response
Traceback (most recent call last):
  File "/home/yuna21724/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/yuna21724/.local/lib/python3.8/site-packages/discord_buttons_plugin/__main__.py", line 17, in soclistener
    await self.emit(data["data"]["custom_id"], data)
KeyError: 'custom_id'


    import discord
    import asyncio
    import SeagamiCommandsListening
    import SeagamiNotice
    import SeagamiCharacter
    from discord_buttons_plugin import *
    from discord.ext import commands
    from discord_buttons_plugin import *
    from discord_slash import SlashCommand
    from discord import Intents
    from discord_components.client import DiscordComponents

    token = ""
    seagami = commands.Bot(command_prefix='.', intents = Intents.all())
    slash = SlashCommand(seagami, sync_commands = True)
    buttons = ButtonsClient(seagami)

    @seagami.event
    async def on_ready():
        DiscordComponents(seagami)
        await seagami.change_presence(status=discord.Status.online)
        print('[알림]디스코드 봇 서비스가 시작되었습니다...', 
    seagami.user.name)
        while True:
            if SeagamiNotice.a['title'] == SeagamiNotice.b['title']:
                print('')
            else:
                embed = discord.Embed(color = 0x2F3136)
                embed.add_field(name = "```????로스트아크 공지사항```", 
     value = "``????로스트아크 점검 시, 봇의 기능이 제한됩니다.``", inline = 
    False)
                embed.add_field(name = f"```???? 
    {SeagamiNotice.a['title']}```", value = '``???? 추가 정보를 확인하려면 
    아래의 바로가기 버튼을 눌러주세요.``', inline = False)
                components_notice = [Button(label = "바로가기", style = 
    5, url = f"{SeagamiNotice.a['Link']}")]
                await 
    seagami.get_channel(int(878004091505221643)).send(embed = embed, 
     components = components_notice)
            await asyncio.sleep(335)
      
    @seagami.event
    async def on_member_join(member):
        message_ = "<@{}>".format(str(member.id))
        embed = discord.Embed(color = 0x2F3136)
        embed.add_field(name = "```????환영해요.```", value = f"``???? 
   ``{message_}``님, 새가미와 아이들에 오신 걸 환영합니다.``", inline = 
    False)
        buttons = [Button(label = "역할 받기", style = 2, custom_id = 
    "role")]
        await seagami.get_channel(int(879993490996600852)).send(embed = 
    embed, components = buttons)
        await 
 
 
 
 member.add_roles(seagami.get_guild(int(870543165004849152)).get_role(int( 
   870552731419566111))) 

    @slash.slash(name="입장", description="새가미 봇이 음성채널로 이동합니 
   다.", guild_ids=[870543165004849152])
    async def in_voice(ctx: SlashCommand):
        try:
            if (ctx.channel.id == int(878003511961464883)):
                await 
    SeagamiCommandsListening.commands_Listening.in_(ctx)
                await ctx.reply('``????``새가미 봇이 음성채널로 이동하였습니 
   다.')
        except:
            await ctx.reply('``????``해당 명령어는 여기서 사용할 수 없습니 
   다.')

     @slash.slash(name="퇴장", description="새가미 봇이 음성채널에서 퇴장 
   합니다.", guild_ids=[870543165004849152])
    async def out_voice(ctx: SlashCommand):
        try:
            if (ctx.channel.id == int(878003511961464883)):
                await 
         `enter code here`SeagamiCommandsListening.commands_Listening.out_(ctx)
                await ctx.reply('``????``새가미 봇이 음성채널에서 퇴장하였습 
   니다.')
        except:
            await ctx.reply('``????``해당 명령어는 여기서 사용할 수 없습니 
   다.')

    @slash.slash(name="재생", description="새가미 봇을 통해 노래를 재생할 
    수 있습니다.", guild_ids=[870543165004849152])
    async def play_voice(ctx: SlashCommand, 링크):
        try:
            if (ctx.channel.id == int(878003511961464883)):
                 await 
    SeagamiCommandsListening.commands_Listening.play_(ctx, 링크)
                await ctx.reply('``????``신청하신 노래를 ``1회``재생 합니 
   다.')
            await buttons.send(
            content = "아래의 버튼을 눌러 ``????명령어``를 사용하실 수 있습니다.", 
            channel = ctx.channel.id,
            components = [
                ActionRow([
                        Button(label = "일시 정지", style = 1, custom_id = "button_pause"), 
                        Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
                        Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
                        ]
                        )])
    except:
        await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')

@slash.slash(name="반복재생", description="새가미 봇을 통해 노래를 반복 재생할 수 있습니다.", guild_ids=[870543165004849152])
async def replay_voice(ctx: SlashCommand, 링크):
    try:
        if (ctx.channel.id == int(878003511961464883)):
            await SeagamiCommandsListening.commands_Listening.replay_(ctx, 링크)
            await ctx.reply('``????``신청하신 노래를 반복 재생 합니다.')
            await buttons.send(
            content = "아래의 버튼을 눌러 ``????명령어``를 사용하실 수 있습니다.", 
            channel = ctx.channel.id,
            components = [
                ActionRow([
                        Button(label = "일시 정지", style = 1, custom_id = "button_pause"), 
                        Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
                        Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
                        ]
                        )])
    except:
        await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')

@slash.slash(name="검색", description="캐릭터 정보를 검색 할 수 있습니다.", guild_ids=[870543165004849152])
async def search_(ctx: SlashCommand, 캐릭터명):
    if (ctx.channel.id == int(882916863779168267)):
            await SeagamiCharacter.search_info.info_(ctx, 캐릭터명)
            if SeagamiCharacter.code['code'] != '100':
                embed = discord.Embed(color = 0x2F3136)
                embed.add_field(name = f"> ```????{SeagamiCharacter.name_['name']}```", value = f"> ``????{SeagamiCharacter.class_info['class']}``", inline = False)
                embed.add_field(name = "```????캐릭터 레벨```", value = f"``Lv. {SeagamiCharacter.Level_['Level'][8:]}``", inline = True)
                embed.add_field(name = "```????원정대 레벨```", value = f"``Lv. {SeagamiCharacter.expedition_Level['expedition'][9:]}``", inline = True)
                embed.add_field(name = "```????아이템 레벨```", value = f"``Lv. {SeagamiCharacter.item_Level['item_Level'][12:]}``", inline = True)
                embed.add_field(name = "> ```????특성```", value = "> ``????펫 효과가 적용 된 특성입니다.``", inline = False)
                embed.add_field(name = "```????치명```", value = f"``{SeagamiCharacter.ability_battle['ability_battle1']}``", inline = True)
                embed.add_field(name = "```????특화```", value = f"``{SeagamiCharacter.ability_battle['ability_battle3']}``", inline = True)
                embed.add_field(name = "```????제압```", value = f"``{SeagamiCharacter.ability_battle['ability_battle5']}``", inline = True)
                embed.add_field(name = "```????신속```", value = f"``{SeagamiCharacter.ability_battle['ability_battle7']}``", inline = True)
                embed.add_field(name = "```????인내```", value = f"``{SeagamiCharacter.ability_battle['ability_battle9']}``", inline = True)
                embed.add_field(name = "```????숙련```", value = f"``{SeagamiCharacter.ability_battle['ability_battle11']}``", inline = True)
                embed.add_field(name = "> ```????각인```", value = "> ``????현재 사용중인 각인입니다.``", inline = False)
                try:
                    for count in range(8):
                        embed.add_field(name = "```????각인```", value = f"``{SeagamiCharacter.ability_engrave[f'ability_engrave{count}']}``", inline = True)
                except:
                    components_ = [[
                                    Button(label = "바로가기", style = 5, url = f'https://lostark.game.onstove.com/Profile/Character/{캐릭터명}')
                                    ]]
                    await ctx.reply(f'``????{캐릭터명}``검색이 완료되었습니다.')
                    await seagami.get_channel(int(882916863779168267)).send(embed = embed, components = components_)
            else:
                await ctx.reply('``????``로스트아크 점검 중 입니다.')
                SeagamiCharacter.code['code'] = '200'          
    else:
        await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')

@buttons.click
async def button_pause(ctx):
    await SeagamiCommandsListening.commands_Listening.pause_()
    await ctx.reply('``????``노래가 일시 정지 되었습니다.')

@buttons.click
async def button_resume(ctx):
    await SeagamiCommandsListening.commands_Listening.resume_()
    await ctx.reply('``????``노래가 다시 재생 되고 있습니다.')      

@buttons.click
async def button_stop(ctx):
    await SeagamiCommandsListening.commands_Listening.stop_()  
    await ctx.reply('``????``재생중인 노래를 종료 하였습니다.')

seagami.run(token)

enter image description here

enter image description here

enter image description here

enter image description here

【问题讨论】:

  • 请将您的代码复制并粘贴到帖子中,不要只是截图。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: discord.py


【解决方案1】:

当在现有键集中找不到映射(字典)键时,会引发 KeyError

如果您不确定收到KeyError 的原因,可以采取以下措施

  • 打印字典看看里面有什么
  • 检查密钥是否符合您的预期

如果要在键不在字典中时为值提供默认值,可以使用dict.get,默认为None

>>> person["pets"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pets'
>>> person.get("pets")
>>> person.get("pets", [])
[]

文档:

有用的链接:https://realpython.com/python-keyerror/%3E


我相信您的错误原因是您安装的名为 discord_buttons_plugin 的第 3 方软件包,据我所知 要求您将 custom_id 添加到除 @ 之外的所有按钮987654331@。在您的 _search 命令中,您忘记添加它,这会导致包代码中的错误。尝试将custom_id 添加到那里的按钮。


长话短说 尝试在_search 命令的按钮组件中添加custom_id

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 2022-12-19
    • 2021-11-20
    • 2022-10-20
    • 2023-03-17
    • 2021-05-09
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多