Merge pull request #34 from Alestrio/dev

Dev
This commit is contained in:
Paillat
2023-04-01 14:50:17 +02:00
committed by GitHub
24 changed files with 1736 additions and 815 deletions

21
.github/workflows/buildDockerImage.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
# Building Docker image and pushing it to Docker Hub
name: Build Docker Image
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build Docker image
run: |
docker build -t ${{ secrets.DOCKER_USERNAME }}/botator:${{ github.sha }} .
- name: Push Docker image to Docker Hub
run: |
echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
docker push ${{ secrets.DOCKER_USERNAME }}/botator:${{ github.sha }}

3
.gitignore vendored
View File

@@ -6,6 +6,9 @@ __pycache__/
# C extensions # C extensions
*.so *.so
# VSCode
.vscode
# Distribution / packaging # Distribution / packaging
.Python .Python
build/ build/

View File

@@ -6,9 +6,21 @@ ENV PYTHONUNBUFFERED=1
# Install pip requirements # Install pip requirements
COPY requirements.txt . COPY requirements.txt .
RUN pip install -r requirements.txt RUN pip install -r requirements.txt
RUN git clone https://github.com/Paillat-dev/Botator.git
WORKDIR /Botator/code/
# Creates a non-root user with an explicit UID and adds permission to access the /app folder # Creates a non-root user with an explicit UID and adds permission to access the /app folder
RUN mkdir /Botator
RUN mkdir /Botator/code
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /Botator/code RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /Botator/code
COPY ./code /Botator/code
WORKDIR /Botator/code/
# Create database folder and files (otherwise it will crash)
RUN mkdir /Botator/database
RUN touch /Botator/database/data.db
RUN touch /Botator/database/premium.db
RUN chown -R appuser /Botator/database
RUN mkdir /Botator/database/google
USER appuser USER appuser
CMD ["python", "code.py"] CMD ["python", "code.py"]

View File

@@ -1,9 +1,8 @@
#coucou c'est fives import discord # discord.py
# wesh wesh ici latouff
import discord # pip install pycord
from discord import Intents from discord import Intents
import cogs # import the cogs import cogs # import the cogs
from config import debug, 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 # 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
@@ -15,19 +14,20 @@ bot.add_cog(cogs.Chat(bot))
bot.add_cog(cogs.ManageChat(bot)) bot.add_cog(cogs.ManageChat(bot))
bot.add_cog(cogs.Moderation(bot)) bot.add_cog(cogs.Moderation(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")
bot.run(discord_token) # run the bot bot.run(discord_token) # run the bot
# set the bot's watching status to watcing your messages to answer you # set the bot's watching status to watcing your messages to answer you
@bot.event @bot.event
async def on_ready(): async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="your messages to answer you")) 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")
@bot.event @bot.event
async def on_application_command_error(ctx, error): async def on_application_command_error(ctx, error):
debug(error) debug(error)

View File

@@ -1,62 +1,97 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
from config import debug, c, max_uses, cp, conn, connp, webhook_url from config import debug, curs_data, max_uses, curs_premium, con_data, con_premium, webhook_url
import makeprompt as mp import makeprompt as mp
import aiohttp import aiohttp
class MyModal(discord.ui.Modal): class MyModal(discord.ui.Modal):
def __init__(self, message): def __init__(self, message):
super().__init__(title="Downvote") super().__init__(title="Downvote")
self.add_item(discord.ui.InputText(label="Reason", style=discord.InputTextStyle.long)) self.add_item(
discord.ui.InputText(
label="Reason", style=discord.InputTextStyle.long)
)
self.message = message self.message = message
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
debug("Downvote sent !") debug("Downvote sent !")
embed = discord.Embed(title="Thanks for your feedback !", description="Your downvote has been sent to the developers. Thanks for your help !", color=discord.Color.og_blurple()) embed = discord.Embed(
title="Thanks for your feedback !",
description="Your downvote has been sent to the developers. Thanks for your help !",
color=discord.Color.og_blurple(),
)
embed.add_field(name="Message", value=self.children[0].value) embed.add_field(name="Message", value=self.children[0].value)
await interaction.response.send_message(embed=embed, ephemeral=True) await interaction.response.send_message(embed=embed, ephemeral=True)
if webhook_url != "" and webhook_url != None: if webhook_url != "" and webhook_url != None:
session = aiohttp.ClientSession() session = aiohttp.ClientSession()
webhook = discord.Webhook.from_url(webhook_url, session=session) webhook = discord.Webhook.from_url(webhook_url, session=session)
embed = discord.Embed(title="Downvote", description=f"Downvote recieved!", color=discord.Color.og_blurple()) embed = discord.Embed(
embed.add_field(name="Reason", value=self.children[0].value, inline=True) title="Downvote",
embed.add_field(name="Author", value=interaction.user.mention, inline=True) description=f"Downvote recieved!",
embed.add_field(name="Channel", value=self.message.channel.name, inline=True) color=discord.Color.og_blurple(),
embed.add_field(name="Guild", value=self.message.guild.name, inline=True) )
history = await self.message.channel.history(limit=5, before=self.message).flatten()
embed.add_field(
name="Reason", value=self.children[0].value, inline=True)
embed.add_field(
name="Author", value=interaction.user.mention, inline=True)
embed.add_field(
name="Channel", value=self.message.channel.name, inline=True
)
embed.add_field(
name="Guild", value=self.message.guild.name, inline=True)
history = await self.message.channel.history(
limit=5, before=self.message
).flatten()
history.reverse() history.reverse()
users = [] users = []
fake_users = [] fake_users = []
for user in history: for user in history:
if user.author not in users: if user.author not in users:
# we anonimize the user, so user1, user2, user3, etc # we anonimize the user, so user1, user2, user3, etc
fake_users.append(f"user{len(fake_users)+1}") fake_users.append(f"user{len(fake_users)+1}")
users.append(user.author) users.append(user.author)
if self.message.author not in users: if self.message.author not in users:
fake_users.append(f"user{len(fake_users)+1}") fake_users.append(f"user{len(fake_users)+1}")
users.append(self.message.author) users.append(self.message.author)
for msg in history: for msg in history:
uname = fake_users[users.index(msg.author)] uname = fake_users[users.index(msg.author)]
if len(msg.content) > 1023: if len(msg.content) > 1023:
embed.add_field(name=f"{uname} said", value=msg.content[:1023], inline=False) embed.add_field(
name=f"{uname} said", value=msg.content[:1023], inline=False
)
else: else:
embed.add_field(name=f"{uname} said", value=msg.content, inline=False) embed.add_field(
if len(self.message.content) > 1021: name=f"{uname} said", value=msg.content, inline=False
)
uname = fake_users[users.index(self.message.author)] uname = fake_users[users.index(self.message.author)]
embed.add_field(name=f"{uname} said", value="*"+self.message.content[:1021]+"*", inline=False) embed.add_field(
else: name=f"{uname} said",
uname = fake_users[users.index(self.message.author)] value="*" + self.message.content[:1021] + "*" if len(
embed.add_field(name=f"{uname} said", value="*"+self.message.content+"*", inline=False) self.message.content) > 1021 else "*" + self.message.content + "*", # [:1021] if len(self.message.content) > 1021,
# means that if the message is longer than 1021 characters, it will be cut at 1021 characters
inline=False,
)
await webhook.send(embed=embed) await webhook.send(embed=embed)
else: else:
debug("Error while sending webhook, probably no webhook is set up in the .env file") debug(
"Error while sending webhook, probably no webhook is set up in the .env file"
)
class Chat(discord.Cog): class Chat(discord.Cog):
def __init__(self, bot: discord.Bot): def __init__(self, bot: discord.Bot):
super().__init__() super().__init__()
self.bot = bot self.bot = bot
@discord.Cog.listener() @discord.Cog.listener()
async def on_message(self, message: discord.Message): async def on_message(self, message: discord.Message):
await mp.chat_process(self, message) await mp.chat_process(self, message)
@@ -78,8 +113,6 @@ class Chat (discord.Cog) :
await ctx.respond("Message redone !", ephemeral=True) await ctx.respond("Message redone !", ephemeral=True)
await mp.chat_process(self, message_to_redo) await mp.chat_process(self, message_to_redo)
@discord.message_command(name="Downvote", description="Downvote a message") @discord.message_command(name="Downvote", description="Downvote a message")
@commands.cooldown(1, 60, commands.BucketType.user) @commands.cooldown(1, 60, commands.BucketType.user)
async def downvote(self, ctx: discord.ApplicationContext, message: discord.Message): async def downvote(self, ctx: discord.ApplicationContext, message: discord.Message):
@@ -87,7 +120,9 @@ class Chat (discord.Cog) :
modal = MyModal(message) modal = MyModal(message)
await ctx.send_modal(modal) await ctx.send_modal(modal)
else: else:
await ctx.respond("You can't downvote a message that is not from me !", ephemeral=True) await ctx.respond(
"You can't downvote a message that is not from me !", ephemeral=True
)
@downvote.error @downvote.error
async def downvote_error(self, ctx, error): async def downvote_error(self, ctx, error):

View File

@@ -1,6 +1,7 @@
import discord import discord
from config import debug 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:
super().__init__() super().__init__()
@@ -8,37 +9,101 @@ 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}") debug(
embed = discord.Embed(title="Help", description="Here is the help page", color=0x00ff00) 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(
title="Help", description="Here is the help page", color=0x00FF00
)
embed.add_field(name="/setup", value="Setup the bot", inline=False) embed.add_field(name="/setup", value="Setup the bot", inline=False)
embed.add_field(name="/enable", value="Enable the bot", inline=False) embed.add_field(name="/enable", value="Enable the bot", inline=False)
embed.add_field(name="/disable", value="Disable the bot", inline=False) embed.add_field(name="/disable", value="Disable the bot", inline=False)
embed.add_field(name="/advanced", value="Set the advanced settings", inline=False) embed.add_field(
embed.add_field(name="/advanced_help", value="Get help about the advanced settings", inline=False) name="/advanced", value="Set the advanced settings", inline=False
embed.add_field(name="/enable_tts", value="Enable the Text To Speech", inline=False) )
embed.add_field(name="/disable_tts", value="Disable the Text To Speech", inline=False) embed.add_field(
embed.add_field(name="/add|remove_channel", value="Add or remove a channel to the list of channels where the bot will answer. Only available on premium guilds", inline=False) name="/advanced_help",
embed.add_field(name="/delete", value="Delete all your data from our server", inline=False) value="Get help about the advanced settings",
embed.add_field(name="/cancel", value="Cancel the last message sent by the bot", inline=False) inline=False,
embed.add_field(name="/default", value="Set the advanced settings to their default values", inline=False) )
embed.add_field(
name="/enable_tts", value="Enable the Text To Speech", inline=False
)
embed.add_field(
name="/disable_tts", value="Disable the Text To Speech", inline=False
)
embed.add_field(
name="/add|remove_channel",
value="Add or remove a channel to the list of channels where the bot will answer. Only available on premium guilds",
inline=False,
)
embed.add_field(
name="/delete", value="Delete all your data from our server", inline=False
)
embed.add_field(
name="/cancel",
value="Cancel the last message sent by the bot",
inline=False,
)
embed.add_field(
name="/default",
value="Set the advanced settings to their default values",
inline=False,
)
embed.add_field(name="/say", value="Say a message", inline=False) embed.add_field(name="/say", value="Say a message", inline=False)
embed.add_field(name="/redo", value="Redo the last message sent by the bot", inline=False) embed.add_field(
embed.add_field(name="/moderation", value="Setup the AI auto-moderation", inline=False) name="/redo", value="Redo the last message sent by the bot", inline=False
embed.add_field(name="/get_toxicity", value="Get the toxicity that the AI would have given to a given message", inline=False) )
embed.add_field(
name="/moderation", value="Setup the AI auto-moderation", inline=False
)
embed.add_field(
name="/get_toxicity",
value="Get the toxicity that the AI would have given to a given message",
inline=False,
)
embed.add_field(name="/help", value="Show this message", inline=False) embed.add_field(name="/help", value="Show this message", inline=False)
# add a footer # add a footer
embed.set_footer(text="Made by @Paillat#7777") embed.set_footer(text="Made by @Paillat#7777")
await ctx.respond(embed=embed, ephemeral=True) await ctx.respond(embed=embed, ephemeral=True)
@discord.slash_command(name="advanced_help", description="Show the advanced settings meanings") @discord.slash_command(
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}") debug(
embed = discord.Embed(title="Advanced Help", description="Here is the advanced help page", color=0x00ff00) 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.add_field(name="temperature", value="The higher the temperature, the more likely the model will take risks. Conversely, a lower temperature will make the model more conservative. The default value is 0.9", inline=False) )
embed.add_field(name="max_tokens", value="The maximum number of tokens to generate. Higher values will result in more coherent text, but will take longer to complete. (default: 50). **Lower values will result in somentimes cutting off the end of the answer, but will be faster.**", inline=False) embed = discord.Embed(
embed.add_field(name="frequency_penalty", value="The higher the frequency penalty, the more new words the model will introduce (default: 0.0)", inline=False) title="Advanced Help",
embed.add_field(name="presence_penalty", value="The higher the presence penalty, the more new words the model will introduce (default: 0.0)", inline=False) description="Here is the advanced help page",
embed.add_field(name="prompt_size", value="The number of messages to use as a prompt (default: 5). The more messages, the more coherent the text will be, but the more it will take to generate and the more it will cost.", inline=False) color=0x00FF00,
)
embed.add_field(
name="temperature",
value="The higher the temperature, the more likely the model will take risks. Conversely, a lower temperature will make the model more conservative. The default value is 0.9",
inline=False,
)
embed.add_field(
name="max_tokens",
value="The maximum number of tokens to generate. Higher values will result in more coherent text, but will take longer to complete. (default: 50). **Lower values will result in somentimes cutting off the end of the answer, but will be faster.**",
inline=False,
)
embed.add_field(
name="frequency_penalty",
value="The higher the frequency penalty, the more new words the model will introduce (default: 0.0)",
inline=False,
)
embed.add_field(
name="presence_penalty",
value="The higher the presence penalty, the more new words the model will introduce (default: 0.0)",
inline=False,
)
embed.add_field(
name="prompt_size",
value="The number of messages to use as a prompt (default: 5). The more messages, the more coherent the text will be, but the more it will take to generate and the more it will cost.",
inline=False,
)
# add a footer # add a footer
embed.set_footer(text="Made by @Paillat#7777") embed.set_footer(text="Made by @Paillat#7777")
await ctx.respond(embed=embed, ephemeral=True) await ctx.respond(embed=embed, ephemeral=True)

