Skip to content

Commit

Permalink
Merge pull request #315 from PyBotDevs/automod-library
Browse files Browse the repository at this point in the history
Migrate all automod db functions to a framework module
  • Loading branch information
notsniped authored Oct 25, 2023
2 parents f9d40aa + cf64eec commit dfb809a
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 38 deletions.
37 changes: 12 additions & 25 deletions cogs/automod.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@

# Imports
import discord
import json
from discord import option, ApplicationContext
from discord.ext import commands
from framework.isobot.db import automod

# Variables

color = discord.Color.random()

with open('database/automod.json', 'r', encoding="utf-8") as f: automod_config = json.load(f)

def save():
with open('database/automod.json', 'w+', encoding="utf-8") as f: json.dump(automod_config, f, indent=4)
automod = automod.Automod()

# Commands
class Automod(commands.Cog):
Expand All @@ -25,7 +20,7 @@ def __init__(self, bot):
description="Shows the current automod configuration for your server"
)
async def automod(self, ctx: ApplicationContext):
loaded_config = automod_config[str(ctx.guild.id)]
loaded_config = automod.fetch_config(ctx.guild.id)
localembed = discord.Embed(title=f"{ctx.guild.name}\'s automod configuration", descripton="Use the `/automod_set` command to change your server's automod configuration.", color=color)
localembed.set_thumbnail(url=ctx.guild.icon_url)
localembed.add_field(name="Swear-filter", value=loaded_config["swear_filter"]["enabled"])
Expand All @@ -39,34 +34,30 @@ async def automod(self, ctx: ApplicationContext):
)
@option(name="toggle", description="Do you want to turn it on or off?", type=bool)
async def automod_swearfilter(self, ctx: ApplicationContext, toggle:bool):
loaded_config = automod_config[str(ctx.guild.id)]
if not ctx.author.guild_permissions.administrator: return await ctx.respond("You cannot use this command. If you think this is a mistake, please contact your server owner/administrator.", ephemeral=True)
if loaded_config["swear_filter"]["enabled"] == toggle: return await ctx.respond(f"That automod option is already set to `{toggle}`.", ephemeral=True)
loaded_config["swear_filter"]["enabled"] = toggle
if automod.fetch_config(ctx.guild.id)["swear_filter"]["enabled"] == toggle: return await ctx.respond(f"That automod option is already set to `{toggle}`.", ephemeral=True)
automod.swearfilter_enabled(ctx.guild.id, toggle)
if toggle is True: await ctx.respond("Swear-filter successfully **enabled**.", ephemeral=True)
elif toggle is False: await ctx.respond("Swear-filter successfully **disabled**.", ephemeral=True)
save()

@commands.slash_command(
name="automod_use_default_keywords",
description="Choose whether or not you want to use the default keywords for automod's swear-filter"
)
@option(name="toggle", description="Do you want to turn it on or off?", type=bool)
async def automod_use_default_keywords(self, ctx: ApplicationContext, toggle:bool):
loaded_config = automod_config[str(ctx.guild.id)]
if not ctx.author.guild_permissions.administrator: return await ctx.respond("You cannot use this command. If you think this is a mistake, please contact your server owner/administrator.", ephemeral=True)
if loaded_config["swear_filter"]["keywords"]["use_default"] == toggle: return await ctx.respond(f"That automod option is already set to `{toggle}`.", ephemeral=True)
loaded_config["swear_filter"]["keywords"]["use_default"] = toggle
if automod.fetch_config(ctx.guild.id)["swear_filter"]["keywords"]["use_default"] == toggle: return await ctx.respond(f"That automod option is already set to `{toggle}`.", ephemeral=True)
automod.swearfilter_usedefaultkeywords(ctx.guild.id, toggle)
if toggle is True: await ctx.respond("Using default swear-filter keywords successfully **enabled**.", ephemeral=True)
elif toggle is False: await ctx.respond("Using default swear-filter keywords successfully **disabled**.", ephemeral=True)
save()

@commands.slash_command(
name="automod_view_custom_keywords",
description="Shows a list of the custom automod swear-filter keywords set for your server",
)
async def automod_view_custom_keywords(self, ctx: ApplicationContext):
loaded_config = automod_config[str(ctx.guild.id)]
loaded_config = automod.fetch_config(ctx.guild.id)
out = ""
if loaded_config["swear_filter"]["keywords"]["custom"] != []:
i = 0
Expand All @@ -85,10 +76,9 @@ async def automod_view_custom_keywords(self, ctx: ApplicationContext):
@option(name="keyword", description="What keyword do you want to add?", type=str)
async def automod_add_custom_keyword(self, ctx: ApplicationContext, keyword:str):
if not ctx.author.guild_permissions.administrator: return await ctx.respond("You cannot use this command. If you think this is a mistake, please contact your server owner/administrator.", ephemeral=True)
loaded_config = automod_config[str(ctx.guild.id)]
loaded_config = automod.fetch_config(ctx.guild.id)
if keyword not in loaded_config["swear_filter"]["keywords"]["custom"]:
loaded_config["swear_filter"]["keywords"]["custom"].append(keyword)
save()
automod.swearfilter_addkeyword(ctx.guild.id, keyword)
localembed = discord.Embed(description=f"New swear-filter keyword `{keyword}` successfully added to configuration.", color=discord.Color.green())
await ctx.respond(embed=localembed, ephemeral=True)
else: return await ctx.respond("That keyword is already added in your automod configuration.", ephemeral=True)
Expand All @@ -98,12 +88,9 @@ async def automod_add_custom_keyword(self, ctx: ApplicationContext, keyword:str)
description="Removes a custom keyword (matching its id) from your server's swear-filter"
)
@option(name="id", description="What's the id of the keyword to remove (can be found in bold through /automod_view_custom_keywords", type=int)
async def automod_remove_custom_keyword(self, ctx: ApplicationContext, id:int):
loaded_config = automod_config[str(ctx.guild.id)]
async def automod_remove_custom_keyword(self, ctx: ApplicationContext, id: int):
try:
data = loaded_config["swear_filter"]["keywords"]["custom"]
data.pop(id-1)
save()
automod.swearfilter_removekeyword(ctx.guild.id, id)
return await ctx.respond(f"Keyword (id: `{id}`) successfully removed from swear-filter configuration.")
except IndexError: await ctx.respond("That keyword id doesn't exist. Please specify a valid id and try again.", ephemeral=True)

