我正在使用Python和py-cord开发一个Discord机器人,并且已经实现了OpenAI API,允许用户查询AI并修改不同的权重和偏差。
我试图使每个服务器的权重特定化,这样一个服务器中的人可以有与另一个服务器中的人不同的设置。为了实现这一点,我尝试使用一个字典,其中服务器ID作为键,权重作为值的列表,但总是会遇到KeyError异常。
import osimport discordimport openaiimport reimport asynciofrom discord.ext import commandsfrom gtts import gTTSfrom discord import FFmpegPCMAudiofrom mutagen.mp3 import MP3bot = discord.Bot(intents=discord.Intents.default())guilds = {}@bot.eventasync 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=)@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]}')
我得到的错误是
Ignoring exception in command dictionarytest: Traceback (most recentcall last): File”/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 127, in wrappedret = await coro(arg) File “/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 911, in _invokeawait self.callback(ctx, **kwargs) File “/home/liam/PycharmProjects/DiscordBot/maintest.py”, line 76, indictionarytestawait 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”, line1009, in invoke_application_commandawait ctx.command.invoke(ctx) File “/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 359, in invokeawait injected(ctx) File “/home/liam/.local/lib/python3.10/site-packages/discord/commands/core.py”,line 135, in wrappedraise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Commandraised an exception: KeyError: 545151014702022656
回答:
由于我们无法看到与您的应用程序相关的数据,很难确定问题所在,但我发现了一些可疑之处,我认为这可能是您的问题所在。您得到的错误信息非常明确。当执行以下这行代码时:
await ctx.respond(f'{guilds[bot.id][1]}')
错误消息告诉您guilds
字典中没有键bot.id
,而bot.id
的值为545151014702022656
。因此,在这种情况下,键是一个整数。
您向guild
字典添加值的唯一地方是这一行:
guilds[f'{bot.id}'] = [self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value]
在这里,您向guilds
字典添加了一个值,其键是一个字符串。我猜这就是您的问题所在。整数545151014702022656
和字符串"545151014702022656"
不是同一事物。您无法匹配您添加到guilds
中的键,因为您添加的是字符串键,但查找的是整数键。所以我猜您只需将上述代码行更改为:
guilds[bot.id] = [self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value]