refactor(help.py, settings.py): remove debug import and debug statements

feat(settings.py): add ctx_to_guid function to convert context to guild id for database queries
feat(settings.py): add support for changing the model used by the bot
fix(settings.py): fix images command not updating the database correctly

feat(cogs/setup.py): add dms_only check to setup_dms command
refactor(cogs/setup.py): move ctx_to_guid function to config.py
refactor(cogs/setup.py): move mg_to_guid function to config.py

feat(makeprompt.py): add support for DMs conversations
fix(makeprompt.py): fix images setting retrieval from database
fix(makeprompt.py): fix guild_id to guid conversion in database queries
refactor(makeprompt.py): extract historicator function to get the channel or user of a message
refactor(makeprompt.py): remove debug statements and unused variables
This commit is contained in:
Paillat
2023-05-05 12:38:02 +02:00
parent f8907667e0
commit 94974b2bd3
5 changed files with 185 additions and 139 deletions

View File

@@ -1,6 +1,4 @@
import discord import discord
from config import debug
class Help(discord.Cog): class Help(discord.Cog):
def __init__(self, bot: discord.Bot) -> None: def __init__(self, bot: discord.Bot) -> None:
@@ -9,9 +7,6 @@ class Help(discord.Cog):
@discord.slash_command(name="help", description="Show all the commands") @discord.slash_command(name="help", description="Show all the commands")
async def help(self, ctx: discord.ApplicationContext): async def help(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the help command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
embed = discord.Embed( embed = discord.Embed(
title="Help", description="Here is the help page", color=0x00FF00 title="Help", description="Here is the help page", color=0x00FF00
) )
@@ -71,9 +66,6 @@ class Help(discord.Cog):
name="advanced_help", description="Show the advanced settings meanings" name="advanced_help", description="Show the advanced settings meanings"
) )
async def advanced_help(self, ctx: discord.ApplicationContext): async def advanced_help(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the advanced_help command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
embed = discord.Embed( embed = discord.Embed(
title="Advanced Help", title="Advanced Help",
description="Here is the advanced help page", description="Here is the advanced help page",

View File

@@ -1,5 +1,5 @@
import discord import discord
from config import debug, con_data, curs_data, moderate from config import debug, con_data, curs_data, moderate, ctx_to_guid
from discord import default_permissions from discord import default_permissions
models = ["davinci", "gpt-3.5-turbo", "gpt-4"] models = ["davinci", "gpt-3.5-turbo", "gpt-4"]
@@ -31,10 +31,7 @@ class Settings(discord.Cog):
presence_penalty: float = None, presence_penalty: float = None,
prompt_size: int = None, prompt_size: int = None,
): ):
debug( curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
f"The user {ctx.author} ran the advanced command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
@@ -69,26 +66,26 @@ class Settings(discord.Cog):
if max_tokens is None: if max_tokens is None:
if ( if (
curs_data.execute( curs_data.execute(
"SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT max_tokens FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
is not None is not None
and max_tokens is None and max_tokens is None
): ):
max_tokens = curs_data.execute( max_tokens = curs_data.execute(
"SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT max_tokens FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
else: else:
max_tokens = 64 max_tokens = 64
if temperature is None: if temperature is None:
if ( if (
curs_data.execute( curs_data.execute(
"SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT temperature FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
is not None is not None
and temperature is None and temperature is None
): ):
temperature = curs_data.execute( temperature = curs_data.execute(
"SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT temperature FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
else: else:
temperature = 0.9 temperature = 0.9
@@ -96,14 +93,14 @@ class Settings(discord.Cog):
if ( if (
curs_data.execute( curs_data.execute(
"SELECT frequency_penalty FROM data WHERE guild_id = ?", "SELECT frequency_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
).fetchone()[0] ).fetchone()[0]
is not None is not None
and frequency_penalty is None and frequency_penalty is None
): ):
frequency_penalty = curs_data.execute( frequency_penalty = curs_data.execute(
"SELECT frequency_penalty FROM data WHERE guild_id = ?", "SELECT frequency_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
).fetchone()[0] ).fetchone()[0]
else: else:
frequency_penalty = 0.0 frequency_penalty = 0.0
@@ -111,27 +108,27 @@ class Settings(discord.Cog):
if ( if (
curs_data.execute( curs_data.execute(
"SELECT presence_penalty FROM data WHERE guild_id = ?", "SELECT presence_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
).fetchone()[0] ).fetchone()[0]
is not None is not None
and presence_penalty is None and presence_penalty is None
): ):
presence_penalty = curs_data.execute( presence_penalty = curs_data.execute(
"SELECT presence_penalty FROM data WHERE guild_id = ?", "SELECT presence_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
).fetchone()[0] ).fetchone()[0]
else: else:
presence_penalty = 0.0 presence_penalty = 0.0
if prompt_size is None: if prompt_size is None:
if ( if (
curs_data.execute( curs_data.execute(
"SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT prompt_size FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
is not None is not None
and prompt_size is None and prompt_size is None
): ):
prompt_size = curs_data.execute( prompt_size = curs_data.execute(
"SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,) "SELECT prompt_size FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),)
).fetchone()[0] ).fetchone()[0]
else: else:
prompt_size = 1 prompt_size = 1
@@ -144,7 +141,7 @@ class Settings(discord.Cog):
frequency_penalty, frequency_penalty,
presence_penalty, presence_penalty,
prompt_size, prompt_size,
ctx.guild.id, ctx_to_guid(ctx),
), ),
) )
con_data.commit() con_data.commit()
@@ -154,11 +151,8 @@ class Settings(discord.Cog):
@discord.slash_command(name="default", description="Default settings") @discord.slash_command(name="default", description="Default settings")
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def default(self, ctx: discord.ApplicationContext): async def default(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the default 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
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond( await ctx.respond(
"This server is not setup, please run /setup", ephemeral=True "This server is not setup, please run /setup", ephemeral=True
@@ -167,7 +161,7 @@ class Settings(discord.Cog):
# set the advanced settings (max_tokens, temperature, frequency_penalty, presence_penalty, prompt_size) and also prompt_prefix to their default values # set the advanced settings (max_tokens, temperature, frequency_penalty, presence_penalty, prompt_size) and also prompt_prefix to their default values
curs_data.execute( curs_data.execute(
"UPDATE data SET max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?", "UPDATE data SET max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?",
(64, 0.9, 0.0, 0.0, 5, ctx.guild.id), (64, 0.9, 0.0, 0.0, 5, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
await ctx.respond( await ctx.respond(
@@ -183,13 +177,10 @@ class Settings(discord.Cog):
) )
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def info(self, ctx: discord.ApplicationContext): async def info(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the info command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
# this command sends all the data about the guild, including the api key, the channel id, the advanced settings and the uses_count_today # this command sends all the data about the guild, including the api key, the channel id, the advanced settings and the uses_count_today
# check if the guild is in the database # check if the guild is in the database
try: try:
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
data = curs_data.fetchone() data = curs_data.fetchone()
except: except:
data = None data = None
@@ -197,7 +188,7 @@ class Settings(discord.Cog):
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
try: try:
curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx_to_guid(ctx),))
model = curs_data.fetchone()[1] model = curs_data.fetchone()[1]
except: except:
model = None model = None
@@ -224,11 +215,8 @@ class Settings(discord.Cog):
@discord.slash_command(name="prefix", description="Change the prefix of the prompt") @discord.slash_command(name="prefix", description="Change the prefix of the prompt")
@default_permissions(administrator=True) @default_permissions(administrator=True)
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}"
)
try: try:
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
data = curs_data.fetchone() data = curs_data.fetchone()
api_key = data[2] api_key = data[2]
except: except:
@@ -248,7 +236,7 @@ class Settings(discord.Cog):
await ctx.respond("Prefix changed !", ephemeral=True, delete_after=5) await ctx.respond("Prefix changed !", ephemeral=True, delete_after=5)
curs_data.execute( curs_data.execute(
"UPDATE data SET prompt_prefix = ? WHERE guild_id = ?", "UPDATE data SET prompt_prefix = ? WHERE guild_id = ?",
(prefix, ctx.guild.id), (prefix, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
@@ -263,12 +251,9 @@ class Settings(discord.Cog):
) )
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def pretend(self, ctx: discord.ApplicationContext, pretend_to_be: str = ""): 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 # check if the guild is in the database
try: try:
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
data = curs_data.fetchone() data = curs_data.fetchone()
api_key = data[2] api_key = data[2]
except: except:
@@ -289,7 +274,7 @@ class Settings(discord.Cog):
pretend_to_be = "" pretend_to_be = ""
curs_data.execute( curs_data.execute(
"UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?", "UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
) )
con_data.commit() con_data.commit()
await ctx.respond("Pretend mode disabled", ephemeral=True, delete_after=5) await ctx.respond("Pretend mode disabled", ephemeral=True, delete_after=5)
@@ -298,7 +283,7 @@ class Settings(discord.Cog):
else: else:
curs_data.execute( curs_data.execute(
"UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?", "UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?",
(ctx.guild.id,), (ctx_to_guid(ctx),),
) )
con_data.commit() con_data.commit()
await ctx.respond("Pretend mode enabled", ephemeral=True, delete_after=5) await ctx.respond("Pretend mode enabled", ephemeral=True, delete_after=5)
@@ -306,7 +291,7 @@ class Settings(discord.Cog):
await ctx.guild.me.edit(nick=pretend_to_be) await ctx.guild.me.edit(nick=pretend_to_be)
curs_data.execute( curs_data.execute(
"UPDATE data SET pretend_to_be = ? WHERE guild_id = ?", "UPDATE data SET pretend_to_be = ? WHERE guild_id = ?",
(pretend_to_be, ctx.guild.id), (pretend_to_be, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
# if the usename is longer than 32 characters, shorten it # if the usename is longer than 32 characters, shorten it
@@ -319,7 +304,7 @@ class Settings(discord.Cog):
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def enable_tts(self, ctx: discord.ApplicationContext): async def enable_tts(self, ctx: discord.ApplicationContext):
# get the guild id # get the guild id
guild_id = ctx.guild.id guild_id = ctx_to_guid(ctx)
# connect to the database # connect to the database
# update the tts value in the database # update the tts value in the database
curs_data.execute("UPDATE data SET tts = 1 WHERE guild_id = ?", (guild_id,)) curs_data.execute("UPDATE data SET tts = 1 WHERE guild_id = ?", (guild_id,))
@@ -331,7 +316,7 @@ class Settings(discord.Cog):
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def disable_tts(self, ctx: discord.ApplicationContext): async def disable_tts(self, ctx: discord.ApplicationContext):
# get the guild id # get the guild id
guild_id = ctx.guild.id guild_id = ctx_to_guid(ctx)
# connect to the database # connect to the database
# update the tts value in the database # update the tts value in the database
curs_data.execute("UPDATE data SET tts = 0 WHERE guild_id = ?", (guild_id,)) curs_data.execute("UPDATE data SET tts = 0 WHERE guild_id = ?", (guild_id,))
@@ -353,16 +338,16 @@ class Settings(discord.Cog):
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def model(self, ctx: discord.ApplicationContext, model: str = "davinci"): async def model(self, ctx: discord.ApplicationContext, model: str = "davinci"):
try: try:
curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx_to_guid(ctx),))
data = curs_data.fetchone()[1] data = curs_data.fetchone()[1]
except: except:
data = None data = None
if data is None: if data is None:
curs_data.execute("INSERT INTO model VALUES (?, ?)", (ctx.guild.id, model)) curs_data.execute("INSERT INTO model VALUES (?, ?)", (ctx_to_guid(ctx), model))
else: else:
curs_data.execute( curs_data.execute(
"UPDATE model SET model_name = ? WHERE guild_id = ?", "UPDATE model SET model_name = ? WHERE guild_id = ?",
(model, ctx.guild.id), (model, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
await ctx.respond("Model changed !", ephemeral=True) await ctx.respond("Model changed !", ephemeral=True)
@@ -382,7 +367,7 @@ class Settings(discord.Cog):
async def images(self, ctx: discord.ApplicationContext, enable_disable: str): async def images(self, ctx: discord.ApplicationContext, enable_disable: str):
try: try:
curs_data.execute( curs_data.execute(
"SELECT * FROM images WHERE guild_id = ?", (ctx.guild.id,) "SELECT * FROM images WHERE guild_id = ?", (ctx_to_guid(ctx),)
) )
data = curs_data.fetchone() data = curs_data.fetchone()
except: except:
@@ -393,12 +378,12 @@ class Settings(discord.Cog):
enable_disable = 0 enable_disable = 0
if data is None: if data is None:
curs_data.execute( curs_data.execute(
"INSERT INTO images VALUES (?, ?, ?)", (ctx.guild.id, 0, enable_disable) "INSERT INTO images VALUES (?, ?, ?)", (ctx_to_guid(ctx), 0, enable_disable)
) )
else: else:
curs_data.execute( curs_data.execute(
"UPDATE images SET is_enabled = ? WHERE guild_id = ?", "UPDATE images SET is_enabled = ? WHERE guild_id = ?",
(enable_disable, ctx.guild.id), (enable_disable, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
await ctx.respond( await ctx.respond(

View File

@@ -1,7 +1,17 @@
import discord import discord
from discord import default_permissions from discord import default_permissions, guild_only
from config import debug, con_data, curs_data, con_premium, curs_premium from discord.ext import commands
from config import debug, con_data, curs_data, con_premium, curs_premium, ctx_to_guid
class NoPrivateMessages(commands.CheckFailure):
pass
def dms_only():
async def predicate(ctx):
if ctx.guild is not None:
raise NoPrivateMessages('Hey no private messages!')
return True
return commands.check(predicate)
class Setup(discord.Cog): class Setup(discord.Cog):
def __init__(self, bot: discord.Bot): def __init__(self, bot: discord.Bot):
@@ -12,15 +22,13 @@ class Setup(discord.Cog):
@discord.option(name="channel_id", description="The channel id", required=True) @discord.option(name="channel_id", description="The channel id", required=True)
@discord.option(name="api_key", description="The api key", required=True) @discord.option(name="api_key", description="The api key", required=True)
@default_permissions(administrator=True) @default_permissions(administrator=True)
@guild_only()
async def setup( async def setup(
self, self,
ctx: discord.ApplicationContext, ctx: discord.ApplicationContext,
channel: discord.TextChannel, channel: discord.TextChannel,
api_key: str, api_key: str,
): ):
debug(
f"The user {ctx.author} ran the setup command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
if channel is None: if channel is None:
await ctx.respond("Invalid channel id", ephemeral=True) await ctx.respond("Invalid channel id", ephemeral=True)
return return
@@ -66,24 +74,75 @@ class Setup(discord.Cog):
await ctx.respond( await ctx.respond(
"The channel id and the api key have been added", ephemeral=True "The channel id and the api key have been added", ephemeral=True
) )
@discord.slash_command(name="setup_dms", description="Setup the bot in dms")
@discord.option(name="api_key", description="The api key", required=True)
@default_permissions(administrator=True)
@dms_only()
async def setup_dms(
self,
ctx: discord.ApplicationContext,
api_key: str,
):
channel = ctx.channel
if channel is None:
await ctx.respond("Invalid channel id", ephemeral=True)
return
try:
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.user.id,))
data = curs_data.fetchone()
if data[3] == None:
data = None
except:
data = None
if data != None:
curs_data.execute(
"UPDATE data SET channel_id = ?, api_key = ? WHERE guild_id = ?",
(channel.id, api_key, ctx.user.id),
)
con_data.commit()
await ctx.respond(
"The channel id and the api key have been updated", ephemeral=True
)
else:
curs_data.execute(
"INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
ctx.user.id,
channel.id,
api_key,
False,
64,
0.9,
0.0,
0.0,
0,
5,
"",
False,
"",
False,
),
)
con_data.commit()
await ctx.respond(
"The api key has been added", ephemeral=True
)
@discord.slash_command( @discord.slash_command(
name="delete", description="Delete the information about this server" name="delete", description="Delete the information about this server"
) )
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def delete(self, ctx: discord.ApplicationContext): async def delete(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the delete 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
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
# delete the guild from the database, except the guild id and the uses_count_today # delete the guild from the database, except the guild id and the uses_count_today
curs_data.execute( curs_data.execute(
"UPDATE data SET api_key = ?, channel_id = ?, is_active = ?, max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?", "UPDATE data SET api_key = ?, channel_id = ?, is_active = ?, max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?",
(None, None, False, 50, 0.9, 0.0, 0.0, 0, ctx.guild.id), (None, None, False, 50, 0.9, 0.0, 0.0, 0, ctx_to_guid(ctx)),
) )
con_data.commit() con_data.commit()
await ctx.respond("Deleted", ephemeral=True) await ctx.respond("Deleted", ephemeral=True)
@@ -92,23 +151,13 @@ class Setup(discord.Cog):
@discord.slash_command(name="enable", description="Enable the bot") @discord.slash_command(name="enable", description="Enable the bot")
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def enable(self, ctx: discord.ApplicationContext): async def enable(self, ctx: discord.ApplicationContext):
# if the guild is eqal to 1014156298226515970, the guild is banned curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
if ctx.guild.id == 1014156298226515970:
await ctx.respond(
"This server is banned for bad and nsfw use.", ephemeral=True
)
return
# check if the guild is in the database
debug(
f"The user {ctx.author} ran the enable command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
# enable the guild # enable the guild
curs_data.execute( curs_data.execute(
"UPDATE data SET is_active = ? WHERE guild_id = ?", (True, ctx.guild.id) "UPDATE data SET is_active = ? WHERE guild_id = ?", (True, ctx_to_guid(ctx))
) )
con_data.commit() con_data.commit()
await ctx.respond("Enabled", ephemeral=True) await ctx.respond("Enabled", ephemeral=True)
@@ -117,17 +166,14 @@ class Setup(discord.Cog):
@discord.slash_command(name="disable", description="Disable the bot") @discord.slash_command(name="disable", description="Disable the bot")
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def disable(self, ctx: discord.ApplicationContext): async def disable(self, ctx: discord.ApplicationContext):
debug(
f"The user {ctx.author} ran the disable 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
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx_to_guid(ctx),))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
# disable the guild # disable the guild
curs_data.execute( curs_data.execute(
"UPDATE data SET is_active = ? WHERE guild_id = ?", (False, ctx.guild.id) "UPDATE data SET is_active = ? WHERE guild_id = ?", (False, ctx_to_guid(ctx))
) )
con_data.commit() con_data.commit()
await ctx.respond("Disabled", ephemeral=True) await ctx.respond("Disabled", ephemeral=True)
@@ -144,12 +190,10 @@ class Setup(discord.Cog):
required=False, required=False,
) )
@default_permissions(administrator=True) @default_permissions(administrator=True)
@guild_only()
async def add_channel( async def add_channel(
self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None
): ):
debug(
f"The user {ctx.author} ran the add_channel 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
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:
@@ -217,12 +261,10 @@ class Setup(discord.Cog):
required=False, required=False,
) )
@default_permissions(administrator=True) @default_permissions(administrator=True)
@guild_only()
async def remove_channel( async def remove_channel(
self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None
): ):
debug(
f"The user {ctx.author} ran the remove_channel 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
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if curs_data.fetchone() is None: if curs_data.fetchone() is None:

View File

@@ -23,8 +23,18 @@ def debug(message):
else: else:
print(message) print(message)
def ctx_to_guid(ctx):
if ctx.guild is None:
return ctx.author.id
else:
return ctx.guild.id
def mg_to_guid(mg):
if mg.guild is None:
return mg.author.id
else:
return mg.guild.id
# connect to the database
con_data = sqlite3.connect("../database/data.db") con_data = sqlite3.connect("../database/data.db")
curs_data = con_data.cursor() curs_data = con_data.cursor()
con_premium = sqlite3.connect("../database/premium.db") con_premium = sqlite3.connect("../database/premium.db")

View File

@@ -1,5 +1,5 @@
import asyncio import asyncio
from config import curs_data, max_uses, curs_premium, con_data, debug, moderate from config import curs_data, max_uses, curs_premium, con_data, debug, moderate, mg_to_guid
import vision_processing import vision_processing
import re import re
import discord import discord
@@ -8,6 +8,12 @@ import openai
import emoji import emoji
import os import os
async def historicator(message):
if message.guild != None:
return message.channel
else:
return message.author
async def replace_mentions(content, bot): async def replace_mentions(content, bot):
mentions = re.findall(r"<@!?\d+>", content) mentions = re.findall(r"<@!?\d+>", content)
for mention in mentions: for mention in mentions:
@@ -50,15 +56,17 @@ def get_guild_data(message):
dict: A dictionary with the data of the guild dict: A dictionary with the data of the guild
""" """
guild_data = {} guild_data = {}
guid = mg_to_guid(message)
try: try:
curs_premium.execute( curs_premium.execute(
"SELECT * FROM data WHERE guild_id = ?", (message.guild.id,)) "SELECT * FROM data WHERE guild_id = ?", (guid,)
) # get the data of the guild
except: except:
pass pass
try: try:
curs_data.execute( curs_data.execute(
"SELECT * FROM model WHERE guild_id = ?", (message.guild.id,) "SELECT * FROM model WHERE guild_id = ?", (guid,)
) # get the model in the database ) # get the model in the database
data = curs_data.fetchone() data = curs_data.fetchone()
model = data[1] model = data[1]
@@ -74,7 +82,7 @@ def get_guild_data(message):
try: try:
curs_data.execute( curs_data.execute(
"SELECT * FROM images WHERE guild_id = ?", (message.guild.id,) "SELECT * FROM images WHERE guild_id = ?", (mg_to_guid(message),)
) # get the images setting in the database ) # get the images setting in the database
images = curs_data.fetchone() images = curs_data.fetchone()
except: except:
@@ -125,9 +133,10 @@ async def need_ignore_message(bot, data_dict, message, guild_data, original_mess
if ( if (
data_dict["uses_count_today"] >= max_uses data_dict["uses_count_today"] >= max_uses
and guild_data["premium"] == 0 and guild_data["premium"] == 0
and message.guild.id != 1050769643180146749 and mg_to_guid(message) != 1050769643180146749
): ):
await message.channel.send( hist = await historicator(message)
await hist.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." 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."
) )
return True return True
@@ -136,8 +145,14 @@ async def need_ignore_message(bot, data_dict, message, guild_data, original_mess
async def get_data_dict(message): async def get_data_dict(message):
try: try:
curs_data.execute( if isinstance(message.channel, discord.DMChannel):
"SELECT * FROM data WHERE guild_id = ?", (message.guild.id,)) curs_data.execute(
"SELECT * FROM data WHERE guild_id = ?", (mg_to_guid(message),)
)
else:
curs_data.execute(
"SELECT * FROM data WHERE guild_id = ?", (mg_to_guid(message),)
)
data = curs_data.fetchone() data = curs_data.fetchone()
# Create a dict with the data # Create a dict with the data
data_dict = { data_dict = {
@@ -154,15 +169,18 @@ async def get_data_dict(message):
"tts": bool(data[11]), "tts": bool(data[11]),
"pretend_to_be": data[12], "pretend_to_be": data[12],
"pretend_enabled": data[13], "pretend_enabled": data[13],
"images_enabled": 0,
"images_usage": 0,
} }
return data_dict return data_dict
except Exception as e: except Exception as e:
# Send an error message hist = await historicator(message)
await message.channel.send( await hist.send(
"The bot is not configured yet. Please use `//setup` to configure it. \n" + "The bot is not configured yet. Please use `//setup` to configure it. \n" +
"If it still doesn't work, it might be a database error. \n ```" + e.__str__() "If it still doesn't work, it might be a database error. \n ```" + e.__str__()
+ "```", delete_after=60 + "```", delete_after=60
) )
raise e
def get_prompt(guild_data, data_dict, message, pretend_to_be): def get_prompt(guild_data, data_dict, message, pretend_to_be):
# support for custom prompts # support for custom prompts
@@ -178,8 +196,8 @@ def get_prompt(guild_data, data_dict, message, pretend_to_be):
# replace the variables in the prompt with the actual values # replace the variables in the prompt with the actual values
prompt = ( prompt = (
prompt.replace("[prompt-prefix]", data_dict['prompt_prefix']) prompt.replace("[prompt-prefix]", data_dict['prompt_prefix'])
.replace("[server-name]", message.guild.name) .replace("[server-name]", message.guild.name if message.guild else "DMs conversation")
.replace("[channel-name]", message.channel.name) .replace("[channel-name]", message.channel.name if message.guild else "DMs conversation")
.replace( .replace(
"[date-and-time]", datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S") "[date-and-time]", datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S")
) )
@@ -212,26 +230,26 @@ async def chat_process(self, message):
original_message = None original_message = None
try: try:
# get the images setting in the database
curs_data.execute( curs_data.execute(
"SELECT * FROM images WHERE guild_id = ?", (message.guild.id,)) "SELECT * FROM images WHERE user_id = ?", (mg_to_guid(message)))
images_data = curs_data.fetchone() images_data = curs_data.fetchone()
except: except:
images_data = None images_data = None
## ---- Message processing ---- ##
if not images_data: if not images_data:
images_data = [message.guild.id, 0, 0] images_data = [0, 0, 0]
images_data = [mg_to_guid(message), 0, 0]
data_dict["images_usage"] = 0 if message.guild.id == 1050769643180146749 else images_data[1] data_dict["images_usage"] = 0 if mg_to_guid(message) == 1050769643180146749 else images_data[1]
print(type(images_data))
print(type(data_dict))
print(type(images_data[2]))
data_dict["images_enabled"] = images_data[2] data_dict["images_enabled"] = images_data[2]
data_dict["images_usage"] = images_data[1]
channels = [] channels = []
try: try:
curs_premium.execute( curs_premium.execute(
"SELECT * FROM channels WHERE guild_id = ?", (message.guild.id,)) "SELECT * FROM channels WHERE guild_id = ?", (mg_to_guid(message),) )
images_data = curs_premium.fetchone() images_data = curs_premium.fetchone()
if guild_data["premium"]: if guild_data["premium"]:
# for 5 times, we get c.fetchone()[1] to c.fetchone()[5] and we add it to the channels list, each time with try except # for 5 times, we get c.fetchone()[1] to c.fetchone()[5] and we add it to the channels list, each time with try except
@@ -248,32 +266,30 @@ async def chat_process(self, message):
return return
try: try:
await message.channel.trigger_typing() try: await message.channel.trigger_typing()
# if the message is not in the owner's guild we update the usage count except: pass
if message.guild.id != 1021872219888033903: if mg_to_guid(message) != 1021872219888033903:
curs_data.execute( curs_data.execute(
"UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?", "UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?",
(message.guild.id,), (mg_to_guid(message),),
) )
con_data.commit() con_data.commit()
# if the message is not a reply hist = await historicator(message)
if original_message == None: if original_message == None:
messages = await message.channel.history( messages = await hist.history(
limit=data_dict["prompt_size"] limit=data_dict["prompt_size"]
).flatten() ).flatten()
messages.reverse()
# if the message is a reply, we need to handle the message history differently
else: else:
messages = await message.channel.history( messages = await hist.history(
limit=data_dict["prompt_size"], before=original_message limit=data_dict["prompt_size"], before=original_message
).flatten() ).flatten()
messages.reverse() messages.reverse()
messages.append(original_message) messages.append(original_message)
messages.append(message) messages.append(message)
except Exception as e: except Exception as e:
debug("Error while getting message history", e) debug("Error while getting message history")
raise e
# if the pretend to be feature is enabled, we add the pretend to be text to the prompt
pretend_to_be = data_dict["pretend_to_be"] pretend_to_be = data_dict["pretend_to_be"]
pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}" if data_dict[ "pretend_enabled"] else "" pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}" if data_dict[ "pretend_enabled"] else ""
debug(f"Pretend to be: {pretend_to_be}") debug(f"Pretend to be: {pretend_to_be}")
@@ -293,7 +309,8 @@ async def chat_process(self, message):
emojis, string = await extract_emoji(response) emojis, string = await extract_emoji(response)
debug(f"Emojis: {emojis}") debug(f"Emojis: {emojis}")
if len(string) < 1996: if len(string) < 1996:
await message.channel.send(string, tts=data_dict["tts"]) hist = await historicator(message)
await hist.send(string, tts=data_dict["tts"])
else: else:
# we send in an embed if the message is too long # we send in an embed if the message is too long
embed = discord.Embed( embed = discord.Embed(
@@ -301,7 +318,8 @@ async def chat_process(self, message):
description=string, description=string,
color=discord.Color.brand_green(), color=discord.Color.brand_green(),
) )
await message.channel.send(embed=embed, tts=data_dict["tts"]) hist = await historicator(message)
await hist.send(embed=embed, tts=data_dict["tts"])
for emoji in emojis: for emoji in emojis:
# if the emoji is longer than 1 character, it's a custom emoji # if the emoji is longer than 1 character, it's a custom emoji
try: try:
@@ -317,7 +335,8 @@ async def chat_process(self, message):
except: except:
pass pass
else: else:
await message.channel.send( hist = await historicator(message)
await hist.send(
"The AI is not sure what to say (the response was empty)" "The AI is not sure what to say (the response was empty)"
) )
@@ -329,7 +348,8 @@ async def check_moderate(api_key, message, msg):
description=f"The message *{msg.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.", description=f"The message *{msg.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(), color=discord.Color.brand_red(),
) )
await message.channel.send( hist = await historicator(message)
await hist.send(
f"{msg.author.mention}", embed=embed, delete_after=10 f"{msg.author.mention}", embed=embed, delete_after=10
) )
message.delete() message.delete()
@@ -355,7 +375,8 @@ async def check_easter_egg(message, msgs):
} }
) )
await asyncio.sleep(1) await asyncio.sleep(1)
await message.channel.send( hist = await historicator(message)
await hist.send(
"https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif" "https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif"
) )
await message.channel.trigger_typing() await message.channel.trigger_typing()
@@ -363,7 +384,6 @@ async def check_easter_egg(message, msgs):
async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data): async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
debug("Using GPT-3.5 Turbo prompt")
msgs = [] # create the msgs list msgs = [] # create the msgs list
msgs.append( msgs.append(
{"name": "System", "role": "user", "content": prompt} {"name": "System", "role": "user", "content": prompt}
@@ -374,33 +394,29 @@ async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
content = await replace_mentions( content = await replace_mentions(
content, bot content, bot
) # replace the mentions in the message ) # replace the mentions in the message
# if the message is flagged as inappropriate by the OpenAI API, we delete it, send a message and ignore it
if await check_moderate(data_dict["api_key"], message, msg): if await check_moderate(data_dict["api_key"], message, msg):
continue # ignore the message continue
content = await replace_mentions(content, bot) content = await replace_mentions(content, bot)
prompt += f"{msg.author.name}: {content}\n"
if msg.author.id == bot.user.id: if msg.author.id == bot.user.id:
role = "assistant" role = "assistant"
name = "assistant" name = "assistant"
else: else:
role = "user" role = "user"
name = msg.author.name 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) name = re.sub(r"[^a-zA-Z0-9_-]", "", name)
if False: # GPT-4 images if False: # GPT-4 images, not implemented yet
input_content = [content] input_content = [content]
for attachment in msg.attachments: for attachment in msg.attachments:
image_bytes = await attachment.read() image_bytes = await attachment.read()
input_content.append({"image": image_bytes}) input_content.append({"image": image_bytes})
msgs.append({"role": role, "content": input_content, "name": name}) msgs.append({"role": role, "content": input_content, "name": name})
# if there is an attachment, we add it to the message
if ( if (
len(msg.attachments) > 0 len(msg.attachments) > 0
and role == "user" and role == "user"
and data_dict["images_enabled"] == 1 and data_dict["images_enabled"] == 1
): ):
for attachment in msg.attachments: for attachment in msg.attachments:
print("attachment found")
path = f"./../database/google-vision/results/{attachment.id}.txt" path = f"./../database/google-vision/results/{attachment.id}.txt"
if data_dict['images_usage'] >= 6 and guild_data["premium"] == 0: if data_dict['images_usage'] >= 6 and guild_data["premium"] == 0:
guild_data["images_limit_reached"] = True guild_data["images_limit_reached"] = True
@@ -450,12 +466,10 @@ async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
) )
curs_data.execute( curs_data.execute(
"UPDATE images SET usage_count = ? WHERE guild_id = ?", "UPDATE images SET usage_count = ? WHERE guild_id = ?",
(data_dict['images_usage'], message.guild.id), (data_dict['images_usage'], mg_to_guid(message)),
) )
else: else:
msgs.append({"role": role, "content": f"{content}", "name": name}) msgs.append({"role": role, "content": f"{content}", "name": name})
# We check for the eastereggs :)
msgs = await check_easter_egg(message, msgs) msgs = await check_easter_egg(message, msgs)
response = "" response = ""
@@ -486,7 +500,8 @@ async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
should_break = True should_break = True
except Exception as e: except Exception as e:
should_break = False should_break = False
await message.channel.send( hist = await historicator(message)
await hist.send(
f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=5 f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=5
) )
# 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)
@@ -499,7 +514,8 @@ async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
response = response.choices[0].message.content response = response.choices[0].message.content
if guild_data["images_limit_reached"]: if guild_data["images_limit_reached"]:
await message.channel.send( hist = await historicator(message)
await hist.send(
f"```diff\n-Warning: You have reached the image limit for this server. You can upgrade to premium to get more images recognized. More info in our server: https://discord.gg/sxjHtmqrbf```", f"```diff\n-Warning: You have reached the image limit for this server. You can upgrade to premium to get more images recognized. More info in our server: https://discord.gg/sxjHtmqrbf```",
delete_after=10, delete_after=10,
) )
@@ -539,7 +555,8 @@ async def davinci_prompt(self, messages, message, data_dict, prompt, guild_data)
response = response.choices[0].text response = response.choices[0].text
except Exception as e: except Exception as e:
response = None response = None
await message.channel.send( hist = await historicator(message)
await hist.send(
f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=10 f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=10
) )
return return