简体   繁体   English

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

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

So I am developing a discord bot in python with py-cord and I have implemented the openai api to allow users to query the AI and modify the different weights and biases.因此,我正在使用 py-cord 在 python 中开发 discord 机器人,并且我已经实现了 openai api 以允许用户查询 AI 并修改不同的权重和偏差。 What I am trying to do is make the weights specific to each guild, so people in one server can have different settings to someone in a different server.我想要做的是使权重特定于每个公会,因此一个服务器中的人可以对不同服务器中的人有不同的设置。 To achieve this I am trying to use a dictionary where the guild id is the key and the weights are in a list as the values but I keep getting KeyError exceptions.为了实现这一点,我尝试使用一个字典,其中公会 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')

This creates a modal for users to input the values they want and then sends those values in a list to the dictionary called guilds with the key being bot.id however when i run a command I created to test pulling a value from the list I get get a KeyError exception.这为用户创建了一个模式来输入他们想要的值,然后将列表中的这些值发送到名为 guilds 的字典,键为bot.id但是当我运行我创建的命令以测试从我得到的列表中提取值时得到一个 KeyError 异常。 The command I run to check is我运行检查的命令是

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

The error I get is我得到的错误是

Ignoring exception in command dictionarytest: Traceback (most recent call last): File "/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py", line 127, in wrapped ret = await coro(arg) File "/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py", line 911, in _invoke await self.callback(ctx, **kwargs) File "/home/liam/PycharmProjects/DiscordBot/maintest.py", line 76, in dictionarytest await ctx.respond(f'{str(guilds[bot.id][1])}') KeyError: 545151014702022656忽略命令字典测试中的异常: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

The above exception was the direct cause of the following exception:上述异常是以下异常的直接原因:

Traceback (most recent call last): File "/home/liam/.local/lib/python3.10/site-packages/discord/bot.py", line 1009, in invoke_application_command await ctx.command.invoke(ctx) File "/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py", line 359, in invoke await injected(ctx) File "/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: 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

Since we can't see the data associated with your app, it's hard to know for sure, but I see something suspicious that I think may be your problem.由于我们看不到与您的应用相关的数据,因此很难确定,但我看到了一些可疑的东西,我认为这可能是您的问题。 The error you are getting is pretty self explanatory.你得到的错误是不言自明的。 When executing this line:执行此行时:

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

the error message is telling you that there is no key bot.id in the guilds dict, and bot.id has the value 545151014702022656 .错误消息告诉您guilds字典中没有键bot.id ,并且bot.id的值为545151014702022656 So in this case, they key is an integer .所以在这种情况下,他们的关键是integer

The only place you add values to the guild dict is this line:您向guild字典添加值的唯一地方是这一行:

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

Here, you are adding a value to the guilds dict with a key that is a string .在这里,您正在向guilds dict 添加一个值,其键是string I bet that's your problem.我敢打赌那是你的问题。 The integer 545151014702022656 and the string "545151014702022656" aren't the same thing. integer 545151014702022656和字符串"545151014702022656"不是一回事。 You fail to match the keys you have added to guilds because you're adding string keys but looking for integer keys.您无法匹配已添加到guilds的键,因为您正在添加字符串键但正在寻找integer键。 So I bet all you have to do to fix your code is change the above line to:所以我敢打赌,修复代码所需要做的就是将上面的行更改为:

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

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

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