从Python字典中的列表中检索值时出错

vuktfyat  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(238)

我正在用Python py-cord 开发一个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')

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

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

我得到的错误是
忽略命令dictionarytest中的异常:追溯(最近一次调用):File“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 127,in wrapped ret = await科罗(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(guildings [bot.id][1])}')KeyError:545151014702022656
上述异常是以下异常的直接原因:
追溯(最近一次调用):文件“/home/liam/.local/lib/python3.10/site-packages/discord/bot.py”,line 1009,in invoke_application_command await ctx.command.invoke(ctx)文件“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 359,in invoke await injected(ctx)文件“/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 135,在 Package 中,从exc引发ApplicationCommandInvokeError(exc)discord.errors.ApplicationCommandInvokeError:应用程序命令引发异常:粤ICP备050151014702号-1

aiqt4smr

aiqt4smr1#

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

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

错误消息告诉你在guilds字典中没有任何键bot.id,而bot.id的值是545151014702022656。所以在这个例子中,键是一个***整数***。
唯一可以向guild dict添加值的地方是这一行:

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

在这里,你添加一个值到guilds dict,其键是***string***。我打赌这是你的问题。整数545151014702022656和字符串"545151014702022656"不是一回事。你无法匹配你添加到guilds的键,因为你添加了***string***键,但是寻找***integer***键。所以我打赌你要做的就是修改上面的代码:

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

相关问题