View File

@@ -1,20 +1,28 @@
import discord import discord
import re import re
import os import os
from config import debug, c from config import debug, curs_data
class ManageChat(discord.Cog): class ManageChat(discord.Cog):
def __init__(self, bot: discord.Bot) -> None: def __init__(self, bot: discord.Bot) -> None:
super().__init__() super().__init__()
self.bot = bot self.bot = bot
@discord.slash_command(name="cancel", description="Cancel the last message sent into a channel") @discord.slash_command(
name="cancel", description="Cancel the last message sent into a channel"
)
async def cancel(self, ctx: discord.ApplicationContext): async def cancel(self, ctx: discord.ApplicationContext):
debug(f"The user {ctx.author} ran the cancel command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") debug(
f"The user {ctx.author} ran the cancel 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,)) curs_data.execute(
if c.fetchone() is None: "SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
await ctx.respond("This server is not setup, please run /setup", ephemeral=True) if curs_data.fetchone() is None:
await ctx.respond(
"This server is not setup, please run /setup", ephemeral=True
)
return return
# get the last message sent by the bot in the cha where the command was sent # get the last message sent by the bot in the cha where the command was sent
last_message = await ctx.channel.fetch_message(ctx.channel.last_message_id) last_message = await ctx.channel.fetch_message(ctx.channel.last_message_id)
@@ -23,16 +31,31 @@ class ManageChat (discord.Cog):
await ctx.respond("The last message has been deleted", ephemeral=True) await ctx.respond("The last message has been deleted", ephemeral=True)
# add a slash command called "clear" that deletes all the messages in the channel # add a slash command called "clear" that deletes all the messages in the channel
@discord.slash_command(name="clear", description="Clear all the messages in the channel") @discord.slash_command(
name="clear", description="Clear all the messages in the channel"
)
async def clear(self, ctx: discord.ApplicationContext): async def clear(self, ctx: discord.ApplicationContext):
debug(f"The user {ctx.author.name} ran the clear 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 clear command command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
await ctx.respond("messages deleted!", ephemeral=True) await ctx.respond("messages deleted!", ephemeral=True)
return await ctx.channel.purge() return await ctx.channel.purge()
@discord.slash_command(name="transcript", description="Get a transcript of the messages that have been sent in this channel intoa text file") @discord.slash_command(
@discord.option(name="channel_send", description="The channel to send the transcript to", required=False) name="transcript",
async def transcript(self, ctx: discord.ApplicationContext, channel_send: discord.TextChannel = None): description="Get a transcript of the messages that have been sent in this channel intoa text file",
debug(f"The user {ctx.author.name} ran the transcript command command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") )
@discord.option(
name="channel_send",
description="The channel to send the transcript to",
required=False,
)
async def transcript(
self, ctx: discord.ApplicationContext, channel_send: discord.TextChannel = None
):
debug(
f"The user {ctx.author.name} ran the transcript command command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
# save all the messages in the channel in a txt file and send it # save all the messages in the channel in a txt file and send it
messages = await ctx.channel.history(limit=None).flatten() messages = await ctx.channel.history(limit=None).flatten()
messages.reverse() messages.reverse()
@@ -51,7 +74,9 @@ class ManageChat (discord.Cog):
# get the user # get the user
user = await self.bot.fetch_user(id) user = await self.bot.fetch_user(id)
# replace the mention with the name # replace the mention with the name
msg.content = msg.content.replace(mention, msg.guild.get_member(user.id).name) msg.content = msg.content.replace(
mention, msg.guild.get_member(user.id).name
)
transcript += f"{msg.author.name}: {msg.content}\n" transcript += f"{msg.author.name}: {msg.content}\n"
# save the transcript in a txt file called transcript.txt. If the file already exists, delete it and create a new one # save the transcript in a txt file called transcript.txt. If the file already exists, delete it and create a new one
# check if the file exists # check if the file exists
@@ -60,15 +85,37 @@ class ManageChat (discord.Cog):
f = open("transcript.txt", "w") f = open("transcript.txt", "w")
f.write(transcript) f.write(transcript)
f.close() f.close()
last_message: discord.Message = await ctx.channel.fetch_message(ctx.channel.last_message_id) last_message: discord.Message = await ctx.channel.fetch_message(
ctx.channel.last_message_id
)
new_file_name = f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt"
# rename the file with the name of the channel and the date in this format: transcript_servername_channelname_dd-month-yyyy.txt ex : transcript_Botator_Testing_12-may-2021.txt # rename the file with the name of the channel and the date in this format: transcript_servername_channelname_dd-month-yyyy.txt ex : transcript_Botator_Testing_12-may-2021.txt
os.rename("transcript.txt", f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt") os.rename(
"transcript.txt",
new_file_name,
)
# send the file in a private message to the user who ran the command # send the file in a private message to the user who ran the command
# TODO: rework so as to give the choice of a private send or a public send
if channel_send is None: if channel_send is None:
await ctx.respond(file=discord.File(f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt"), ephemeral=True) await ctx.respond(
file=discord.File(
new_file_name
),
ephemeral=True,
)
else: else:
await channel_send.send(file=discord.File(f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt")) await channel_send.send(
file=discord.File(
new_file_name
)
)
await ctx.respond("Transcript sent!", ephemeral=True, delete_after=5) await ctx.respond("Transcript sent!", ephemeral=True, delete_after=5)
await ctx.author.send(file=discord.File(f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt")) await ctx.author.send(
file=discord.File(
new_file_name
)
)
# delete the file # delete the file
os.remove(f"transcript_{ctx.guild.name}_{ctx.channel.name}_{last_message.created_at.strftime('%d-%B-%Y')}.txt") os.remove(
new_file_name
)

View File

@@ -1,87 +1,196 @@
import discord import discord
from discord import default_permissions from discord import default_permissions
import os import os
from config import debug, c, conn from config import debug, curs_data, con_data
import openai import openai
import requests import requests
import toxicity as tox #this is a file called toxicity.py, which contains the toxicity function that allows you to check if a message is toxic or not (it uses the perspective api)
class Moderation(discord.Cog): class Moderation(discord.Cog):
def __init__(self, bot: discord.Bot) -> None: def __init__(self, bot: discord.Bot) -> None:
super().__init__() super().__init__()
self.bot = bot self.bot = bot
@discord.slash_command(name="moderation", description="Enable or disable AI moderation & set the rules")
@discord.option(name="enable", description="Enable or disable AI moderation", reqired=True,) @discord.slash_command(
@discord.option(name="log_channel", description="The channel where the moderation logs will be sent", required=True) name="moderation", description="Enable or disable AI moderation & set the rules"
@discord.option(name="moderator_role", description="The role of the moderators", required=True) )
@discord.option(
name="enable",
description="Enable or disable AI moderation",
reqired=True,
)
@discord.option(
name="log_channel",
description="The channel where the moderation logs will be sent",
required=True,
)
@discord.option(
name="moderator_role", description="The role of the moderators", required=True
)
# the types of toxicity are 'requestedAttributes': {'TOXICITY': {}, 'SEVERE_TOXICITY': {}, 'IDENTITY_ATTACK': {}, 'INSULT': {}, 'PROFANITY': {}, 'THREAT': {}, 'SEXUALLY_EXPLICIT': {}, 'FLIRTATION': {}, 'OBSCENE': {}, 'SPAM': {}}, # the types of toxicity are 'requestedAttributes': {'TOXICITY': {}, 'SEVERE_TOXICITY': {}, 'IDENTITY_ATTACK': {}, 'INSULT': {}, 'PROFANITY': {}, 'THREAT': {}, 'SEXUALLY_EXPLICIT': {}, 'FLIRTATION': {}, 'OBSCENE': {}, 'SPAM': {}},
@discord.option(name="toxicity", description="The toxicity threshold", required=False) @discord.option(
@discord.option(name="severe_toxicity", description="The severe toxicity threshold", required=False) name="toxicity", description="The toxicity threshold", required=False
@discord.option(name="identity_attack", description="The identity attack threshold", required=False) )
@discord.option(
name="severe_toxicity",
description="The severe toxicity threshold",
required=False,
)
@discord.option(
name="identity_attack",
description="The identity attack threshold",
required=False,
)
@discord.option(name="insult", description="The insult threshold", required=False) @discord.option(name="insult", description="The insult threshold", required=False)
@discord.option(name="profanity", description="The profanity threshold", required=False) @discord.option(
name="profanity", description="The profanity threshold", required=False
)
@discord.option(name="threat", description="The threat threshold", required=False) @discord.option(name="threat", description="The threat threshold", required=False)
@discord.option(name="sexually_explicit", description="The sexually explicit threshold", required=False) @discord.option(
@discord.option(name="flirtation", description="The flirtation threshold", required=False) name="sexually_explicit",
description="The sexually explicit threshold",
required=False,
)
@discord.option(
name="flirtation", description="The flirtation threshold", required=False
)
@discord.option(name="obscene", description="The obscene threshold", required=False) @discord.option(name="obscene", description="The obscene threshold", required=False)
@discord.option(name="spam", description="The spam threshold", required=False) @discord.option(name="spam", description="The spam threshold", required=False)
# we set the default permissions to the administrator permission, so only the server administrators can use this command # we set the default permissions to the administrator permission, so only the server administrators can use this command
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def moderation(self, ctx: discord.ApplicationContext, enable: bool, log_channel: discord.TextChannel, moderator_role: discord.Role, toxicity: float = None, severe_toxicity: float = None, identity_attack: float = None, insult: float = None, profanity: float = None, threat: float = None, sexually_explicit: float = None, flirtation: float = None, obscene: float = None, spam: float = None): async def moderation(
await ctx.respond("Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://github.com/Paillat-dev/Moderator/ \n If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv", ephemeral=True) self,
ctx: discord.ApplicationContext,
enable: bool,
log_channel: discord.TextChannel,
moderator_role: discord.Role,
toxicity: float = None,
severe_toxicity: float = None,
identity_attack: float = None,
insult: float = None,
profanity: float = None,
threat: float = None,
sexually_explicit: float = None,
flirtation: float = None,
obscene: float = None,
spam: float = None,
):
# local import, because we don't want to import the toxicity function if the moderation is disabled
# import toxicity as tox # this is a file called toxicity.py, which contains the toxicity function that allows you to check if a message is toxic or not (it uses the perspective api)
await ctx.respond(
"Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://github.com/Paillat-dev/Moderator/ \n If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv",
ephemeral=True,
)
if enable == False: if enable == False:
c.execute("DELETE FROM moderation WHERE guild_id = ?", (str(ctx.guild.id),)) curs_data.execute("DELETE FROM moderation WHERE guild_id = ?", (str(ctx.guild.id),))
conn.commit() con_data.commit()
await ctx.respond("Moderation disabled!", ephemeral=True) await ctx.respond("Moderation disabled!", ephemeral=True)
return return
@discord.Cog.listener() # Moderation has been moved to a new bot..
async def on_message(self, message: discord.Message): # @discord.Cog.listener()
if message.author == self.bot.user: return # async def on_message(self, message: discord.Message):
try: c.execute("SELECT * FROM moderation WHERE guild_id = ?", (str(message.guild.id),)) # if message.author == self.bot.user:
except: return # return
data = c.fetchone() # try:
if data is None: return # curs_data.execute(
channel = self.bot.get_channel(int(data[1])) # "SELECT * FROM moderation WHERE guild_id = ?", (str(message.guild.id),)
is_enabled = data[2] # )
moderator_role = message.guild.get_role(int(data[3])) # except:
#we also do that with the manage_messages permission, so the moderators can't be moderated # return
if message.author.guild_permissions.manage_messages: return #if the user is a moderator, we don't want to moderate him because he is allowed to say whatever he wants because he is just like a dictator # data = curs_data.fetchone()
if message.author.guild_permissions.administrator: return #if the user is an administrator, we don't want to moderate him because he is allowed to say whatever he wants because he is a DICTATOR # if data is None:
if not is_enabled: return # return
content = message.content # channel = self.bot.get_channel(int(data[1]))
message_toxicity = tox.get_toxicity(content) # is_enabled = data[2]
reasons_to_delete = [] # moderator_role = message.guild.get_role(int(data[3]))
reasons_to_suspicous = [] # # we also do that with the manage_messages permission, so the moderators can't be moderated
for i in message_toxicity: # if message.author.guild_permissions.manage_messages:
if i >= float(data[message_toxicity.index(i)+4]): reasons_to_delete.append(tox.toxicity_names[message_toxicity.index(i)]) # return # if the user is a moderator, we don't want to moderate him because he is allowed to say whatever he wants because he is just like a dictator
for i in message_toxicity: # if message.author.guild_permissions.administrator:
if float(data[message_toxicity.index(i)+4]-0.1) <= i < float(data[message_toxicity.index(i)+4]): reasons_to_suspicous.append(tox.toxicity_names[message_toxicity.index(i)]) # return # if the user is an administrator, we don't want to moderate him because he is allowed to say whatever he wants because he is a DICTATOR
if len(reasons_to_delete) > 0: # if not is_enabled:
embed = discord.Embed(title="Message deleted", description=f"Your message was deleted because it was too toxic. The following reasons were found: **{'**, **'.join(reasons_to_delete)}**", color=discord.Color.red()) # return
await message.reply(f"{message.author.mention}", embed=embed, delete_after=15) # content = message.content
await message.delete() # message_toxicity = tox.get_toxicity(content)
embed = discord.Embed(title="Message deleted", description=f"**{message.author}**'s message ***{content}*** was deleted because it was too toxic. The following reasons were found:", color=discord.Color.red()) # reasons_to_delete = []
for i in reasons_to_delete: # reasons_to_suspicous = []
toxicity_value = message_toxicity[tox.toxicity_names.index(i)] # for i in message_toxicity:
embed.add_field(name=i, value=f"Found toxicity value: **{toxicity_value*100}%**", inline=False) # if i >= float(data[message_toxicity.index(i) + 4]):
await channel.send(embed=embed) # reasons_to_delete.append(tox.toxicity_names[message_toxicity.index(i)])
elif len(reasons_to_suspicous) > 0: # for i in message_toxicity:
await message.reply(f"{moderator_role.mention} This message might be toxic. The following reasons were found: **{'**, **'.join(reasons_to_suspicous)}**", delete_after=15, mention_author=False) # if (
embed = discord.Embed(title="Message suspicious", description=f"**{message.author}**'s message [***{content}***]({message.jump_url}) might be toxic. The following reasons were found:", color=discord.Color.orange()) # float(data[message_toxicity.index(i) + 4] - 0.1)
for i in reasons_to_suspicous: # <= i
toxicity_value = message_toxicity[tox.toxicity_names.index(i)] # < float(data[message_toxicity.index(i) + 4])
embed.add_field(name=i, value=f"Found toxicity value: **{toxicity_value*100}%**", inline=False) # ):
await channel.send(embed=embed) # reasons_to_suspicous.append(
#we add a reaction to the message so the moderators can easily find it orange circle emoji # tox.toxicity_names[message_toxicity.index(i)]
await message.add_reaction("🟠") # )
# if len(reasons_to_delete) > 0:
# embed = discord.Embed(
# title="Message deleted",
# description=f"Your message was deleted because it was too toxic. The following reasons were found: **{'**, **'.join(reasons_to_delete)}**",
# color=discord.Color.red(),
# )
# await message.reply(
# f"{message.author.mention}", embed=embed, delete_after=15
# )
# await message.delete()
# embed = discord.Embed(
# title="Message deleted",
# description=f"**{message.author}**'s message ***{content}*** was deleted because it was too toxic. The following reasons were found:",
# color=discord.Color.red(),
# )
# for i in reasons_to_delete:
# toxicity_value = message_toxicity[tox.toxicity_names.index(i)]
# embed.add_field(
# name=i,
# value=f"Found toxicity value: **{toxicity_value*100}%**",
# inline=False,
# )
# await channel.send(embed=embed)
# elif len(reasons_to_suspicous) > 0:
# await message.reply(
# f"{moderator_role.mention} This message might be toxic. The following reasons were found: **{'**, **'.join(reasons_to_suspicous)}**",
# delete_after=15,
# mention_author=False,
# )
# embed = discord.Embed(
# title="Message suspicious",
# description=f"**{message.author}**'s message [***{content}***]({message.jump_url}) might be toxic. The following reasons were found:",
# color=discord.Color.orange(),
# )
# for i in reasons_to_suspicous:
# toxicity_value = message_toxicity[tox.toxicity_names.index(i)]
# embed.add_field(
# name=i,
# value=f"Found toxicity value: **{toxicity_value*100}%**",
# inline=False,
# )
# await channel.send(embed=embed)
# # we add a reaction to the message so the moderators can easily find it orange circle emoji
# await message.add_reaction("🟠")
@discord.slash_command(name="get_toxicity", description="Get the toxicity of a message") @discord.slash_command(
@discord.option(name="message", description="The message you want to check", required=True) name="get_toxicity", description="Get the toxicity of a message"
)
@discord.option(
name="message", description="The message you want to check", required=True
)
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def get_toxicity(self, ctx: discord.ApplicationContext, message: str): async def get_toxicity(self, ctx: discord.ApplicationContext, message: str):
await ctx.respond("Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://discord.gg/pB6hXtUeDv . If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv", ephemeral=True) await ctx.respond(
"Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://discord.gg/pB6hXtUeDv . If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv",
ephemeral=True,
)
@discord.slash_command(name="moderation_help", description="Get help with the moderation AI") @discord.slash_command(
name="moderation_help", description="Get help with the moderation AI"
)
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def moderation_help(self, ctx: discord.ApplicationContext): async def moderation_help(self, ctx: discord.ApplicationContext):
await ctx.respond("Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://github.com/Paillat-dev/Moderator/ . If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv", ephemeral=True) await ctx.respond(
"Our moderation capabilities have been switched to our new 100% free and open-source AI discord moderation bot! You add it to your server here: https://discord.com/api/oauth2/authorize?client_id=1071451913024974939&permissions=1377342450896&scope=bot and you can find the source code here: https://github.com/Paillat-dev/Moderator/ . If you need help, you can join our support server here: https://discord.gg/pB6hXtUeDv",
ephemeral=True,
)

View File

@@ -1,9 +1,12 @@
import discord import discord
from config import debug, conn, c, moderate from config import debug, con_data, curs_data, moderate
from discord import default_permissions from discord import default_permissions
import openai import openai
models = ["davinci", "chatGPT", "gpt-4"]
models = ["davinci", "gpt-3.5-turbo", "gpt-4"]
images_recognition = ["enable", "disable"] images_recognition = ["enable", "disable"]
class Settings(discord.Cog): class Settings(discord.Cog):
def __init__(self, bot: discord.Bot) -> None: def __init__(self, bot: discord.Bot) -> None:
super().__init__() super().__init__()
@@ -15,18 +18,38 @@ class Settings (discord.Cog) :
# add the options # add the options
@discord.option(name="max_tokens", description="The max tokens", required=False) @discord.option(name="max_tokens", description="The max tokens", required=False)
@discord.option(name="temperature", description="The temperature", required=False) @discord.option(name="temperature", description="The temperature", required=False)
@discord.option(name="frequency_penalty", description="The frequency penalty", required=False) @discord.option(
@discord.option(name="presence_penalty", description="The presence penalty", required=False) name="frequency_penalty", description="The frequency penalty", required=False
)
@discord.option(
name="presence_penalty", description="The presence penalty", required=False
)
@discord.option(name="prompt_size", description="The prompt size", required=False) @discord.option(name="prompt_size", description="The prompt size", required=False)
async def advanced(self, ctx: discord.ApplicationContext, max_tokens: int = None, temperature: float = None, frequency_penalty: float = None, presence_penalty: float = None, prompt_size: int = None): async def advanced(
debug(f"The user {ctx.author} ran the advanced command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") self,
ctx: discord.ApplicationContext,
max_tokens: int = None,
temperature: float = None,
frequency_penalty: float = None,
presence_penalty: float = None,
prompt_size: int = None,
):
debug(
f"The user {ctx.author} ran the advanced 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,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.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
# check if the user has entered at least one argument # check if the user has entered at least one argument
if max_tokens is None and temperature is None and frequency_penalty is None and presence_penalty is None and prompt_size is None: if (
max_tokens is None
and temperature is None
and frequency_penalty is None
and presence_penalty is None
and prompt_size is None
):
await ctx.respond("You must enter at least one argument", ephemeral=True) await ctx.respond("You must enter at least one argument", ephemeral=True)
return return
# check if the user has entered valid arguments # check if the user has entered valid arguments
@@ -36,80 +59,158 @@ class Settings (discord.Cog) :
if temperature is not None and (temperature < 0.0 or temperature > 1.0): if temperature is not None and (temperature < 0.0 or temperature > 1.0):
await ctx.respond("Invalid temperature", ephemeral=True) await ctx.respond("Invalid temperature", ephemeral=True)
return return
if frequency_penalty is not None and (frequency_penalty < 0.0 or frequency_penalty > 2.0): if frequency_penalty is not None and (
frequency_penalty < 0.0 or frequency_penalty > 2.0
):
await ctx.respond("Invalid frequency penalty", ephemeral=True) await ctx.respond("Invalid frequency penalty", ephemeral=True)
return return
if presence_penalty is not None and (presence_penalty < 0.0 or presence_penalty > 2.0): if presence_penalty is not None and (
presence_penalty < 0.0 or presence_penalty > 2.0
):
await ctx.respond("Invalid presence penalty", ephemeral=True) await ctx.respond("Invalid presence penalty", ephemeral=True)
return return
if prompt_size is not None and (prompt_size < 1 or prompt_size > 10): if prompt_size is not None and (prompt_size < 1 or prompt_size > 10):
await ctx.respond("Invalid prompt size", ephemeral=True) await ctx.respond("Invalid prompt size", ephemeral=True)
return return
if max_tokens is None: if max_tokens is None:
if c.execute("SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] is not None and max_tokens is None: if (
max_tokens = c.execute("SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] curs_data.execute(
"SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
is not None
and max_tokens is None
):
max_tokens = curs_data.execute(
"SELECT max_tokens FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
else: else:
max_tokens = 64 max_tokens = 64
if temperature is None: if temperature is None:
if c.execute("SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] is not None and temperature is None: if (
temperature = c.execute("SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] curs_data.execute(
"SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
is not None
and temperature is None
):
temperature = curs_data.execute(
"SELECT temperature FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
else: else:
temperature = 0.9 temperature = 0.9
if frequency_penalty is None: if frequency_penalty is None:
if c.execute("SELECT frequency_penalty FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] is not None and frequency_penalty is None: if (
frequency_penalty = c.execute("SELECT frequency_penalty FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] curs_data.execute(
"SELECT frequency_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,),
).fetchone()[0]
is not None
and frequency_penalty is None
):
frequency_penalty = curs_data.execute(
"SELECT frequency_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,),
).fetchone()[0]
else: else:
frequency_penalty = 0.0 frequency_penalty = 0.0
if presence_penalty is None: if presence_penalty is None:
if c.execute("SELECT presence_penalty FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] is not None and presence_penalty is None: if (
presence_penalty = c.execute("SELECT presence_penalty FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] curs_data.execute(
"SELECT presence_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,),
).fetchone()[0]
is not None
and presence_penalty is None
):
presence_penalty = curs_data.execute(
"SELECT presence_penalty FROM data WHERE guild_id = ?",
(ctx.guild.id,),
).fetchone()[0]
else: else:
presence_penalty = 0.0 presence_penalty = 0.0
if prompt_size is None: if prompt_size is None:
if c.execute("SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] is not None and prompt_size is None: if (
prompt_size = c.execute("SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,)).fetchone()[0] curs_data.execute(
"SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
is not None
and prompt_size is None
):
prompt_size = curs_data.execute(
"SELECT prompt_size FROM data WHERE guild_id = ?", (ctx.guild.id,)
).fetchone()[0]
else: else:
prompt_size = 1 prompt_size = 1
# update the database # update the database
c.execute("UPDATE data SET max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?", (max_tokens, temperature, frequency_penalty, presence_penalty, prompt_size, ctx.guild.id)) curs_data.execute(
conn.commit() "UPDATE data SET max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?",
(
max_tokens,
temperature,
frequency_penalty,
presence_penalty,
prompt_size,
ctx.guild.id,
),
)
con_data.commit()
await ctx.respond("Advanced settings updated", ephemeral=True) await ctx.respond("Advanced settings updated", ephemeral=True)
# create a command called "delete" that only admins can use wich deletes the guild id, the api key, the channel id and the advanced settings from the database # create a command called "delete" that only admins can use wich deletes the guild id, the api key, the channel id and the advanced settings from the database
@discord.slash_command(name="default", description="Default settings") @discord.slash_command(name="default", description="Default settings")
##@discord.commands.permissions(administrator=True) ##@discord.commands.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}") 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
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.fetchone() is None: if curs_data.fetchone() is None:
await ctx.respond("This server is not setup, please run /setup", ephemeral=True) await ctx.respond(
"This server is not setup, please run /setup", ephemeral=True
)
return return
# 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
c.execute("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)) curs_data.execute(
conn.commit() "UPDATE data SET max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?",
await ctx.respond("The advanced settings have been set to their default values", ephemeral=True) (64, 0.9, 0.0, 0.0, 5, ctx.guild.id),
)
con_data.commit()
await ctx.respond(
"The advanced settings have been set to their default values",
ephemeral=True,
)
# create a command called "cancel" that deletes the last message sent by the bot in the response channel # create a command called "cancel" that deletes the last message sent by the bot in the response channel
# when a message is sent into a channel check if the guild is in the database and if the bot is enabled # when a message is sent into a channel check if the guild is in the database and if the bot is enabled
@discord.slash_command(name="info", description="Show the information stored about this server") @discord.slash_command(
name="info", description="Show the information stored about this server"
)
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}") 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:
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone() data = curs_data.fetchone()
except: data = None except:
data = None
if data[2] is None: if data[2] is None:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
return return
try: try:
c.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,))
model = c.fetchone()[1] model = curs_data.fetchone()[1]
except: model = None except:
if model is None: model = "davinci" model = None
embed = discord.Embed(title="Info", description="Here is the info page", color=0x00ff00) if model is None:
model = "davinci"
embed = discord.Embed(
title="Info", description="Here is the info page", color=0x00FF00
)
embed.add_field(name="guild_id", value=data[0], inline=False) embed.add_field(name="guild_id", value=data[0], inline=False)
embed.add_field(name="API Key", value="secret", inline=False) embed.add_field(name="API Key", value="secret", inline=False)
embed.add_field(name="Main channel ID", value=data[1], inline=False) embed.add_field(name="Main channel ID", value=data[1], inline=False)
@@ -128,10 +229,12 @@ 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}"
)
try: try:
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone() data = curs_data.fetchone()
api_key = data[2] api_key = data[2]
except: except:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
@@ -142,21 +245,35 @@ class Settings (discord.Cog) :
if prefix != "": if prefix != "":
await ctx.defer() await ctx.defer()
if await moderate(api_key=api_key, text=prefix): 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) await ctx.respond(
"This has been flagged as inappropriate by OpenAI, please choose another prefix",
ephemeral=True,
)
return return
await ctx.respond("Prefix changed !", ephemeral=True, delete_after=5) await ctx.respond("Prefix changed !", ephemeral=True, delete_after=5)
c.execute("UPDATE data SET prompt_prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id)) curs_data.execute(
conn.commit() "UPDATE data SET prompt_prefix = ? WHERE guild_id = ?",
(prefix, ctx.guild.id),
)
con_data.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(
@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) 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 = ""): 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
try: try:
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone() data = curs_data.fetchone()
api_key = data[2] api_key = data[2]
except: except:
await ctx.respond("This server is not setup", ephemeral=True) await ctx.respond("This server is not setup", ephemeral=True)
@@ -167,23 +284,35 @@ class Settings (discord.Cog) :
if pretend_to_be is not None or pretend_to_be != "": if pretend_to_be is not None or pretend_to_be != "":
await ctx.defer() await ctx.defer()
if await moderate(api_key=api_key, text=pretend_to_be): 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) await ctx.respond(
"This has been flagged as inappropriate by OpenAI, please choose another name",
ephemeral=True,
)
return return
if pretend_to_be == "": if pretend_to_be == "":
pretend_to_be = "" pretend_to_be = ""
c.execute("UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute(
conn.commit() "UPDATE data SET pretend_enabled = 0 WHERE guild_id = ?",
(ctx.guild.id,),
)
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)
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,)) curs_data.execute(
conn.commit() "UPDATE data SET pretend_enabled = 1 WHERE guild_id = ?",
(ctx.guild.id,),
)
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)
# 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)) curs_data.execute(
conn.commit() "UPDATE data SET pretend_to_be = ? WHERE guild_id = ?",
(pretend_to_be, ctx.guild.id),
)
con_data.commit()
# if the usename is longer than 32 characters, shorten it # if the usename is longer than 32 characters, shorten it
if len(pretend_to_be) > 31: if len(pretend_to_be) > 31:
pretend_to_be = pretend_to_be[:32] pretend_to_be = pretend_to_be[:32]
@@ -196,8 +325,8 @@ class Settings (discord.Cog) :
guild_id = ctx.guild.id guild_id = ctx.guild.id
# connect to the database # connect to the database
# update the tts value in the database # update the tts value in the database
c.execute("UPDATE data SET tts = 1 WHERE guild_id = ?", (guild_id,)) curs_data.execute("UPDATE data SET tts = 1 WHERE guild_id = ?", (guild_id,))
conn.commit() con_data.commit()
# send a message # send a message
await ctx.respond("TTS has been enabled", ephemeral=True) await ctx.respond("TTS has been enabled", ephemeral=True)
@@ -207,41 +336,73 @@ class Settings (discord.Cog) :
guild_id = ctx.guild.id guild_id = ctx.guild.id
# connect to the database # connect to the database
# update the tts value in the database # update the tts value in the database
c.execute("UPDATE data SET tts = 0 WHERE guild_id = ?", (guild_id,)) curs_data.execute("UPDATE data SET tts = 0 WHERE guild_id = ?", (guild_id,))
conn.commit() con_data.commit()
# send a message # send a message
await ctx.respond("TTS has been disabled", ephemeral=True) await ctx.respond("TTS has been disabled", ephemeral=True)
# autocompletition # autocompletition
async def autocomplete(ctx: discord.AutocompleteContext): async def autocomplete(ctx: discord.AutocompleteContext):
return [model for model in models if model.startswith(ctx.value)] return [model for model in models if model.startswith(ctx.value)]
@discord.slash_command(name="model", description="Change the model used by the bot") @discord.slash_command(name="model", description="Change the model used by the bot")
@discord.option(name="model", description="The model you want to use. Leave blank to use the davinci model", required=False, autocomplete=autocomplete) @discord.option(
name="model",
description="The model you want to use. Leave blank to use the davinci model",
required=False,
autocomplete=autocomplete,
)
@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:
c.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM model WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone()[1] data = curs_data.fetchone()[1]
except: except:
data = None data = None
if data is None: c.execute("INSERT INTO model VALUES (?, ?)", (ctx.guild.id, model)) if data is None:
else: c.execute("UPDATE model SET model_name = ? WHERE guild_id = ?", (model, ctx.guild.id)) curs_data.execute("INSERT INTO model VALUES (?, ?)", (ctx.guild.id, model))
conn.commit() else:
curs_data.execute(
"UPDATE model SET model_name = ? WHERE guild_id = ?",
(model, ctx.guild.id),
)
con_data.commit()
await ctx.respond("Model changed !", ephemeral=True) await ctx.respond("Model changed !", ephemeral=True)
async def images_recognition_autocomplete(ctx: discord.AutocompleteContext): async def images_recognition_autocomplete(ctx: discord.AutocompleteContext):
return [state for state in images_recognition if state.startswith(ctx.value)] return [state for state in images_recognition if state.startswith(ctx.value)]
@discord.slash_command(name="images", description="Enable or disable images recognition")
@discord.option(name="enable_disable", description="Enable or disable images recognition", autocomplete=images_recognition_autocomplete) @discord.slash_command(
name="images", description="Enable or disable images recognition"
)
@discord.option(
name="enable_disable",
description="Enable or disable images recognition",
autocomplete=images_recognition_autocomplete,
)
@default_permissions(administrator=True) @default_permissions(administrator=True)
async def images(self, ctx: discord.ApplicationContext, enable_disable: str): async def images(self, ctx: discord.ApplicationContext, enable_disable: str):
try: try:
c.execute("SELECT * FROM images WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM images WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone() data = curs_data.fetchone()
except: except:
data = None data = None
if enable_disable == "enable": enable_disable = 1 if enable_disable == "enable":
elif enable_disable == "disable": enable_disable = 0 enable_disable = 1
if data is None: c.execute("INSERT INTO images VALUES (?, ?, ?)", (ctx.guild.id, 0, enable_disable)) elif enable_disable == "disable":
else: c.execute("UPDATE images SET is_enabled = ? WHERE guild_id = ?", (enable_disable, ctx.guild.id)) enable_disable = 0
conn.commit() if data is None:
await ctx.respond("Images recognition has been " + ("enabled" if enable_disable == 1 else "disabled"), ephemeral=True) curs_data.execute(
"INSERT INTO images VALUES (?, ?, ?)", (ctx.guild.id, 0, enable_disable)
)
else:
curs_data.execute(
"UPDATE images SET is_enabled = ? WHERE guild_id = ?",
(enable_disable, ctx.guild.id),
)
con_data.commit()
await ctx.respond(
"Images recognition has been "
+ ("enabled" if enable_disable == 1 else "disabled"),
ephemeral=True,
)

View File

@@ -1,5 +1,6 @@
import discord import discord
from config import debug, conn, c, connp, cp from config import debug, con_data, curs_data, con_premium, curs_premium
class Setup(discord.Cog): class Setup(discord.Cog):
def __init__(self, bot: discord.Bot): def __init__(self, bot: discord.Bot):
@@ -9,44 +10,84 @@ class Setup (discord.Cog) :
@discord.slash_command(name="setup", description="Setup the bot") @discord.slash_command(name="setup", description="Setup the bot")
@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)
async def setup(self, ctx: discord.ApplicationContext, channel: discord.TextChannel, api_key: str): async def setup(
self,
ctx: discord.ApplicationContext,
channel: discord.TextChannel,
api_key: str,
):
# check if the api key is valid # check if the api key is valid
debug(f"The user {ctx.author} ran the setup command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}") debug(
f"The user {ctx.author} ran the setup command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
)
# check if the channel is valid # check if the channel is valid
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
# check if the guild is already in the database bi checking if there is a key for the guild # check if the guild is already in the database bi checking if there is a key for the guild
try: try:
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
data = c.fetchone() data = curs_data.fetchone()
if data[3] == None: data = None if data[3] == None:
data = None
except: except:
data = None data = None
if data != None: if data != None:
c.execute("UPDATE data SET channel_id = ?, api_key = ? WHERE guild_id = ?", (channel.id, api_key, ctx.guild.id)) curs_data.execute(
"UPDATE data SET channel_id = ?, api_key = ? WHERE guild_id = ?",
(channel.id, api_key, ctx.guild.id),
)
# c.execute("UPDATE data SET is_active = ?, max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?", (False, 64, 0.9, 0.0, 0.0, 5, ctx.guild.id)) # c.execute("UPDATE data SET is_active = ?, max_tokens = ?, temperature = ?, frequency_penalty = ?, presence_penalty = ?, prompt_size = ? WHERE guild_id = ?", (False, 64, 0.9, 0.0, 0.0, 5, ctx.guild.id))
conn.commit() con_data.commit()
await ctx.respond("The channel id and the api key have been updated", ephemeral=True) await ctx.respond(
"The channel id and the api key have been updated", ephemeral=True
)
else: else:
# in this case, the guild is not in the database, so we add it # in this case, the guild is not in the database, so we add it
c.execute("INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (ctx.guild.id, channel.id, api_key, False, 64, 0.9, 0.0, 0.0, 0, 5, "", False, "", False)) curs_data.execute(
conn.commit() "INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
await ctx.respond("The channel id and the api key have been added", ephemeral=True) (
ctx.guild.id,
channel.id,
api_key,
False,
64,
0.9,
0.0,
0.0,
0,
5,
"",
False,
"",
False,
),
)
con_data.commit()
await ctx.respond(
"The channel id and the api key have been added", ephemeral=True
)
@discord.slash_command(name="delete", description="Delete the information about this server") @discord.slash_command(
name="delete", description="Delete the information about this server"
)
##@discord.commands.permissions(administrator=True) ##@discord.commands.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}") 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
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.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
c.execute("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)) curs_data.execute(
conn.commit() "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),
)
con_data.commit()
await ctx.respond("Deleted", ephemeral=True) await ctx.respond("Deleted", ephemeral=True)
# create a command called "enable" that only admins can use # create a command called "enable" that only admins can use
@@ -55,42 +96,64 @@ class Setup (discord.Cog) :
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 # if the guild is eqal to 1014156298226515970, the guild is banned
if ctx.guild.id == 1014156298226515970: if ctx.guild.id == 1014156298226515970:
await ctx.respond("This server is banned for bad and nsfw use.", ephemeral=True) await ctx.respond(
"This server is banned for bad and nsfw use.", ephemeral=True
)
return return
# check if the guild is in the database # 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}") debug(
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) f"The user {ctx.author} ran the enable command in the channel {ctx.channel} of the guild {ctx.guild}, named {ctx.guild.name}"
if c.fetchone() is None: )
curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
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
c.execute("UPDATE data SET is_active = ? WHERE guild_id = ?", (True, ctx.guild.id)) curs_data.execute(
conn.commit() "UPDATE data SET is_active = ? WHERE guild_id = ?", (True, ctx.guild.id)
)
con_data.commit()
await ctx.respond("Enabled", ephemeral=True) await ctx.respond("Enabled", ephemeral=True)
# create a command called "disable" that only admins can use # create a command called "disable" that only admins can use
@discord.slash_command(name="disable", description="Disable the bot") @discord.slash_command(name="disable", description="Disable the bot")
##@discord.commands.permissions(administrator=True) ##@discord.commands.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}") 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
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.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
c.execute("UPDATE data SET is_active = ? WHERE guild_id = ?", (False, ctx.guild.id)) curs_data.execute(
conn.commit() "UPDATE data SET is_active = ? WHERE guild_id = ?", (False, ctx.guild.id)
)
con_data.commit()
await ctx.respond("Disabled", ephemeral=True) await ctx.respond("Disabled", ephemeral=True)
# create a command calles "add channel" that can only be used in premium servers # create a command calles "add channel" that can only be used in premium servers
@discord.slash_command(name="add_channel", description="Add a channel to the list of channels. Premium only.") @discord.slash_command(
@discord.option(name="channel", description="The channel to add", type=discord.TextChannel, required=False) name="add_channel",
async def add_channel(self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None): description="Add a channel to the list of channels. Premium only.",
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}") )
@discord.option(
name="channel",
description="The channel to add",
type=discord.TextChannel,
required=False,
)
async def add_channel(
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
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.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
# check if the guild is premium # check if the guild is premium
@@ -105,16 +168,21 @@ class Setup (discord.Cog) :
if channel is None: if channel is None:
channel = ctx.channel channel = ctx.channel
# check if the channel is already in the list # check if the channel is already in the list
c.execute("SELECT channel_id FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT channel_id FROM data WHERE guild_id = ?", (ctx.guild.id,))
if str(channel.id) == c.fetchone()[0]: if str(channel.id) == curs_data.fetchone()[0]:
await ctx.respond("This channel is already set as the main channel", ephemeral=True) await ctx.respond(
"This channel is already set as the main channel", ephemeral=True
)
return return
cp.execute("SELECT * FROM channels WHERE guild_id = ?", (ctx.guild.id,)) cp.execute("SELECT * FROM channels WHERE guild_id = ?", (ctx.guild.id,))
guild_channels = cp.fetchone() guild_channels = cp.fetchone()
if guild_channels is None: if guild_channels is None:
# if the channel is not in the list, add it # if the channel is not in the list, add it
cp.execute("INSERT INTO channels VALUES (?, ?, ?, ?, ?, ?)", (ctx.guild.id, channel.id, None, None, None, None)) cp.execute(
connp.commit() "INSERT INTO channels VALUES (?, ?, ?, ?, ?, ?)",
(ctx.guild.id, channel.id, None, None, None, None),
)
con_premium.commit()
await ctx.respond(f"Added channel **{channel.name}**", ephemeral=True) await ctx.respond(f"Added channel **{channel.name}**", ephemeral=True)
return return
channels = guild_channels[1:] channels = guild_channels[1:]
@@ -123,20 +191,35 @@ class Setup (discord.Cog) :
return return
for i in range(5): for i in range(5):
if channels[i] == None: if channels[i] == None:
cp.execute(f"UPDATE channels SET channel{i} = ? WHERE guild_id = ?", (channel.id, ctx.guild.id)) cp.execute(
connp.commit() f"UPDATE channels SET channel{i} = ? WHERE guild_id = ?",
(channel.id, ctx.guild.id),
)
con_premium.commit()
await ctx.respond(f"Added channel **{channel.name}**", ephemeral=True) await ctx.respond(f"Added channel **{channel.name}**", ephemeral=True)
return return
await ctx.respond("You can only add 5 channels", ephemeral=True) await ctx.respond("You can only add 5 channels", ephemeral=True)
# create a command called "remove channel" that can only be used in premium servers # create a command called "remove channel" that can only be used in premium servers
@discord.slash_command(name="remove_channel", description="Remove a channel from the list of channels. Premium only.") @discord.slash_command(
@discord.option(name="channel", description="The channel to remove", type=discord.TextChannel, required=False) name="remove_channel",
async def remove_channel(self, ctx: discord.ApplicationContext, channel: discord.TextChannel = None): description="Remove a channel from the list of channels. Premium only.",
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}") )
@discord.option(
name="channel",
description="The channel to remove",
type=discord.TextChannel,
required=False,
)
async def remove_channel(
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
c.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT * FROM data WHERE guild_id = ?", (ctx.guild.id,))
if c.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
# check if the guild is premium # check if the guild is premium
@@ -153,21 +236,31 @@ class Setup (discord.Cog) :
# check if the channel is in the list # check if the channel is in the list
cp.execute("SELECT * FROM channels WHERE guild_id = ?", (ctx.guild.id,)) cp.execute("SELECT * FROM channels WHERE guild_id = ?", (ctx.guild.id,))
guild_channels = cp.fetchone() guild_channels = cp.fetchone()
c.execute("SELECT channel_id FROM data WHERE guild_id = ?", (ctx.guild.id,)) curs_data.execute("SELECT channel_id FROM data WHERE guild_id = ?", (ctx.guild.id,))
if str(channel.id) == c.fetchone()[0]: if str(channel.id) == curs_data.fetchone()[0]:
await ctx.respond("This channel is set as the main channel and therefore cannot be removed. Type /setup to change the main channel.", ephemeral=True) await ctx.respond(
"This channel is set as the main channel and therefore cannot be removed. Type /setup to change the main channel.",
ephemeral=True,
)
return return
if guild_channels is None: if guild_channels is None:
await ctx.respond("This channel was not added. Nothing changed", ephemeral=True) await ctx.respond(
"This channel was not added. Nothing changed", ephemeral=True
)
return return
channels = guild_channels[1:] channels = guild_channels[1:]
if str(channel.id) not in channels: if str(channel.id) not in channels:
await ctx.respond("This channel was not added. Nothing changed", ephemeral=True) await ctx.respond(
"This channel was not added. Nothing changed", ephemeral=True
)
return return
# remove the channel from the list # remove the channel from the list
for i in range(5): for i in range(5):
if channels[i] == str(channel.id): if channels[i] == str(channel.id):
cp.execute(f"UPDATE channels SET channel{i} = ? WHERE guild_id = ?", (None, ctx.guild.id)) cp.execute(
connp.commit() f"UPDATE channels SET channel{i} = ? WHERE guild_id = ?",
(None, ctx.guild.id),
)
con_premium.commit()
await ctx.respond(f"Removed channel **{channel.name}**", ephemeral=True) await ctx.respond(f"Removed channel **{channel.name}**", ephemeral=True)
return return

View File

@@ -3,6 +3,7 @@ import sqlite3
from dotenv import load_dotenv from dotenv import load_dotenv
import os import os
import openai 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")
@@ -10,17 +11,23 @@ webhook_url = os.getenv("WEBHOOK_URL")
max_uses: int = 400 max_uses: int = 400
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./../database/google-vision/botator.json" os.environ[
"GOOGLE_APPLICATION_CREDENTIALS"
] = "./../database/google-vision/botator.json"
def debug(message): def debug(message):
# if the os is windows, we logging.info(message), if # if the os is windows, we logging.info(message), if
if os.name == "nt": if os.name == "nt":
logging.info(message) logging.info(message)
conn = sqlite3.connect('../database/data.db')
c = conn.cursor() # connect to the database
connp = sqlite3.connect('../database/premium.db') con_data = sqlite3.connect("../database/data.db")
cp = connp.cursor() curs_data = con_data.cursor()
con_premium = sqlite3.connect("../database/premium.db")
curs_premium = con_premium.cursor()
async def moderate(api_key, text): async def moderate(api_key, text):
openai.api_key = api_key openai.api_key = api_key
@@ -29,31 +36,54 @@ async def moderate(api_key, text):
) )
return response["results"][0]["flagged"] 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)''')
curs_data.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
# we delete the moderation table and create a new one # we delete the moderation table and create a new one
c.execute('''CREATE TABLE IF NOT EXISTS moderation (guild_id text, logs_channel_id text, is_enabled boolean, mod_role_id text, toxicity real, severe_toxicity real, identity_attack real, insult real, profanity real, threat real, sexually_explicit real, flirtation real, obscene real, spam real)''') curs_data.execute(
c.execute("PRAGMA table_info(moderation)") """CREATE TABLE IF NOT EXISTS moderation (guild_id text, logs_channel_id text, is_enabled boolean, mod_role_id text, toxicity real, severe_toxicity real, identity_attack real, insult real, profanity real, threat real, sexually_explicit real, flirtation real, obscene real, spam real)"""
result = c.fetchall() )
# This code returns the number of columns in the table "moderation" in the database "data.db".
curs_data.execute("PRAGMA table_info(moderation)")
result = curs_data.fetchall()
actual_columns = len(result) actual_columns = len(result)
if actual_columns != expected_columns: if actual_columns != expected_columns:
# we add the new columns # we add the new columns
c.execute("ALTER TABLE moderation ADD COLUMN toxicity real") curs_data.execute("ALTER TABLE moderation ADD COLUMN toxicity real")
c.execute("ALTER TABLE moderation ADD COLUMN severe_toxicity real") curs_data.execute("ALTER TABLE moderation ADD COLUMN severe_toxicity real")
c.execute("ALTER TABLE moderation ADD COLUMN identity_attack real") curs_data.execute("ALTER TABLE moderation ADD COLUMN identity_attack real")
c.execute("ALTER TABLE moderation ADD COLUMN insult real") curs_data.execute("ALTER TABLE moderation ADD COLUMN insult real")
c.execute("ALTER TABLE moderation ADD COLUMN profanity real") curs_data.execute("ALTER TABLE moderation ADD COLUMN profanity real")
c.execute("ALTER TABLE moderation ADD COLUMN threat real") curs_data.execute("ALTER TABLE moderation ADD COLUMN threat real")
c.execute("ALTER TABLE moderation ADD COLUMN sexually_explicit real") curs_data.execute("ALTER TABLE moderation ADD COLUMN sexually_explicit real")
c.execute("ALTER TABLE moderation ADD COLUMN flirtation real") curs_data.execute("ALTER TABLE moderation ADD COLUMN flirtation real")
c.execute("ALTER TABLE moderation ADD COLUMN obscene real") curs_data.execute("ALTER TABLE moderation ADD COLUMN obscene real")
c.execute("ALTER TABLE moderation ADD COLUMN spam real") curs_data.execute("ALTER TABLE moderation ADD COLUMN spam real")
else: else:
print("Table already has the correct number of columns") print("Table already has the correct number of columns")
pass
c.execute('''CREATE TABLE IF NOT EXISTS model (guild_id text, model_name text)''') # This code creates the model table if it does not exist
c.execute('''CREATE TABLE IF NOT EXISTS images (guild_id text, usage_count integer, is_enabled boolean)''') curs_data.execute(
cp.execute('''CREATE TABLE IF NOT EXISTS data (user_id text, guild_id text, premium boolean)''') """CREATE TABLE IF NOT EXISTS model (guild_id text, model_name text)"""
cp.execute('''CREATE TABLE IF NOT EXISTS channels (guild_id text, channel0 text, channel1 text, channel2 text, channel3 text, channel4 text)''') )
# This code creates the images table if it does not exist
curs_data.execute(
"""CREATE TABLE IF NOT EXISTS images (guild_id text, usage_count integer, is_enabled boolean)"""
)
# This code creates the data table if it does not exist
curs_premium.execute(
"""CREATE TABLE IF NOT EXISTS data (user_id text, guild_id text, premium boolean)"""
)
# This code creates the channels table if it does not exist
curs_premium.execute(
"""CREATE TABLE IF NOT EXISTS channels (guild_id text, channel0 text, channel1 text, channel2 text, channel3 text, channel4 text)"""
)

View File

@@ -1,11 +1,11 @@
import asyncio import asyncio
from config import c, max_uses, cp, conn, debug, moderate from config import curs_data, max_uses, curs_premium, con_data, debug, moderate
import vision_processing import vision_processing
import re import re
import discord import discord
import datetime import datetime
import openai import openai
import emoji # pip install emoji import emoji
import os import os
async def replace_mentions(content, bot): async def replace_mentions(content, bot):
@@ -33,7 +33,9 @@ async def extract_emoji(string):
debug(f"Found emoji: {match}") debug(f"Found emoji: {match}")
found_emojis.append(match) found_emojis.append(match)
debug(f"Sting before: {string}") debug(f"Sting before: {string}")
string = string.replace(f"+{match}", "") # we remove the emoji from the string string = string.replace(
f"+{match}", ""
) # we remove the emoji from the string
debug(f"Sting after: {string}") debug(f"Sting after: {string}")
for match in custom_emoji_matches: for match in custom_emoji_matches:
debug(f"Match: {match}") debug(f"Match: {match}")
@@ -42,128 +44,338 @@ async def extract_emoji(string):
string = string.replace(f"+<:{match[0]}:{match[1]}>", "") string = string.replace(f"+<:{match[0]}:{match[1]}>", "")
return found_emojis, string return found_emojis, string
async def chat_process(self, message):
if message.author.bot: def get_guild_data(message):
return """This function gets the data of the guild where the message was sent.
try: c.execute("SELECT * FROM data WHERE guild_id = ?", (message.guild.id,))
Args:
message (str): Data of the message that was sent
Returns:
dict: A dictionary with the data of the guild
"""
guild_data = {}
try:
curs_premium.execute(
"SELECT * FROM data WHERE guild_id = ?", (message.guild.id,))
except: except:
return pass
data = c.fetchone()
channel_id = data[1]
api_key = data[2]
is_active = data[3]
max_tokens = data[4]
temperature = data[5]
frequency_penalty = data[6]
presence_penalty = data[7]
uses_count_today = data[8]
prompt_size = data[9]
prompt_prefix = data[10]
tts = data[11]
pretend_to_be = data[12]
pretend_enabled = data[13]
images_limit_reached = False
try: cp.execute("SELECT * FROM data WHERE guild_id = ?", (message.guild.id,))
except: pass
try:
c.execute("SELECT * FROM model WHERE guild_id = ?", (message.guild.id,)) # get the model in the database
model = c.fetchone()[1]
except: model = "chatGPT"
try: premium = cp.fetchone()[2] # get the premium status of the guild
except: premium = 0 # if the guild is not in the database, it's not premium
try: try:
c.execute("SELECT * FROM images WHERE guild_id = ?", (message.guild.id,)) # get the images setting in the database curs_data.execute(
data = c.fetchone() "SELECT * FROM model WHERE guild_id = ?", (message.guild.id,)
) # get the model in the database
data = curs_data.fetchone()
model = model[1]
except: except:
data = None model = "gpt-3.5-turbo"
if data is None: data = [message.guild.id, 0, 0]
images_usage = data[1]
images_enabled = data[2]
channels = []
if message.guild.id == 1050769643180146749: images_usage = 0 # if the guild is the support server, we set the images usage to 0, so the bot can be used as much as possible
try: try:
cp.execute("SELECT * FROM channels WHERE guild_id = ?", (message.guild.id,)) # [2] # get the premium status of the guild
data = cp.fetchone() data = curs_premium.fetchone()
if premium: premium = data[2]
#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 except:
for i in range(1, 6): premium = 0 # if the guild is not in the database, it's not premium
#we use the i variable to get the channel id
try: channels.append(str(data[i]))
except: pass
except: channels = []
if api_key is None: return # if the api key is not set, return try:
curs_data.execute(
"SELECT * FROM images WHERE guild_id = ?", (message.guild.id,)
) # get the images setting in the database
images = curs_data.fetchone()
except:
images = None
try : original_message = await message.channel.fetch_message(message.reference.message_id) # check if someone replied to the bot guild_data["model"] = "gpt-3.5-turbo" if model == "chatGPT" else model
except : original_message = None # if not, nobody replied to the bot guild_data["premium"] = premium
guild_data["images"] = images
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 guild_data["images_limit_reached"] = False
return guild_data
async def need_ignore_message(bot, data_dict, message, guild_data, original_message, channels):
## ---- Message ignore conditions ---- ##
if data_dict["api_key"] is None:
return True # if the api key is not set, return
if (
# if the message is not in a premium channel and # if the message is not in a premium channel and
not (str(message.channel.id) in channels
# if the message doesn't mention the bot and # if the message doesn't mention the bot and
# if the message is not a reply to the bot and and (message.content.find("<@" + str(bot.user.id) + ">") != -1
or original_message)) # if the message is not a reply to the bot and
# if the message is not in the default channel # if the message is not in the default channel
# return and str(message.channel.id) != str(data_dict["channel_id"])
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 ):
return True
# 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 and message.guild.id != 1050769643180146749:
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 # 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 # send a message and return
elif uses_count_today >= max_uses*5 and premium == 1: return elif data_dict["uses_count_today"] >= max_uses * 5 and guild_data["premium"] == 1:
return True
# if the bot is not active in this guild we return # if the bot is not active in this guild we return
if is_active == 0: return if data_dict["is_active"] == 0:
return True
# if the message starts with - or // it's a comment and we 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("//"):
try: await message.channel.trigger_typing() return True
except: pass
# 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 (
data_dict["uses_count_today"] >= max_uses
and guild_data["premium"] == 0
and message.guild.id != 1050769643180146749
):
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."
)
return True
return False
async def get_data_dict(message):
try:
curs_data.execute(
"SELECT * FROM data WHERE guild_id = ?", (message.guild.id,))
data = curs_data.fetchone()
# Create a dict with the data
data_dict = {
"channel_id": data[1],
"api_key": data[2],
"is_active": data[3],
"max_tokens": data[4],
"temperature": data[5],
"frequency_penalty": data[6],
"presence_penalty": data[7],
"uses_count_today": data[8],
"prompt_size": data[9],
"prompt_prefix": data[10],
"tts": bool(data[11]),
"pretend_to_be": data[12],
"pretend_enabled": data[13],
}
return data_dict
except Exception as e:
# Send an error message
await message.channel.send(
"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__()
+ "```", delete_after=60
)
async def chat_process(self, message):
"""This function processes the message and sends the prompt to the API
Args:
message (str): Data of the message that was sent
"""
if message.author.bot:
return
guild_data = get_guild_data(message)
data_dict = await get_data_dict(message)
try:
original_message = await message.channel.fetch_message(
message.reference.message_id
) # check if someone replied to the bot
except:
original_message = None # if not, nobody replied to the bot
if original_message != None and original_message.author.id != self.bot.user.id:
# if the message someone replied to is not from the bot, set original_message to None
original_message = None
try:
# get the images setting in the database
curs_data.execute(
"SELECT * FROM images WHERE guild_id = ?", (message.guild.id,))
images_data = curs_data.fetchone()
except:
images_data = None
## ---- Message processing ---- ##
print(message)
if not images_data:
images_data = [message.guild.id, 0, 0]
data_dict["images_usage"] = 0 if message.guild.id == 1050769643180146749 else images_data[1]
data_dict["images_enabled"] = images_data[2]
channels = []
try:
curs_premium.execute(
"SELECT * FROM channels WHERE guild_id = ?", (message.guild.id,))
images_data = curs_premium.fetchone()
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 i in range(1, 6):
# we use the i variable to get the channel id
try:
channels.append(str(images_data[i]))
except:
pass
except:
debug("No premium channels found for this guild")
if (await need_ignore_message(self.bot, data_dict, message, guild_data, original_message, channels)):
return
print("prompt handler")
try:
await message.channel.trigger_typing()
# if the message is not in the owner's guild we update the usage count # if the message is not in the owner's guild we update the usage count
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,)) curs_data.execute(
conn.commit() "UPDATE data SET uses_count_today = uses_count_today + 1 WHERE guild_id = ?",
(message.guild.id,),
)
con_data.commit()
# if the message is not a reply # 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=data_dict["prompt_size"]
).flatten()
messages.reverse() messages.reverse()
# if the message is a reply, we need to handle the message history differently # 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=data_dict["prompt_size"], before=original_message
).flatten()
messages.reverse() messages.reverse()
messages.append(original_message) messages.append(original_message)
messages.append(message) messages.append(message)
except Exception as e:
debug("Error while getting message history", e)
print(e)
# if the pretend to be feature is enabled, we add the pretend to be text to the prompt # if the pretend to be feature is enabled, we add the pretend to be text to the prompt
if pretend_enabled : pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}" pretend_to_be = f"In this conversation, the assistant pretends to be {pretend_to_be}" if data_dict[
else: pretend_to_be = "" # if the pretend to be feature is disabled, we don't add anything to the prompt "pretend_enabled"] else ""
if prompt_prefix == None: prompt_prefix = "" # if the prompt prefix is not set, we set it to an empty string prompt_prefix = "" if data_dict["prompt_prefix"] == None else data_dict["prompt_prefix"]
# open the prompt file for the selected model with utf-8 encoding for emojis # open the prompt file for the selected model with utf-8 encoding for emojis
with open(f"./prompts/{model}.txt", "r", encoding="utf-8") as f: with open(f"./prompts/{guild_data['model']}.txt", "r", encoding="utf-8") as f:
prompt = f.read() prompt = f.read()
f.close()
# replace the variables in the prompt with the actual values # replace the variables in the prompt with the actual values
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 = (
############################## chatGPT and gpt-4 handling ############################## prompt.replace("[prompt-prefix]", prompt_prefix)
if model == "chatGPT" or model == "gpt-4": # if the model is chatGPT, we handle it in a certain way .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)
)
f.close()
prompt_handlers = {
"gpt-3.5-turbo": gpt_prompt,
"gpt-4": gpt_prompt,
"davinci": davinci_prompt,
}
response = await prompt_handlers[guild_data["model"]](
self.bot, messages, message, data_dict, prompt, guild_data
)
if response != "":
emojis, string = await extract_emoji(response)
debug(f"Emojis: {emojis}")
if len(string) < 1996:
await message.channel.send(string, tts=data_dict["tts"])
else:
# we send in an embed if the message is too long
embed = discord.Embed(
title="Botator response",
description=string,
color=discord.Color.brand_green(),
)
await message.channel.send(embed=embed, tts=data_dict["tts"])
for emoji in emojis:
# if the emoji is longer than 1 character, it's a custom emoji
try:
if len(emoji) > 1:
# if the emoji is a custom emoji, we need to fetch it
# the emoji is in the format id
debug(f"Emoji: {emoji}")
emoji = await message.guild.fetch_emoji(int(emoji))
await message.add_reaction(emoji)
else:
debug(f"Emoji: {emoji}")
await message.add_reaction(emoji)
except:
pass
else:
await message.channel.send(
"The AI is not sure what to say (the response was empty)"
)
async def check_moderate(api_key, message, msg):
if await moderate(api_key=api_key, text=msg.content):
embed = discord.Embed(
title="Message flagged as inappropriate",
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(),
)
await message.channel.send(
f"{msg.author.mention}", embed=embed, delete_after=10
)
message.delete()
return True
return False
async def check_easter_egg(message, msgs):
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",
}
)
if message.content.lower().find("hello there") != -1:
msgs.append(
{
"role": "user",
"content": 'SYSTEM INFORMATION: Hello there detected. Botator will now say "General Kenobi!" in reference to star wars',
"name": "system",
}
)
await asyncio.sleep(1)
await message.channel.send(
"https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif"
)
await message.channel.trigger_typing()
return msgs
async def gpt_prompt(bot, messages, message, data_dict, prompt, guild_data):
msgs = [] # create the msgs list msgs = [] # create the msgs list
msgs.append({"name":"System","role": "user", "content": prompt}) # add the prompt to the msgs list msgs.append(
{"name": "System", "role": "user", "content": prompt}
) # add the prompt to the msgs list
name = "" # create the name variable name = "" # create the name variable
for msg in messages: # for each message in the messages list for msg in messages: # for each message in the messages list
content = msg.content # get the content of the message content = msg.content # get the content of the message
content = await replace_mentions(content, self.bot) # replace the mentions in the message content = await replace_mentions(
content, bot
) # 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 the message is flagged as inappropriate by the OpenAI API, we delete it, send a message and ignore it
if await moderate(api_key=api_key, text=content): if await check_moderate(data_dict["api_key"], message, msg):
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()) continue # ignore the message
await message.channel.send(f"{msg.author.mention}", embed=embed, delete_after=10) content = await replace_mentions(content, bot)
message.delete() prompt += f"{msg.author.name}: {content}\n"
else: # if the message is not flagged as inappropriate if msg.author.id == bot.user.id:
if msg.author.id == self.bot.user.id:
role = "assistant" role = "assistant"
name = "assistant" name = "assistant"
else: else:
@@ -177,133 +389,152 @@ async def chat_process(self, message):
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 there is an attachment, we add it to the message
if len(msg.attachments) > 0 and role == "user" and images_enabled == 1: if (
len(msg.attachments) > 0
and role == "user"
and data_dict["images_enabled"] == 1
):
for attachment in msg.attachments: for attachment in msg.attachments:
if images_usage >= 6 and premium == 0: images_limit_reached = True path = f"./../database/google-vision/results/{attachment.id}.txt"
elif images_usage >= 30 and premium == 1: images_limit_reached = True if images_usage >= 6 and guild_data["premium"] == 0:
if attachment.url.endswith((".png", ".jpg", ".jpeg", ".gif")) and images_limit_reached == False and os.path.exists(f"./../database/google-vision/results/{attachment.id}.txt") == False: guild_data["images_limit_reached"] = True
elif images_usage >= 30 and guild_data["premium"] == 1:
guild_data["images_limit_reached"] = True
if (
attachment.url.endswith((".png", ".jpg", ".jpeg", ".gif"))
and not guild_data["images_limit_reached"]
and not os.path.exists(path)
):
images_usage += 1 images_usage += 1
analysis = await vision_processing.process(attachment) analysis = await vision_processing.process(attachment)
if analysis != None: if analysis != None:
content = f"{content} \n\n {analysis}" content = f"{content} \n\n {analysis}"
msgs.append({"role": role, "content": f"{content}", "name": name}) msgs.append(
{
"role": role,
"content": f"{content}",
"name": name,
}
)
# if the attachment is still an image, we can check if there's a file called ./../database/google-vision/results/{attachment.id}.txt, if there is, we add the content of the file to the message # if the attachment is still an image, we can check if there's a file called ./../database/google-vision/results/{attachment.id}.txt, if there is, we add the content of the file to the message
elif attachment.url.endswith((".png", ".jpg", ".jpeg", ".gif")) and os.path.exists(f"./../database/google-vision/results/{attachment.id}.txt") == True: elif attachment.url.endswith(
(".png", ".jpg", ".jpeg", ".gif")
) and os.path.exists(path):
try: try:
with open(f"./../database/google-vision/results/{attachment.id}.txt", "r") as f: with open(
path,
"r",
) as f:
content = f"{content} \n\n {f.read()}" content = f"{content} \n\n {f.read()}"
f.close()
msgs.append({"role": role, "content": f"{content}", "name": name})
except: except:
msgs.append({"role": role, "content": f"{content}", "name": name}) debug(f"Error while reading {path}")
finally:
msgs.append(
{
"role": role,
"content": f"{content}",
"name": name,
}
)
f.close()
else:
msgs.append(
{"role": role, "content": f"{content}", "name": name}
)
curs_data.execute(
"UPDATE images SET usage_count = ? WHERE guild_id = ?",
(images_usage, message.guild.id),
)
else: else:
msgs.append({"role": role, "content": f"{content}", "name": name}) msgs.append({"role": role, "content": f"{content}", "name": name})
c.execute("UPDATE images SET usage_count = ? WHERE guild_id = ?", (images_usage, message.guild.id))
else: # We check for the eastereggs :)
msgs.append({"role": role, "content": f"{content}", "name": name}) msgs = await check_easter_egg(message, msgs)
# 2 easter eggs
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"})
if message.content.lower().find("hello there") != -1:
msgs.append({"role": "user", "content": "SYSTEM INFORMATION: Hello there detected. Botator will now say \"General Kenobi!\" in reference to star wars", "name": "system"})
await asyncio.sleep(1)
await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif")
await message.channel.trigger_typing()
if model == "chatGPT": model = "gpt-3.5-turbo" # if the model is chatGPT, we set the model to gpt-3.5-turbo
response = "" response = ""
should_break = True should_break = True
for x in range(10): for x in range(10):
try: try:
openai.api_key = api_key openai.api_key = data_dict["api_key"]
response = await openai.ChatCompletion.acreate( response = await openai.ChatCompletion.acreate(
model=model, model=guild_data["model"],
temperature=2, temperature=2,
top_p=0.9, top_p=0.9,
frequency_penalty=0, frequency_penalty=0,
presence_penalty=0, presence_penalty=0,
messages=msgs, messages=msgs,
max_tokens=512, # max tokens is 4000, that's a lot of text! (the max tokens is 2048 for the davinci model) # max tokens is 4000, that's a lot of text! (the max tokens is 2048 for the davinci model)
max_tokens=512,
) )
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 redone arrow # react with a redone arrow
await message.add_reaction("🔃") await message.add_reaction("🔃")
else: should_break = True else:
should_break = True
except Exception as e: except Exception as e:
should_break = False should_break = False
await message.channel.send(f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=5) await message.channel.send(
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)
if response == None: should_break = False if response == None:
if should_break: break should_break = False
if should_break:
break
await asyncio.sleep(15) await asyncio.sleep(15)
await message.channel.trigger_typing() await message.channel.trigger_typing()
response = response.choices[0].message.content response = response.choices[0].message.content
if images_limit_reached == True:
await message.channel.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```", delete_after=10) if guild_data["images_limit_reached"]:
#-----------------------------------------Davinci------------------------------------------------------------------------------------------ await message.channel.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```",
delete_after=10,
)
return response
elif model == "davinci": # if the model is davinci or gpt-4, we handle it in a certain way async def davinci_prompt(self, messages, message, data_dict, prompt, guild_data):
for msg in messages: for msg in messages:
content = msg.content if not await self.check_moderate(data_dict["api_key"], message, msg):
if await moderate(api_key=api_key, text=msg.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())
await message.channel.send(f"{msg.author.mention}", embed=embed, delete_after=10)
message.delete()
else:
content = await replace_mentions(content, self.bot) content = await replace_mentions(content, self.bot)
prompt += f"{msg.author.name}: {content}\n" prompt += f"{msg.author.name}: {content}\n"
if message.content.lower().find("undude") != -1: prompt.append(await check_easter_egg(message, prompt))
prompt += "System: Undude detected. Botator is now mad. He will start talking in capital letters.\n"
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"
await asyncio.sleep(1)
await message.channel.send("https://media.tenor.com/FxIRfdV3unEAAAAd/star-wars-general-grievous.gif")
await message.channel.trigger_typing()
prompt = prompt + f"\n{self.bot.user.name}:" prompt = prompt + f"\n{self.bot.user.name}:"
response = "" response = ""
for _ in range(10): for _ in range(10):
try: try:
openai.api_key = api_key openai.api_key = data_dict["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),
max_tokens=int(max_tokens), max_tokens=int(data_dict["max_tokens"]),
top_p=1, top_p=1,
temperature=float(temperature), temperature=float(data_dict["temperature"]),
frequency_penalty=float(frequency_penalty), frequency_penalty=float(data_dict["frequency_penalty"]),
presence_penalty=float(presence_penalty), presence_penalty=float(data_dict["presence_penalty"]),
stop=[" Human:", " AI:", "AI:", "<|endofprompt|>",] stop=[
" Human:",
" AI:",
"AI:",
"<|endofprompt|>",
],
) )
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(f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=10) await message.channel.send(
f"```diff\n-Error: OpenAI API ERROR.\n\n{e}```", delete_after=10
)
return return
if response != None: break if response != None:
if response != "": break
if tts: tts = True return response
else: tts = False
emojis, string = await extract_emoji(response)
debug(f"Emojis: {emojis}")
if len(string) < 1996:
await message.channel.send(string, tts=tts)
else:
#we send in an embed if the message is too long
embed = discord.Embed(title="Botator response", description=string, color=discord.Color.brand_green())
await message.channel.send(embed=embed, tts=tts)
for emoji in emojis:
#if the emoji is longer than 1 character, it's a custom emoji
try:
if len(emoji) > 1:
#if the emoji is a custom emoji, we need to fetch it
#the emoji is in the format id
debug(f"Emoji: {emoji}")
emoji = await message.guild.fetch_emoji(int(emoji))
await message.add_reaction(emoji)
else:
debug(f"Emoji: {emoji}")
await message.add_reaction(emoji)
except : pass
else:
await message.channel.send("The AI is not sure what to say (the response was empty)")

View File

@@ -3,32 +3,52 @@ import asyncio # pip install asyncio
import sqlite3 # pip install sqlite3 import sqlite3 # pip install sqlite3
import logging # pip install logging import logging # pip install logging
import os # pip install os import os # pip install os
intents = discord.Intents.all() intents = discord.Intents.all()
conn = sqlite3.connect('../database/premium.db') conn = sqlite3.connect("../database/premium.db")
c = conn.cursor() c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS data (user_id text, guild_id text, premium boolean)''') c.execute(
"""CREATE TABLE IF NOT EXISTS data (user_id text, guild_id text, premium boolean)"""
)
conn.commit() conn.commit()
bot = discord.Bot() bot = discord.Bot()
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
@bot.command() @bot.command()
@discord.commands.option(name="server id", description="The server id for which you want to activate premium features", required=True) @discord.commands.option(
name="server id",
description="The server id for which you want to activate premium features",
required=True,
)
async def activate_premium(ctx, server_id): async def activate_premium(ctx, server_id):
# first check if the user is already in the database, select guuild_id and premium from the data table where user_id is the author's id # first check if the user is already in the database, select guuild_id and premium from the data table where user_id is the author's id
logging.info("Activating premium for user " + str(ctx.author.id)) logging.info("Activating premium for user " + str(ctx.author.id))
c.execute("SELECT guild_id, premium FROM data WHERE user_id = ?", (ctx.author.id,)) c.execute("SELECT guild_id, premium FROM data WHERE user_id = ?", (ctx.author.id,))
# if a guild_id is found, override the old settings with the new ones # if a guild_id is found, override the old settings with the new ones
if c.fetchone() is not None: if c.fetchone() is not None:
c.execute("UPDATE data SET guild_id = ?, premium = ? WHERE user_id = ?", (server_id, True, ctx.author.id)) c.execute(
"UPDATE data SET guild_id = ?, premium = ? WHERE user_id = ?",
(server_id, True, ctx.author.id),
)
conn.commit() conn.commit()
logging.info("Premium activated for server " + server_id + "by user " + str(ctx.author.id)) logging.info(
"Premium activated for server "
+ server_id
+ "by user "
+ str(ctx.author.id)
)
await ctx.respond("Premium activated for server " + server_id, ephemeral=True) await ctx.respond("Premium activated for server " + server_id, ephemeral=True)
# if no guild_id is found, insert the new settings # if no guild_id is found, insert the new settings
else: else:
c.execute("INSERT INTO data VALUES (?, ?, ?)", (ctx.author.id, server_id, True)) c.execute("INSERT INTO data VALUES (?, ?, ?)", (ctx.author.id, server_id, True))
conn.commit() conn.commit()
logging.info("Premium updated for server " + server_id + "by user " + str(ctx.author.id)) logging.info(
"Premium updated for server " + server_id + "by user " + str(ctx.author.id)
)
await ctx.respond("Premium activated for server " + server_id, ephemeral=True) await ctx.respond("Premium activated for server " + server_id, ephemeral=True)
# each 24 hours, check if each user if they have the premium role "1050823446445178900" in the server "1050769643180146749" # each 24 hours, check if each user if they have the premium role "1050823446445178900" in the server "1050769643180146749"
async def check_premium(): async def check_premium():
while True: while True:
@@ -41,16 +61,31 @@ async def check_premium():
# if the user has the premium role, set premium to true # if the user has the premium role, set premium to true
logging.info("Checking premium for user " + str(row[0])) logging.info("Checking premium for user " + str(row[0]))
if discord.utils.get(user.roles, id=1050823446445178900) is not None: if discord.utils.get(user.roles, id=1050823446445178900) is not None:
c.execute("UPDATE data SET premium = ? WHERE user_id = ?", (True, row[0])) c.execute(
"UPDATE data SET premium = ? WHERE user_id = ?", (True, row[0])
)
conn.commit() conn.commit()
logging.info("Premium activated for server " + str(row[1]) + "by user " + str(row[0])) logging.info(
"Premium activated for server "
+ str(row[1])
+ "by user "
+ str(row[0])
)
# if the user does not have the premium role, set premium to false # if the user does not have the premium role, set premium to false
else: else:
c.execute("UPDATE data SET premium = ? WHERE user_id = ?", (False, row[0])) c.execute(
"UPDATE data SET premium = ? WHERE user_id = ?", (False, row[0])
)
conn.commit() conn.commit()
logging.info("Premium deactivated for server " + str(row[1]) + "by user " + str(row[0])) logging.info(
"Premium deactivated for server "
+ str(row[1])
+ "by user "
+ str(row[0])
)
await asyncio.sleep(86400) await asyncio.sleep(86400)
# add a task to the bot that runs check_premium every 24 hours # add a task to the bot that runs check_premium every 24 hours
bot.loop.create_task(check_premium()) bot.loop.create_task(check_premium())
# run the bot # run the bot

