繁体   English   中英

从 python 字典中的列表中检索值时遇到问题

[英]trouble retrieving value from list inside a python dictionary

因此,我正在使用 py-cord 在 python 中开发 discord 机器人,并且我已经实现了 openai api 以允许用户查询 AI 并修改不同的权重和偏差。 我想要做的是使权重特定于每个公会,因此一个服务器中的人可以对不同服务器中的人有不同的设置。 为了实现这一点,我尝试使用一个字典,其中公会 ID 是键,权重作为值在列表中,但我不断收到 KeyError 异常。

import os
import discord
import openai
import re
import asyncio
from discord.ext import commands
from gtts import gTTS
from discord import FFmpegPCMAudio
from mutagen.mp3 import MP3

bot = discord.Bot(intents=discord.Intents.default())

guilds = {}

@bot.event
async def on_ready():
    bot.temp = 1
    bot.topp = 0.5
    bot.freqpen = 0.3
    bot.prespen = 0.3
    x = datetime.datetime.now()
    print('logged in as {0.user} at'.format(bot), x, "\n")

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label=f"Temperature. Current: {bot.temp}"))
        self.add_item(discord.ui.InputText(label=f"Frequency Penalty. Current: {bot.freqpen}"))
        self.add_item(discord.ui.InputText(label=f"Presence Penalty. Current: {bot.prespen}"))
        self.add_item(discord.ui.InputText(label=f"Top P. Current: {bot.topp}"))

    async def callback(self, interaction: discord.Interaction):
        guilds[f'{bot.id}'] = [self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value]
        embed = discord.Embed(title="New GPT-3 weights and biases", color=0xFF5733)
        embed.add_field(name=f"Temperature: {bot.temp}", value="Controls randomness: Lowering results in less random completions. I recommend not going higher than 1.", inline=False)
        embed.add_field(name=f"Frequency Penalty: {bot.freqpen}", value="How much to penalize new tokens based on their existing frequency in the text so far. ", inline=False)
        embed.add_field(name=f"Presence Penalty: {bot.prespen}", value="How much to penalize new tokens based on whether they appear in the text so far. Increases the model's likelihood to talk about new topics. Will not function above 2.", inline=False)
        embed.add_field(name=f"Top P: {bot.topp}", value="Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered. Will not function above 1.", inline=False)
        await interaction.response.send_message(embeds=[embed])

@bot.slash_command(description="Change the GPT-3 weights and biases")
async def setvalues(ctx: discord.ApplicationContext):
    bot.id = ctx.guild.id
    modal = MyModal(title="Modify GPT-3 weights")
    await ctx.send_modal(modal)

bot.run('token')

这为用户创建了一个模式来输入他们想要的值,然后将列表中的这些值发送到名为 guilds 的字典,键为bot.id但是当我运行我创建的命令以测试从我得到的列表中提取值时得到一个 KeyError 异常。 我运行检查的命令是

@bot.slash_command()
async def dictionarytest(ctx):
    await ctx.respond(f'{guilds[bot.id][1]}')

我得到的错误是

忽略命令字典测试中的异常:Traceback(最近一次调用最后一次):文件“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,第 127 行,包装为 ret = _invoke 中的等待 coro(arg) 文件“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,第 911 行等待 self.callback(ctx, **kwargs)文件“/home/liam/PycharmProjects/DiscordBot/maintest.py”,第 76 行,在 dictionarytest await ctx.respond(f'{str(guilds[bot.id][1])}') KeyError: 545151014702022656

上述异常是以下异常的直接原因:

Traceback(最近一次调用最后):文件“/home/liam/.local/lib/python3.10/site-packages/discord/bot.py”,第 1009 行,invoke_application_command await ctx.command.invoke(ctx) 文件“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,第 359 行,调用等待注入(ctx)文件“/home/liam/.local/lib/ python3.10/site-packages/discord/commands/core.py",第 135 行,在从 exc discord.errors.ApplicationCommandInvokeError 包装的 raise ApplicationCommandInvokeError(exc) 中:应用程序命令引发异常:KeyError:545151014702022656

由于我们看不到与您的应用相关的数据,因此很难确定,但我看到了一些可疑的东西,我认为这可能是您的问题。 你得到的错误是不言自明的。 执行此行时:

await ctx.respond(f'{guilds[bot.id][1]}')

错误消息告诉您guilds字典中没有键bot.id ,并且bot.id的值为545151014702022656 所以在这种情况下,他们的关键是integer

您向guild字典添加值的唯一地方是这一行:

guilds[f'{bot.id}'] = [self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value]

在这里,您正在向guilds dict 添加一个值,其键是string 我敢打赌那是你的问题。 integer 545151014702022656和字符串"545151014702022656"不是一回事。 您无法匹配已添加到guilds的键,因为您正在添加字符串键但正在寻找integer键。 所以我敢打赌,修复代码所需要做的就是将上面的行更改为:

guilds[bot.id] = [self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value]

问题未解决?试试以下方法:

从 python 字典中的列表中检索值时遇到问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM