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. 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.
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. 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
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
CodePudding user response:
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
. So in this case, they key is an integer.
The only place you add values to the guild
dict is this line:
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. I bet that's your problem. The integer 545151014702022656
and the string "545151014702022656"
aren't the same thing. You fail to match the keys you have added to guilds
because you're adding string keys but looking for integer keys. 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]