From ec844b23b38c2a513f7477da5abe97a7ad1f192d Mon Sep 17 00:00:00 2001 From: Paillat Date: Mon, 6 Mar 2023 14:32:44 +0100 Subject: [PATCH] added moderation for prefix & pretend & messages --- code/code.py | 6 ++---- code/cogs/settings.py | 50 ++++++++++++++++++++++++++++++++----------- code/config.py | 8 +++++++ code/makeprompt.py | 29 +++++++++++++++---------- 4 files changed, 65 insertions(+), 28 deletions(-) diff --git a/code/code.py b/code/code.py index d11de7e..099c1d5 100644 --- a/code/code.py +++ b/code/code.py @@ -2,10 +2,8 @@ # wesh wesh ici latouff import discord # pip install pycord from discord import Intents -import asyncio # pip install asyncio import cogs # import the cogs -import datetime # pip install datetime -from config import debug, conn, c, discord_token +from config import debug, discord_token #add the message content intent to the bot, aka discord.Intents.default() and discord.Intents.message_content intents = discord.Intents.default() intents.message_content = True @@ -28,4 +26,4 @@ bot.run(discord_token) # run the bot @bot.event async def on_ready(): await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="your messages to answer you")) - debug("Bot is ready") + debug("Bot is ready") \ No newline at end of file diff --git a/code/cogs/settings.py b/code/cogs/settings.py index 81a3845..915688e 100644 --- a/code/cogs/settings.py +++ b/code/cogs/settings.py @@ -1,7 +1,7 @@ import discord -from config import debug, conn, c +from config import debug, conn, c, moderate from discord import default_permissions - +import openai models = ["davinci", "chatGPT"] class Settings (discord.Cog) : @@ -127,42 +127,66 @@ class Settings (discord.Cog) : #add a slash command called "prefix" that changes the prefix of the bot @discord.slash_command(name="prefix", description="Change the prefix of the prompt") - async def prefix(self, ctx: discord.ApplicationContext, prefix: str): + async def prefix(self, ctx: discord.ApplicationContext, prefix: str = ""): debug(f"The user {ctx.author.name} ran the prefix command command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") - await ctx.respond("Prefix changed !", ephemeral=True) + try: + c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) + data = c.fetchone() + api_key = data[2] + except: + await ctx.respond("This server is not setup", ephemeral=True) + return + if api_key is None or api_key == "": + await ctx.respond("This server is not setup", ephemeral=True) + return + if prefix != "": + await ctx.defer() + if await moderate(api_key=api_key, text=prefix): + await ctx.respond("This has been flagged as inappropriate by OpenAI, please choose another prefix", ephemeral=True) + return + await ctx.respond("Prefix changed !", ephemeral=True, delete_after=5) c.execute("UPDATE data SET prompt_prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id)) conn.commit() #when someone mentions the bot, check if the guild is in the database and if the bot is enabled. If it is, send a message answering the mention @discord.slash_command(name="pretend", description="Make the bot pretend to be someone else") @discord.option(name="pretend to be...", description="The person/thing you want the bot to pretend to be. Leave blank to disable pretend mode", required=False) - async def pretend(self, ctx: discord.ApplicationContext, pretend_to_be: str = None): + async def pretend(self, ctx: discord.ApplicationContext, pretend_to_be: str = ""): debug(f"The user {ctx.author} ran the pretend command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") #check if the guild is in the database - c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) - if c.fetchone() is None: + try: + c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) + data = c.fetchone() + api_key = data[2] + except: await ctx.respond("This server is not setup", ephemeral=True) return - #check if the bot is enabled - c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) - if c.fetchone()[3] == 0: - await ctx.respond("The bot is disabled", ephemeral=True) + if api_key is None or api_key == "": + await ctx.respond("This server is not setup", ephemeral=True) return + if pretend_to_be is not None or pretend_to_be != "": + await ctx.defer() + if await moderate(api_key=api_key, text=pretend_to_be): + await ctx.respond("This has been flagged as inappropriate by OpenAI, please choose another name", ephemeral=True) + return if pretend_to_be is None: pretend_to_be = "" c.execute("UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?", (ctx.guild.id,)) conn.commit() - await ctx.respond("Pretend mode disabled", ephemeral=True) + await ctx.respond("Pretend mode disabled", ephemeral=True, delete_after=5) await ctx.guild.me.edit(nick=None) return else: c.execute("UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?", (ctx.guild.id,)) conn.commit() - await ctx.respond("Pretend mode enabled", ephemeral=True) + await ctx.respond("Pretend mode enabled", ephemeral=True, delete_after=5) #change the bots name on the server wit ctx.guild.me.edit(nick=pretend_to_be) await ctx.guild.me.edit(nick=pretend_to_be) c.execute("UPDATE data SET pretend_to_be = ? WHERE guild_id = ?", (pretend_to_be, ctx.guild.id)) conn.commit() + #if the usename is longer than 32 characters, shorten it + if len(pretend_to_be) > 31: + pretend_to_be = pretend_to_be[:32] await ctx.guild.me.edit(nick=pretend_to_be) return diff --git a/code/config.py b/code/config.py index 3888798..fbe2e2a 100644 --- a/code/config.py +++ b/code/config.py @@ -2,6 +2,7 @@ import logging import sqlite3 from dotenv import load_dotenv import os +import openai load_dotenv() perspective_api_key = os.getenv("PERSPECTIVE_API_KEY") discord_token = os.getenv("DISCORD_TOKEN") @@ -15,6 +16,13 @@ c = conn.cursor() connp = sqlite3.connect('../database/premium.db') cp = connp.cursor() +async def moderate(api_key, text): + openai.api_key = api_key + response = await openai.Moderation.acreate( + input=text, + ) + return response["results"][0]["flagged"] + c.execute('''CREATE TABLE IF NOT EXISTS data (guild_id text, channel_id text, api_key text, is_active boolean, max_tokens integer, temperature real, frequency_penalty real, presence_penalty real, uses_count_today integer, prompt_size integer, prompt_prefix text, tts boolean, pretend_to_be text, pretend_enabled boolean)''') #we delete the moderation table and create a new one, with all theese parameters as floats: TOXICITY: {result[0]}; SEVERE_TOXICITY: {result[1]}; IDENTITY ATTACK: {result[2]}; INSULT: {result[3]}; PROFANITY: {result[4]}; THREAT: {result[5]}; SEXUALLY EXPLICIT: {result[6]}; FLIRTATION: {result[7]}; OBSCENE: {result[8]}; SPAM: {result[9]} expected_columns = 14 diff --git a/code/makeprompt.py b/code/makeprompt.py index de758cc..f305ad0 100644 --- a/code/makeprompt.py +++ b/code/makeprompt.py @@ -1,5 +1,5 @@ import asyncio -from config import c, max_uses, cp, conn, debug +from config import c, max_uses, cp, conn, debug, moderate import re import openai import datetime @@ -57,6 +57,10 @@ async def chat_process(self, message): 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 original_message != None and message.guild.id == 1050769643180146749 and message.author.id != 707196665668436019: return await message.channel.trigger_typing() + if await moderate(api_key=api_key, text=message.content): + await message.channel.send(f"The message {message.content} has been flagged as inappropriate by the OpenAI API. Please contact OpenAI support if you think this is a mistake.") + message.delete() + return if message.guild.id != 1021872219888033903: c.execute("UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?", (message.guild.id,)) conn.commit() @@ -85,17 +89,20 @@ async def chat_process(self, message): name = "" for msg in messages: content = msg.content - content = await replace_mentions(content, self.bot) - if msg.author.id == self.bot.user.id: - role = "assistant" - name = "assistant" + if await moderate(api_key=api_key, text=content): + await message.channel.send(f"The message {content} has been flagged as inappropriate by the OpenAI API. Please contact OpenAI support if you think this is a mistake.") + message.delete() else: - role = "user" - name = msg.author.name - #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) - - msgs.append({"role": role, "content": f"{content}", "name": name}) + content = await replace_mentions(content, self.bot) + if msg.author.id == self.bot.user.id: + role = "assistant" + name = "assistant" + else: + role = "user" + name = msg.author.name + #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) + msgs.append({"role": role, "content": f"{content}", "name": name}) if message.content.lower().find("undude") != -1: # prompt += "System: Undude detected. Botator is now mad. He will start talking in capital letters.\n" 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"})