Expand Down
70 changes: 70 additions & 0 deletions framework/isobot/db/automod.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""The framework module library used for managing server automod configurations."""

# Imports
import json

# Functions
class Automod():
"""Initializes the Automod database system."""
def __init__(self):
print("[framework/db/Automod] Automod db library initialized.")

def load(self) -> dict:
"""Fetches and returns the latest data from the items database."""
with open("database/automod.json", 'r', encoding="utf8") as f: db = json.load(f)
return db

def save(self, data: dict) -> int:
"""Dumps all cached data to your local machine."""
with open("database/automod.json", 'w+', encoding="utf8") as f: json.dump(data, f, indent=4)
return 0

def generate(self, server_id: int) -> int:
"""Generates a new database key for the specified server/guild id in the automod database."""
automod_config = self.load()
if str(server_id) not in automod_config:
automod_config[str(server_id)] = {
"swear_filter": {
"enabled": False,
"keywords": {
"use_default": True,
"default": ["fuck", "shit", "pussy", "penis", "cock", "vagina", "sex", "moan", "bitch", "hoe", "nigga", "nigger", "xxx", "porn"],
"custom": []
}
}
}
self.save(automod_config)

def fetch_config(self, server_id: int) -> dict:
"""Fetches and returns the specified server's automod configuration.\n\nReturns in raw `dict` format."""
automod_config = self.load()
return automod_config[str(server_id)]

def swearfilter_enabled(self, server_id: int, value: bool) -> int:
"""Sets a `bool` value to define whether the server's swear-filter is enabled or not."""
automod_config = self.load()
automod_config[str(server_id)]["swear_filter"]["enabled"] = value
self.save(automod_config)
return 0

def swearfilter_usedefaultkeywords(self, server_id: int, enabled: bool) -> int:
"""Sets a `bool` value to define whether the server's swear-filter will use default keywords."""
automod_config = self.load()
automod_config[str(server_id)]["swear_filter"]["keywords"]["use_default"] = enabled
self.save(automod_config)
return 0

def swearfilter_addkeyword(self, server_id: int, keyword: str) -> int:
"""Adds a new custom keyword for the server's automod configuration."""
automod_config = self.load()
automod_config[str(server_id)]["swear_filter"]["keywords"]["custom"].append(keyword)
self.save(automod_config)
return 0

def swearfilter_removekeyword(self, server_id: int, keyword_id: int) -> int:
"""Removes a keyword (using id) from the server's automod configuration."""
automod_config = self.load()
data = automod_config[str(server_id)]["swear_filter"]["keywords"]["custom"]
data.pop(id-1)
self.save(automod_config)
return 0
16 changes: 3 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from math import floor
from random import randint
from framework.isobot import currency, colors, settings
from framework.isobot.db import levelling, items, userdata
from framework.isobot.db import levelling, items, userdata, automod
from discord import ApplicationContext, option
from discord.ext import commands
from cogs.isocoin import create_isocoin_key
Expand Down Expand Up @@ -57,6 +57,7 @@ def save():
levelling = levelling.Levelling()
items = items.Items()
userdata = userdata.UserData()
automod = automod.Automod()

# Theme Loader
themes = False # True: enables themes; False: disables themes;
Expand Down Expand Up @@ -100,18 +101,7 @@ async def on_message(ctx):
settings.generate(ctx.author.id)
items.generate(ctx.author.id)
levelling.generate(ctx.author.id)
if str(ctx.guild.id) not in automod_config:
automod_config[str(ctx.guild.id)] = {
"swear_filter": {
"enabled": False,
"keywords": {
"use_default": True,
"default": ["fuck", "shit", "pussy", "penis", "cock", "vagina", "sex", "moan", "bitch", "hoe", "nigga", "nigger", "xxx", "porn"],
"custom": []
}
}
}
save()
automod.generate(ctx.guild.id)
uList = list()
if str(ctx.guild.id) in presence:
for userid in presence[str(ctx.guild.id)].keys(): uList.append(userid)
Expand Down

0 comments on commit dfb809a

Please sign in to comment.