View File

@@ -1,7 +1,9 @@
import sqlite3 import sqlite3
conn = sqlite3.connect('../database/data.db')
conn = sqlite3.connect("../database/data.db")
c = conn.cursor() c = conn.cursor()
import time import time
# the database is: 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)''') # the database is: 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)''')
# set the uses_count_today to 0 for all guilds every 24 hours # set the uses_count_today to 0 for all guilds every 24 hours
while True: while True:

View File

@@ -1,7 +1,19 @@
from googleapiclient import discovery from googleapiclient import discovery
from config import perspective_api_key from config import perspective_api_key
import re import re
toxicity_names = ["toxicity", "severe_toxicity", "identity_attack", "insult", "profanity", "threat", "sexually_explicit", "flirtation", "obscene", "spam"]
toxicity_names = [
"toxicity",
"severe_toxicity",
"identity_attack",
"insult",
"profanity",
"threat",
"sexually_explicit",
"flirtation",
"obscene",
"spam",
]
toxicity_definitions = [ toxicity_definitions = [
"A rude, disrespectful, or unreasonable message that is likely to make people leave a discussion.", "A rude, disrespectful, or unreasonable message that is likely to make people leave a discussion.",
"A very hateful, aggressive, disrespectful message or otherwise very likely to make a user leave a discussion or give up on sharing their perspective. This attribute is much less sensitive to more mild forms of toxicity, such as messages that include positive uses of curse words.", "A very hateful, aggressive, disrespectful message or otherwise very likely to make a user leave a discussion or give up on sharing their perspective. This attribute is much less sensitive to more mild forms of toxicity, such as messages that include positive uses of curse words.",
@@ -12,12 +24,12 @@ toxicity_definitions = [
"Contains references to sexual acts, body parts, or other lewd content. \n **English only**", "Contains references to sexual acts, body parts, or other lewd content. \n **English only**",
"Pickup lines, complimenting appearance, subtle sexual innuendos, etc. \n **English only**", "Pickup lines, complimenting appearance, subtle sexual innuendos, etc. \n **English only**",
"Obscene or vulgar language such as cursing. \n **English only**", "Obscene or vulgar language such as cursing. \n **English only**",
"Irrelevant and unsolicited commercial content. \n **English only**" "Irrelevant and unsolicited commercial content. \n **English only**",
] ]
client = discovery.build(
client = discovery.build("commentanalyzer", "commentanalyzer",
"v1alpha1", "v1alpha1",
developerKey=perspective_api_key, developerKey=perspective_api_key,
discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1", discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1",
@@ -25,53 +37,120 @@ client = discovery.build("commentanalyzer",
) )
analyze_request = { analyze_request = {
'comment': {'text': ''}, # The text to analyze "comment": {"text": ""}, # The text to analyze
# we will ask the following attributes to google: TOXICITY, SEVERE_TOXICITY, IDENTITY_ATTACK, INSULT, PRPFANITY, THREAT, SEXUALLY_EXPLICIT, FLIRTATION, OBSCENE, SPAM # we will ask the following attributes to google: TOXICITY, SEVERE_TOXICITY, IDENTITY_ATTACK, INSULT, PRPFANITY, THREAT, SEXUALLY_EXPLICIT, FLIRTATION, OBSCENE, SPAM
'requestedAttributes': {'TOXICITY': {}, 'SEVERE_TOXICITY': {}, 'IDENTITY_ATTACK': {}, 'INSULT': {}, 'PROFANITY': {}, 'THREAT': {}, 'SEXUALLY_EXPLICIT': {}, 'FLIRTATION': {}, 'OBSCENE': {}, 'SPAM': {}}, "requestedAttributes": {
"TOXICITY": {},
"SEVERE_TOXICITY": {},
"IDENTITY_ATTACK": {},
"INSULT": {},
"PROFANITY": {},
"THREAT": {},
"SEXUALLY_EXPLICIT": {},
"FLIRTATION": {},
"OBSCENE": {},
"SPAM": {},
},
# we will analyze the text in any language automatically detected by google # we will analyze the text in any language automatically detected by google
'languages': [], "languages": [],
'doNotStore': 'true' # We don't want google to store the data because of privacy reasons & the GDPR (General Data Protection Regulation, an EU law that protects the privacy of EU citizens and residents for data privacy and security purposes https://gdpr-info.eu/) "doNotStore": "true", # We don't want google to store the data because of privacy reasons & the GDPR (General Data Protection Regulation, an EU law that protects the privacy of EU citizens and residents for data privacy and security purposes https://gdpr-info.eu/)
} }
analyze_request_not_en = { analyze_request_not_en = {
'comment': {'text': ''}, # The text to analyze "comment": {"text": ""}, # The text to analyze
# we will ask the following attributes to google: TOXICITY, SEVERE_TOXICITY, IDENTITY_ATTACK, INSULT, PRPFANITY, THREAT, SEXUALLY_EXPLICIT, FLIRTATION, OBSCENE, SPAM # we will ask the following attributes to google: TOXICITY, SEVERE_TOXICITY, IDENTITY_ATTACK, INSULT, PRPFANITY, THREAT, SEXUALLY_EXPLICIT, FLIRTATION, OBSCENE, SPAM
'requestedAttributes': {'TOXICITY': {}, 'SEVERE_TOXICITY': {}, 'IDENTITY_ATTACK': {}, 'INSULT': {}, 'PROFANITY': {}, 'THREAT': {}}, "requestedAttributes": {
"TOXICITY": {},
"SEVERE_TOXICITY": {},
"IDENTITY_ATTACK": {},
"INSULT": {},
"PROFANITY": {},
"THREAT": {},
},
# we will analyze the text in any language automatically detected by google # we will analyze the text in any language automatically detected by google
'languages': [], "languages": [],
'doNotStore': 'true' # We don't want google to store the data because of privacy reasons & the GDPR (General Data Protection Regulation, an EU law that protects the privacy of EU citizens and residents for data privacy and security purposes https://gdpr-info.eu/) "doNotStore": "true", # We don't want google to store the data because of privacy reasons & the GDPR (General Data Protection Regulation, an EU law that protects the privacy of EU citizens and residents for data privacy and security purposes https://gdpr-info.eu/)
} }
def get_toxicity(message: str): def get_toxicity(message: str):
# we first remove all kind of markdown from the message to avoid exploits # we first remove all kind of markdown from the message to avoid exploits
message = re.sub(r'\*([^*]+)\*', r'\1', message) message = re.sub(r"\*([^*]+)\*", r"\1", message)
message = re.sub(r'\_([^_]+)\_', r'\1', message) message = re.sub(r"\_([^_]+)\_", r"\1", message)
message = re.sub(r'\*\*([^*]+)\*\*', r'\1', message) message = re.sub(r"\*\*([^*]+)\*\*", r"\1", message)
message = re.sub(r'\_\_([^_]+)\_\_', r'\1', message) message = re.sub(r"\_\_([^_]+)\_\_", r"\1", message)
message = re.sub(r'\|\|([^|]+)\|\|', r'\1', message) message = re.sub(r"\|\|([^|]+)\|\|", r"\1", message)
message = re.sub(r'\~([^~]+)\~', r'\1', message) message = re.sub(r"\~([^~]+)\~", r"\1", message)
message = re.sub(r'\~\~([^~]+)\~\~', r'\1', message) message = re.sub(r"\~\~([^~]+)\~\~", r"\1", message)
message = re.sub(r'\`([^`]+)\`', r'\1', message) message = re.sub(r"\`([^`]+)\`", r"\1", message)
message = re.sub(r'\`\`\`([^`]+)\`\`\`', r'\1', message) message = re.sub(r"\`\`\`([^`]+)\`\`\`", r"\1", message)
# we try doing the request in english, but if we get 'errorType': 'LANGUAGE_NOT_SUPPORTED_BY_ATTRIBUTE' we try again with the analyze_request_not_en # we try doing the request in english, but if we get 'errorType': 'LANGUAGE_NOT_SUPPORTED_BY_ATTRIBUTE' we try again with the analyze_request_not_en
try: try:
analyze_request['comment']['text'] = message analyze_request["comment"]["text"] = message
response = client.comments().analyze(body=analyze_request).execute() response = client.comments().analyze(body=analyze_request).execute()
except: except:
analyze_request_not_en['comment']['text'] = message analyze_request_not_en["comment"]["text"] = message
response = client.comments().analyze(body=analyze_request_not_en).execute() response = client.comments().analyze(body=analyze_request_not_en).execute()
try: return [float(response['attributeScores']['TOXICITY']['summaryScore']['value']), float(response['attributeScores']['SEVERE_TOXICITY']['summaryScore']['value']), float(response['attributeScores']['IDENTITY_ATTACK']['summaryScore']['value']), float(response['attributeScores']['INSULT']['summaryScore']['value']), float(response['attributeScores']['PROFANITY']['summaryScore']['value']), float(response['attributeScores']['THREAT']['summaryScore']['value']), float(response['attributeScores']['SEXUALLY_EXPLICIT']['summaryScore']['value']), float(response['attributeScores']['FLIRTATION']['summaryScore']['value']), float(response['attributeScores']['OBSCENE']['summaryScore']['value']), float(response['attributeScores']['SPAM']['summaryScore']['value'])] try:
except: return [float(response['attributeScores']['TOXICITY']['summaryScore']['value']), float(response['attributeScores']['SEVERE_TOXICITY']['summaryScore']['value']), float(response['attributeScores']['IDENTITY_ATTACK']['summaryScore']['value']), float(response['attributeScores']['INSULT']['summaryScore']['value']), float(response['attributeScores']['PROFANITY']['summaryScore']['value']), float(response['attributeScores']['THREAT']['summaryScore']['value'])] return [
float(response["attributeScores"]["TOXICITY"]["summaryScore"]["value"]),
float(
response["attributeScores"]["SEVERE_TOXICITY"]["summaryScore"]["value"]
),
float(
response["attributeScores"]["IDENTITY_ATTACK"]["summaryScore"]["value"]
),
float(response["attributeScores"]["INSULT"]["summaryScore"]["value"]),
float(response["attributeScores"]["PROFANITY"]["summaryScore"]["value"]),
float(response["attributeScores"]["THREAT"]["summaryScore"]["value"]),
float(
response["attributeScores"]["SEXUALLY_EXPLICIT"]["summaryScore"][
"value"
]
),
float(response["attributeScores"]["FLIRTATION"]["summaryScore"]["value"]),
float(response["attributeScores"]["OBSCENE"]["summaryScore"]["value"]),
float(response["attributeScores"]["SPAM"]["summaryScore"]["value"]),
]
except:
return [
float(response["attributeScores"]["TOXICITY"]["summaryScore"]["value"]),
float(
response["attributeScores"]["SEVERE_TOXICITY"]["summaryScore"]["value"]
),
float(
response["attributeScores"]["IDENTITY_ATTACK"]["summaryScore"]["value"]
),
float(response["attributeScores"]["INSULT"]["summaryScore"]["value"]),
float(response["attributeScores"]["PROFANITY"]["summaryScore"]["value"]),
float(response["attributeScores"]["THREAT"]["summaryScore"]["value"]),
]
# test part # test part
def test(): def test():
print("Testing toxicity.py...") print("Testing toxicity.py...")
print("Hello world:") print("Hello world:")
result = get_toxicity('Hello world') result = get_toxicity("Hello world")
try: print(f"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]}") try:
except: print(f"TOXICITY: {result[0]}; SEVERE_TOXICITY: {result[1]}; IDENTITY ATTACK: {result[2]}; INSULT: {result[3]}; PROFANITY: {result[4]}; THREAT: {result[5]}") print(
f"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]}"
)
except:
print(
f"TOXICITY: {result[0]}; SEVERE_TOXICITY: {result[1]}; IDENTITY ATTACK: {result[2]}; INSULT: {result[3]}; PROFANITY: {result[4]}; THREAT: {result[5]}"
)
print("HELLO WORLD GET ABSOLUTELY BUY MY NEW MERCH OMGGGGGGG:") print("HELLO WORLD GET ABSOLUTELY BUY MY NEW MERCH OMGGGGGGG:")
result = get_toxicity('HELLO WORLD GET ABSOLUTELY BUY MY NEW MERCH OMGGGGGGG') result = get_toxicity("HELLO WORLD GET ABSOLUTELY BUY MY NEW MERCH OMGGGGGGG")
try: print(f"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]}") try:
except: print(f"TOXICITY: {result[0]}; SEVERE_TOXICITY: {result[1]}; IDENTITY ATTACK: {result[2]}; INSULT: {result[3]}; PROFANITY: {result[4]}; THREAT: {result[5]}") print(
f"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]}"
)
except:
print(
f"TOXICITY: {result[0]}; SEVERE_TOXICITY: {result[1]}; IDENTITY ATTACK: {result[2]}; INSULT: {result[3]}; PROFANITY: {result[4]}; THREAT: {result[5]}"
)
# uncomment the following line to test the code # uncomment the following line to test the code
# test() # test()

View File

@@ -2,13 +2,20 @@ import io
import os import os
import asyncio import asyncio
from config import debug from config import debug
# Imports the Google Cloud client library # Imports the Google Cloud client library
from google.cloud import vision from google.cloud import vision
# Instantiates a client # Instantiates a client
try:
client = vision.ImageAnnotatorClient() client = vision.ImageAnnotatorClient()
except:
debug("Google Vision API is not setup, please run /setup")
async def process(attachment): async def process(attachment):
try:
debug("Processing image...") debug("Processing image...")
image = vision.Image() image = vision.Image()
image.source.image_uri = attachment.url image.source.image_uri = attachment.url
@@ -22,14 +29,21 @@ async def process(attachment):
labels = labels[:2] labels = labels[:2]
objects = objects[:7] objects = objects[:7]
final = "<image\n" final = "<image\n"
if len(labels) > 0: final += "Labels:\n" if len(labels) > 0:
final += "Labels:\n"
for label in labels: for label in labels:
final += label.description + ", " final += label.description + ", "
final = final[:-2] + "\n" final = final[:-2] + "\n"
if len(texts) > 0: final += "Text:\n" if len(texts) > 0:
try: final += texts[0].description + "\n" #we take the first text, wich is the whole text in reality final += "Text:\n"
except: pass try:
if len(objects) > 0: final += "Objects:\n" final += (
texts[0].description + "\n"
) # we take the first text, wich is the whole text in reality
except:
pass
if len(objects) > 0:
final += "Objects:\n"
for obj in objects: for obj in objects:
final += obj.name + ", " final += obj.name + ", "
final = final[:-2] + "\n" final = final[:-2] + "\n"
@@ -39,8 +53,15 @@ async def process(attachment):
if not os.path.exists("./../database/google-vision/results"): if not os.path.exists("./../database/google-vision/results"):
os.mkdir("./../database/google-vision/results") os.mkdir("./../database/google-vision/results")
# we create the file # we create the file
with open(f"./../database/google-vision/results/{attachment.id}.txt", "w", encoding="utf-8") as f: with open(
f"./../database/google-vision/results/{attachment.id}.txt",
"w",
encoding="utf-8",
) as f:
f.write(final) f.write(final)
f.close() f.close()
return final return final
except Exception as e:
debug("Error while processing image: " + str(e))

14
docker-compose.yml Normal file
View File

@@ -0,0 +1,14 @@
# Docker compose sample file
version: '3'
services:
botator:
image: botator/botator:latest
container_name: botator
restart: always
volumes:
- ./database:/Botator/database
environment:
- PERSPECTIVE_API_KEY=your_api_key
- WEBHOOK_URL=https://yourdomain.com/botator
- DISCORD_TOKEN=your_token

View File

@@ -1,8 +0,0 @@
# To ensure app dependencies are ported from your virtual environment/host machine into your container, run 'pip freeze > requirements.txt' in the terminal to overwrite this file
py-cord
openai
apsw
google-api-python-client
python-dotenv
emoji
google-cloud-vision

View File

@@ -1,20 +0,0 @@
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10.0
# Keeps Python from generating .pyc files in the container
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
# Install pip requirements
COPY requirements.txt .
RUN pip install -r requirements.txt
RUN git clone https://github.com/Paillat-dev/Botator.git
WORKDIR /Botator/code/
COPY premium-key.txt /Botator/code/
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /Botator/code
USER appuser
CMD ["python", "premiumcode.py"]

View File

@@ -1,3 +0,0 @@
# To ensure app dependencies are ported from your virtual environment/host machine into your container, run 'pip freeze > requirements.txt' in the terminal to overwrite this file
py-cord
openai

View File

@@ -1,17 +0,0 @@
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10.0
# Keeps Python from generating .pyc files in the container
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
# Install pip requirements
RUN git clone https://github.com/Paillat-dev/Botator.git
WORKDIR /Botator/code/
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /Botator/code
USER appuser
CMD ["python", "resetter.py"]

8
requirements.txt Normal file
View File

@@ -0,0 +1,8 @@
py-cord
python-dotenv
openai
emoji
# Google api
google-api-python-client
google-cloud-vision

View File

@@ -1,24 +1,23 @@
import io import io
import os import os
import asyncio import asyncio
# Imports the Google Cloud client library # Imports the Google Cloud client library
from google.cloud import vision from google.cloud import vision
# we set the env variable GOOGLE_APPLICATION_CREDENTIALS to the path of the json file # we set the env variable GOOGLE_APPLICATION_CREDENTIALS to the path of the json file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./../database/google-vision/botator-vision-8cd1030a7541.json" os.environ[
"GOOGLE_APPLICATION_CREDENTIALS"
] = "./../database/google-vision/botator-vision-8cd1030a7541.json"
# Instantiates a client # Instantiates a client
client = vision.ImageAnnotatorClient() client = vision.ImageAnnotatorClient()
# The name of the image file to annotate # The name of the image file to annotate
file_name = os.path.abspath('./../database/google-vision/label.jpg') file_name = os.path.abspath("./../database/google-vision/label.jpg")
print(file_name) print(file_name)
# Loads the image into memory # Loads the image into memory
with io.open(file_name, 'rb') as image_file: with io.open(file_name, "rb") as image_file:
content = image_file.read() content = image_file.read()
image = vision.Image(content=content) image = vision.Image(content=content)
@@ -31,28 +30,32 @@ image = vision.Image(content=content)
# for label in labels: # for label in labels:
# print(label.description) # print(label.description)
async def get_labels(image): async def get_labels(image):
response = client.label_detection(image=image) response = client.label_detection(image=image)
labels = response.label_annotations labels = response.label_annotations
return labels return labels
async def get_text(image): async def get_text(image):
response = client.text_detection(image=image) response = client.text_detection(image=image)
texts = response.text_annotations texts = response.text_annotations
return texts return texts
# now we print the labels # now we print the labels
async def main(): async def main():
labels = await get_labels(image) labels = await get_labels(image)
print('Labels:') print("Labels:")
for label in labels: for label in labels:
print(label.description) print(label.description)
texts = await get_text(image) texts = await get_text(image)
print('Texts:') print("Texts:")
for text in texts: for text in texts:
print(text.description) print(text.description)
# now we run the main function # now we run the main function
if __name__ == '__main__': if __name__ == "__main__":
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
loop.run_until_complete(main()) loop.run_until_complete(main())