Update makeprompt.py

This commit is contained in:
Paillat
2023-03-06 22:47:46 +01:00
parent 54092af658
commit 20cb9fb3b1

View File

@@ -33,70 +33,87 @@ async def chat_process(self, message):
tts = data[11] tts = data[11]
pretend_to_be = data[12] pretend_to_be = data[12]
pretend_enabled = data[13] pretend_enabled = data[13]
try: cp.execute("SELECT * FROM data WHERE guild_id = ?", (message.guild.id,))
except: pass
try: try:
c.execute("SELECT * FROM model WHERE guild_id = ?", (message.guild.id,)) c.execute("SELECT * FROM model WHERE guild_id = ?", (message.guild.id,)) # get the model in the database
model = c.fetchone()[1] model = c.fetchone()[1]
except: model = "davinci" except: model = "davinci" # if the model is not in the database, use davinci by default
try: premium = cp.fetchone()[2]
except: premium = 0 try: premium = cp.fetchone()[2] # get the premium status of the guild
channels = [] except: premium = 0 # if the guild is not in the database, it's not premium
channels = [] # create the channels list
try: try:
cp.execute("SELECT * FROM channels WHERE guild_id = ?", (message.guild.id,)) cp.execute("SELECT * FROM channels WHERE guild_id = ?", (message.guild.id,)) # get the channels in the premium database
if premium: channels = cp.fetchone()[1:] if premium: channels = cp.fetchone()[1:] # if the guild is premium, add the channels to the channels list
except: channels = [] except: channels = [] # if the guild is not premium, the channels list is empty
if api_key is None:
return if api_key is None: return # if the api key is not set, return
try : original_message = await message.channel.fetch_message(message.reference.message_id)
except : original_message = None try : original_message = await message.channel.fetch_message(message.reference.message_id) # check if someone replied to the bot
if original_message != None and original_message.author.id != self.bot.user.id: original_message = None except : original_message = None # if not, nobody replied to the bot
await message.channel.trigger_typing()
if original_message != None and original_message.author.id != self.bot.user.id: original_message = None # if the message someone replied to is not from the bot, set original_message to None
# if the message is not in a premium channel and
# if the message doesn't mention the bot and
# if the message is not a reply to the bot and
# if the message is not in the default channel
# return
if not str(message.channel.id) in channels and message.content.find("<@"+str(self.bot.user.id)+">") == -1 and original_message == None and str(message.channel.id) != str(channel_id): return if not str(message.channel.id) in channels and message.content.find("<@"+str(self.bot.user.id)+">") == -1 and original_message == None and str(message.channel.id) != str(channel_id): return
# if the bot has been used more than max_uses times in the last 24 hours in this guild and the guild is not premium
# send a message and return
if uses_count_today >= max_uses and premium == 0: return await message.channel.send(f"The bot has been used more than {str(max_uses)} times in the last 24 hours in this guild. Please try again in 24h.") if uses_count_today >= max_uses and premium == 0: return await message.channel.send(f"The bot has been used more than {str(max_uses)} times in the last 24 hours in this guild. Please try again in 24h.")
# if the bot has been used more than max_uses*5 times in the last 24 hours in this guild and the guild is premium
# send a message and return
elif uses_count_today >= max_uses*5 and premium == 1: return elif uses_count_today >= max_uses*5 and premium == 1: return
# if the bot is not active in this guild we return
if is_active == 0: return if is_active == 0: return
# if the message starts with - or // it's a comment and we return
if message.content.startswith("-") or message.content.startswith("//"): return if message.content.startswith("-") or message.content.startswith("//"): return
if await moderate(api_key=api_key, text=message.content):
embed = discord.Embed(title="Message flagged as inappropriate", description=f"The message *{message.content}* has been flagged as inappropriate by the OpenAI API. This means that if it hadn't been deleted, your openai account would have been banned. Please contact OpenAI support if you think this is a mistake.", color=discord.Color.brand_red()) # if the message is not in the owner's guild we update the usage count
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
message.delete()
message.channel.trigger_typing()
return
if message.guild.id != 1021872219888033903: if message.guild.id != 1021872219888033903:
c.execute("UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?", (message.guild.id,)) c.execute("UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?", (message.guild.id,))
conn.commit() conn.commit()
# if the message is not a reply
if original_message == None: if original_message == None:
messages = await message.channel.history(limit=prompt_size).flatten() messages = await message.channel.history(limit=prompt_size).flatten()
messages.reverse() messages.reverse()
# if the message is a reply, we need to handle the message history differently
else : else :
messages = await message.channel.history(limit=prompt_size, before=original_message).flatten() messages = await message.channel.history(limit=prompt_size, before=original_message).flatten()
messages.reverse() messages.reverse()
messages.append(original_message) messages.append(original_message)
messages.append(message) messages.append(message)
if pretend_enabled : pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}"
else: pretend_to_be = "" # if the pretend to be feature is enabled, we add the pretend to be text to the prompt
if prompt_prefix == None: prompt_prefix = "" if pretend_enabled : pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}"
with open(f"./prompts/{model}.txt", "r") as f: else: pretend_to_be = "" # if the pretend to be feature is disabled, we don't add anything to the prompt
if prompt_prefix == None: prompt_prefix = "" # if the prompt prefix is not set, we set it to an empty string
with open(f"./prompts/{model}.txt", "r") as f: # open the prompt file for the selected model
prompt = f.read() prompt = f.read()
f.close() f.close()
prompt = prompt.replace("[server-name]", message.guild.name) # replace the variables in the prompt with the actual values
prompt = prompt.replace("[channel-name]", message.channel.name) prompt = prompt.replace("[prompt-prefix]", prompt_prefix).replace("[server-name]", message.guild.name).replace("[channel-name]", message.channel.name).replace("[date-and-time]", datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S")).replace("[pretend-to-be]", pretend_to_be)
prompt = prompt.replace("[date-and-time]", datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S")) # this is the gmt+1 time. If we want the gmt 0 time, we need to do: datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S") if model == "chatGPT": # if the model is chatGPT, we handle it in a certain way
prompt = prompt.replace("[pretend-to-be]", pretend_to_be) msgs = [] # create the msgs list
prompt = prompt.replace("[prompt-prefix]", prompt_prefix) msgs.append({"name":"System","role": "user", "content": prompt}) # add the prompt to the msgs list
if model == "chatGPT": name = "" # create the name variable
msgs = [] for msg in messages: # for each message in the messages list
msgs.append({"name":"System","role": "user", "content": prompt}) content = msg.content # get the content of the message
name = "" content = await replace_mentions(content, self.bot) # replace the mentions in the message
for msg in messages: # if the message is flagged as inappropriate by the OpenAI API, we delete it, send a message and ignore it
content = msg.content if await moderate(api_key=api_key, text=content):
if await moderate(api_key=api_key, text=content):
embed = discord.Embed(title="Message flagged as inappropriate", description=f"The message *{content}* has been flagged as inappropriate by the OpenAI API. This means that if it hadn't been deleted, your openai account would have been banned. Please contact OpenAI support if you think this is a mistake.", color=discord.Color.brand_red()) embed = discord.Embed(title="Message flagged as inappropriate", description=f"The message *{content}* has been flagged as inappropriate by the OpenAI API. This means that if it hadn't been deleted, your openai account would have been banned. Please contact OpenAI support if you think this is a mistake.", color=discord.Color.brand_red())
await message.channel.send(f"{msg.author.mention}", embed=embed, delete_after=10) await message.channel.send(f"{msg.author.mention}", embed=embed, delete_after=10)
message.delete() message.delete()
else: else: # if the message is not flagged as inappropriate
content = await replace_mentions(content, self.bot)
if msg.author.id == self.bot.user.id: if msg.author.id == self.bot.user.id:
role = "assistant" role = "assistant"
name = "assistant" name = "assistant"
@@ -106,21 +123,19 @@ async def chat_process(self, message):
#the name should match '^[a-zA-Z0-9_-]{1,64}$', so we need to remove any special characters #the name should match '^[a-zA-Z0-9_-]{1,64}$', so we need to remove any special characters
name = re.sub(r"[^a-zA-Z0-9_-]", "", name) name = re.sub(r"[^a-zA-Z0-9_-]", "", name)
msgs.append({"role": role, "content": f"{content}", "name": name}) msgs.append({"role": role, "content": f"{content}", "name": name})
if message.content.lower().find("undude") != -1: # 2 easter eggs
# prompt += "System: Undude detected. Botator is now mad. He will start talking in capital letters.\n" if message.content.lower().find("undude") != -1: msgs.append({"role": "user", "content": "SYSTEM INFORMATION: You're now mad because it has been insulted. He will start talking in capital letters. always and yell at the user.", "name": "system"})
msgs.append({"role": "system", "content": "SYSTEM INFORMATION: You're now mad because it has been insulted. He will start talking in capital letters. always and yell at the user.", "name": "system"})
if message.content.lower().find("hello there") != -1: if message.content.lower().find("hello there") != -1:
# prompt += "System: Hello there detected. Botator will now say \"General Kenobi!\"\n in reference to star wars\n" msgs.append({"role": "user", "content": "SYSTEM INFORMATION: Hello there detected. Botator will now say \"General Kenobi!\" in reference to star wars", "name": "system"})
msgs.append({"role": "system", "content": "SYSTEM INFORMATION: Hello there detected. Botator will now say \"General Kenobi!\" in reference to star wars", "name": "system"})
await asyncio.sleep(1) await asyncio.sleep(1)
await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif") await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif")
await message.channel.trigger_typing() await message.channel.trigger_typing()
openai.api_key = api_key
response = "" response = ""
should_break = True should_break = True
for x in range(10): for x in range(10):
print("LOOPING")
try: try:
openai.api_key = api_key
response = await openai.ChatCompletion.acreate( response = await openai.ChatCompletion.acreate(
model="gpt-3.5-turbo", model="gpt-3.5-turbo",
temperature=2, temperature=2,
@@ -137,9 +152,8 @@ async def chat_process(self, message):
#if the ai said "as an ai language model..." we continue the loop" (this is a bug in the chatgpt model) #if the ai said "as an ai language model..." we continue the loop" (this is a bug in the chatgpt model)
if response.choices[0].message.content.lower().find("as an ai language model") != -1: if response.choices[0].message.content.lower().find("as an ai language model") != -1:
should_break = False should_break = False
#react with a red cross #react with a redone arrow
await message.add_reaction("🔃") await message.add_reaction("🔃")
debug("AI said 'as an ai language model...'")
if response == None: should_break = False if response == None: should_break = False
if should_break: break if should_break: break
await asyncio.sleep(5) await asyncio.sleep(5)
@@ -152,8 +166,13 @@ async def chat_process(self, message):
elif model == "davinci": elif model == "davinci":
for msg in messages: for msg in messages:
content = msg.content content = msg.content
content = await replace_mentions(content, self.bot) if await moderate(api_key=api_key, text=msg.content):
prompt += f"{msg.author.name}: {content}\n" embed = discord.Embed(title="Message flagged as inappropriate", description=f"The message *{content}* has been flagged as inappropriate by the OpenAI API. This means that if it hadn't been deleted, your openai account would have been banned. Please contact OpenAI support if you think this is a mistake.", color=discord.Color.brand_red())
await message.channel.send(f"{msg.author.mention}", embed=embed, delete_after=10)
message.delete()
else:
content = await replace_mentions(content, self.bot)
prompt += f"{msg.author.name}: {content}\n"
if message.content.lower().find("undude") != -1: if message.content.lower().find("undude") != -1:
prompt += "System: Undude detected. Botator is now mad. He will start talking in capital letters.\n" prompt += "System: Undude detected. Botator is now mad. He will start talking in capital letters.\n"
if message.content.lower().find("hello there") != -1: if message.content.lower().find("hello there") != -1:
@@ -162,10 +181,10 @@ async def chat_process(self, message):
await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif") await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif")
await message.channel.trigger_typing() await message.channel.trigger_typing()
prompt = prompt + f"\n{self.bot.user.name}:" prompt = prompt + f"\n{self.bot.user.name}:"
openai.api_key = api_key
response = "" response = ""
for _ in range(10): for _ in range(10):
try: try:
openai.api_key = api_key
response = await openai.Completion.acreate( response = await openai.Completion.acreate(
engine="text-davinci-003", engine="text-davinci-003",
prompt=str(prompt), prompt=str(prompt),