added moderation for prefix & pretend & messages

This commit is contained in:
Paillat
2023-03-06 14:32:44 +01:00
parent 64f3d01860
commit ec844b23b3
4 changed files with 65 additions and 28 deletions

View File

@@ -2,10 +2,8 @@
# wesh wesh ici latouff # wesh wesh ici latouff
import discord # pip install pycord import discord # pip install pycord
from discord import Intents from discord import Intents
import asyncio # pip install asyncio
import cogs # import the cogs import cogs # import the cogs
import datetime # pip install datetime from config import debug, discord_token
from config import debug, conn, c, discord_token
#add the message content intent to the bot, aka discord.Intents.default() and discord.Intents.message_content #add the message content intent to the bot, aka discord.Intents.default() and discord.Intents.message_content
intents = discord.Intents.default() intents = discord.Intents.default()
intents.message_content = True intents.message_content = True

View File

@@ -1,7 +1,7 @@
import discord import discord
from config import debug, conn, c from config import debug, conn, c, moderate
from discord import default_permissions from discord import default_permissions
import openai
models = ["davinci", "chatGPT"] models = ["davinci", "chatGPT"]
class Settings (discord.Cog) : 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 #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") @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}") 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)) c.execute("UPDATE data SET prompt_prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
conn.commit() 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 #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.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) @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}") 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 #check if the guild is in the database
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) try:
if c.fetchone() is None: 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) await ctx.respond("This server is not setup", ephemeral=True)
return return
#check if the bot is enabled if api_key is None or api_key == "":
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) await ctx.respond("This server is not setup", ephemeral=True)
if c.fetchone()[3] == 0:
await ctx.respond("The bot is disabled", ephemeral=True)
return 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: if pretend_to_be is None:
pretend_to_be = "" pretend_to_be = ""
c.execute("UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?", (ctx.guild.id,)) c.execute("UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?", (ctx.guild.id,))
conn.commit() 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) await ctx.guild.me.edit(nick=None)
return return
else: else:
c.execute("UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?", (ctx.guild.id,)) c.execute("UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?", (ctx.guild.id,))
conn.commit() 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) #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) 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)) c.execute("UPDATE data SET pretend_to_be = ? WHERE guild_id = ?", (pretend_to_be, ctx.guild.id))
conn.commit() 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) await ctx.guild.me.edit(nick=pretend_to_be)
return return

View File

@@ -2,6 +2,7 @@ import logging
import sqlite3 import sqlite3
from dotenv import load_dotenv from dotenv import load_dotenv
import os import os
import openai
load_dotenv() load_dotenv()
perspective_api_key = os.getenv("PERSPECTIVE_API_KEY") perspective_api_key = os.getenv("PERSPECTIVE_API_KEY")
discord_token = os.getenv("DISCORD_TOKEN") discord_token = os.getenv("DISCORD_TOKEN")
@@ -15,6 +16,13 @@ c = conn.cursor()
connp = sqlite3.connect('../database/premium.db') connp = sqlite3.connect('../database/premium.db')
cp = connp.cursor() 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)''') 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]} #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 expected_columns = 14

View File

@@ -1,5 +1,5 @@
import asyncio import asyncio
from config import c, max_uses, cp, conn, debug from config import c, max_uses, cp, conn, debug, moderate
import re import re
import openai import openai
import datetime 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 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 if original_message != None and message.guild.id == 1050769643180146749 and message.author.id != 707196665668436019: return
await message.channel.trigger_typing() 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: 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()
@@ -85,17 +89,20 @@ async def chat_process(self, message):
name = "" name = ""
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=content):
if msg.author.id == self.bot.user.id: 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.")
role = "assistant" message.delete()
name = "assistant"
else: else:
role = "user" content = await replace_mentions(content, self.bot)
name = msg.author.name if msg.author.id == self.bot.user.id:
#the name should match '^[a-zA-Z0-9_-]{1,64}$', so we need to remove any special characters role = "assistant"
name = re.sub(r"[^a-zA-Z0-9_-]", "", name) name = "assistant"
else:
msgs.append({"role": role, "content": f"{content}", "name": name}) 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: 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"
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"}) 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"})