Browse Source

Settings cog moved over to the new internal settings object stuff. Also some extra comments here and there/

tags/v1.5.0
Roxie Gibson 6 years ago
parent
commit
f090fcffc2
3 changed files with 138 additions and 89 deletions
  1. +37
    -9
      Roxbot/settings/guild_settings.py
  2. +92
    -77
      Roxbot/settings/settings.py
  3. +9
    -3
      main.py

+ 37
- 9
Roxbot/settings/guild_settings.py View File





def _open_config(): def _open_config():
"""
Opens the guild settings file
:return settings file: :type dict:
"""
with open('Roxbot/settings/servers.json', 'r') as config_file: with open('Roxbot/settings/servers.json', 'r') as config_file:
return json.load(config_file) return json.load(config_file)


def _write_changes(config): def _write_changes(config):
"""
Writes given config to disk.
:param config: :type dict:
:return:
"""
with open('Roxbot/settings/servers.json', 'w') as conf_file: with open('Roxbot/settings/servers.json', 'w') as conf_file:
json.dump(config, conf_file) json.dump(config, conf_file)


"WARNING: The settings file for {} was missing the {} setting in the {} cog. This has been fixed with the template version. It is disabled by default.".format( "WARNING: The settings file for {} was missing the {} setting in the {} cog. This has been fixed with the template version. It is disabled by default.".format(
server.name.upper(), setting.upper(), cog_setting.upper())) server.name.upper(), setting.upper(), cog_setting.upper()))


def get(guilds):
def get_all(guilds):
"""
Returns a list of GuildSettings for all guilds the bot can see.
:param guilds:
:return list of GuildSettings: :type list:
"""
error_check(guilds) error_check(guilds)
guild_list = [] guild_list = []
for guild in guilds: for guild in guilds:
guild_list.append(guild) guild_list.append(guild)
return guild_list return guild_list


def get(guild):
"""
Gets a single GuildSettings Object representing the settings of that guild
:param guild:
:return Single GuildSettings Object: :type GuildSettings:
"""
error_check(guild)
return GuildSettings(guild)

def get_guild(guilds, wanted_guild): def get_guild(guilds, wanted_guild):
for guild in guilds: for guild in guilds:
if guild.id == wanted_guild.id: if guild.id == wanted_guild.id:
return None return None


class GuildSettings(object): class GuildSettings(object):

"""
An Object to store all settings for one guild.
The goal is to make editing settings a lot easier and make it so you don't have to handle things like ID's which caused a lot of issues when moving over to discord.py 1.0
"""
__slots__ = ["settings", "id", "name", "nsfw", "self_assign", "greets", "goodbyes", "twitch", "perm_roles", "custom_commands", "warnings", "is_anal", "gss"] __slots__ = ["settings", "id", "name", "nsfw", "self_assign", "greets", "goodbyes", "twitch", "perm_roles", "custom_commands", "warnings", "is_anal", "gss"]


def __init__(self, guild): def __init__(self, guild):
self.id = guild.id self.id = guild.id
self.name = str(guild) self.name = str(guild)
self.settings = _open_config()[str(self.id)]
self.settings = self.refresh()
self.get_settings() self.get_settings()


def __str__(self): def __str__(self):
return self.name return self.name


def refresh(self):
return _open_config()[str(self.id)]

def get_settings(self): def get_settings(self):
self.nsfw = self.settings["nsfw"] self.nsfw = self.settings["nsfw"]
self.self_assign = self.settings["self_assign"] self.self_assign = self.settings["self_assign"]
# Add custom cog settings loading here # Add custom cog settings loading here
self.gss = self.settings["gss"] self.gss = self.settings["gss"]


def update_settings(self, changed_dict, setting = None):
def update(self, changed_dict, setting = None):
self.settings = self.refresh()
self.get_settings() self.get_settings()
if setting is not None: if setting is not None:
self.settings[str(self.id)][setting] = changed_dict
self.settings[setting] = changed_dict
else: else:
self.settings[str(self.id)] = changed_dict
settings = _open_config()
settings[str(self.id)] = self.settings
_write_changes(settings)
self.settings = changed_dict
_write_changes(self.settings)

+ 92
- 77
Roxbot/settings/settings.py View File

import asyncio import asyncio


from Roxbot import checks, load_config from Roxbot import checks, load_config
from Roxbot.settings.guild_settings import ServerConfig
from Roxbot.settings import guild_settings as settings


import discord import discord
from discord.ext.commands import bot, group, is_owner, bot_has_permissions from discord.ext.commands import bot, group, is_owner, bot_has_permissions
""" """
def __init__(self, bot_client): def __init__(self, bot_client):
self.bot = bot_client self.bot = bot_client
self.con = ServerConfig()
self.serverconfig = self.con.servers
self.settings = settings


def get_channel(self, ctx, channel): def get_channel(self, ctx, channel):
if ctx.message.channel_mentions: if ctx.message.channel_mentions:
await self.bot.change_nickname(ctx.message.server.me, nick) await self.bot.change_nickname(ctx.message.server.me, nick)
return await ctx.send(":thumbsup:") return await ctx.send(":thumbsup:")



@bot.command(aliases=["activity"]) @bot.command(aliases=["activity"])
@is_owner() @is_owner()
async def changeactivity(self, ctx, *, game: str): async def changeactivity(self, ctx, *, game: str):
@checks.is_owner_or_admin() @checks.is_owner_or_admin()
async def printsettings(self, ctx, option=None): async def printsettings(self, ctx, option=None):
"OWNER OR ADMIN ONLY: Prints the servers settings file." "OWNER OR ADMIN ONLY: Prints the servers settings file."
self.serverconfig = self.con.load_config()
config = self.serverconfig[str(ctx.guild.id)]
config = self.settings.get(ctx.guild)
em = discord.Embed(colour=0xDEADBF) em = discord.Embed(colour=0xDEADBF)
em.set_author(name="{} settings for {}.".format(self.bot.user.name, ctx.message.guild.name), icon_url=self.bot.user.avatar_url) em.set_author(name="{} settings for {}.".format(self.bot.user.name, ctx.message.guild.name), icon_url=self.bot.user.avatar_url)
if option in config: if option in config:
async def settings(self, ctx): async def settings(self, ctx):
if ctx.invoked_subcommand is None: if ctx.invoked_subcommand is None:
return await ctx.send('Missing Argument') return await ctx.send('Missing Argument')
self.serverconfig = self.con.load_config()
self.guild_id = str(ctx.guild.id)
self.guild_settings = self.settings.get(ctx.guild)


@settings.command(aliases=["sa"]) @settings.command(aliases=["sa"])
async def selfassign(self, ctx, selection, *, changes = None): async def selfassign(self, ctx, selection, *, changes = None):
""" """
selection = selection.lower() selection = selection.lower()
role = discord.utils.find(lambda u: u.name == changes, ctx.message.guild.roles) role = discord.utils.find(lambda u: u.name == changes, ctx.message.guild.roles)
self_assign = self.guild_settings.self_assign

if selection == "enable": if selection == "enable":
self.serverconfig[self.guild_id]["self_assign"]["enabled"] = 1
self_assign["enabled"] = 1
await ctx.send("'self_assign' was enabled!") await ctx.send("'self_assign' was enabled!")
elif selection == "disable": elif selection == "disable":
self.serverconfig[self.guild_id]["self_assign"]["enabled"] = 0
self_assign["enabled"] = 0
await ctx.send("'self_assign' was disabled :cry:") await ctx.send("'self_assign' was disabled :cry:")
elif selection == "addrole": elif selection == "addrole":
if role.id in self.serverconfig[self.guild_id]["self_assign"]["roles"]:
return await ctx.send("{} is already a self-assignable role.".format(role.name),
delete_after=self.con.delete_after)

self.serverconfig[self.guild_id]["self_assign"]["roles"].append(role.id)
if role.id in self_assign["roles"]:
return await ctx.send("{} is already a self-assignable role.".format(role.name))
self_assign["roles"].append(role.id)
await ctx.send('Role "{}" added'.format(str(role))) await ctx.send('Role "{}" added'.format(str(role)))
elif selection == "removerole": elif selection == "removerole":
if role.id in self.serverconfig[self.guild_id]["self_assign"]["roles"]:
self.serverconfig[self.guild_id]["self_assign"]["roles"].remove(role.id)
self.con.update_config(self.serverconfig)
if role.id in self_assign["roles"]:
self_assign["roles"].remove(role.id)
await ctx.send('"{}" has been removed from the self-assignable roles.'.format(str(role))) await ctx.send('"{}" has been removed from the self-assignable roles.'.format(str(role)))
else: else:
return await ctx.send("That role was not in the list.") return await ctx.send("That role was not in the list.")
else: else:
return await ctx.send("No valid option given.") return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
return self.guild_settings.update(self_assign, "self_assign")


@settings.command(aliases=["jl"]) @settings.command(aliases=["jl"])
async def joinleave(self, ctx, selection, *, changes = None): async def joinleave(self, ctx, selection, *, changes = None):
enable/disable: Enable/disables parts of the cog. Needs to specify which part. enable/disable: Enable/disables parts of the cog. Needs to specify which part.
Example: Example:
;settings joinleave enable greets|goodbyes ;settings joinleave enable greets|goodbyes
welcomechannel/goodbyeschannel: Sets the channels for either option. Must be a ID or mention.
greetschannel/goodbyeschannel: Sets the channels for either option. Must be a ID or mention.
custommessage: specifies a custom message for the greet messages. custommessage: specifies a custom message for the greet messages.
""" """
selection = selection.lower() selection = selection.lower()
if selection == "enable":
if changes == "greets":
self.serverconfig[self.guild_id]["greets"]["enabled"] = 1
channel = self.get_channel(ctx, changes)
greets = self.guild_settings.greets
goodbyes = self.guild_settings.goodbyes

if changes == "greets":
if selection == "enable":
greets["enabled"] = 1
await ctx.send("'greets' was enabled!") await ctx.send("'greets' was enabled!")
elif changes == "goodbyes":
self.serverconfig[self.guild_id]["goodbyes"]["enabled"] = 1
await ctx.send("'goodbyes' was enabled!")
elif selection == "disable":
if changes == "greets":
self.serverconfig[self.guild_id]["greets"]["enabled"] = 0
elif selection == "disable":
greets["enabled"] = 0
await ctx.send("'greets' was disabled :cry:") await ctx.send("'greets' was disabled :cry:")
elif changes == "goodbyes":
self.serverconfig[self.guild_id]["goodbyes"]["enabled"] = 0

elif changes == "goodbyes":
if selection == "enable":
goodbyes["enabled"] = 1
await ctx.send("'goodbyes' was enabled!")
elif selection == "disable":
goodbyes["enabled"] = 0
await ctx.send("'goodbyes' was disabled :cry:") await ctx.send("'goodbyes' was disabled :cry:")
elif selection == "welcomechannel":
channel = self.get_channel(ctx, changes)
self.serverconfig[self.guild_id]["greets"]["welcome-channel"] = channel.id
await ctx.send("{} has been set as the welcome channel!".format(channel.mention))
elif selection == "goodbyeschannel":
channel = self.get_channel(ctx, changes)
self.serverconfig[self.guild_id]["goodbyes"]["goodbye-channel"] = channel.id
await ctx.send("{} has been set as the goodbye channel!".format(channel.mention))
elif selection == "custommessage":
self.serverconfig[self.guild_id]["greets"]["custom-message"] = changes
await ctx.send("Custom message set to '{}'".format(changes))

else: else:
return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
if selection == "greetschannel":
greets["welcome-channel"] = channel.id
changes = "greets"
await ctx.send("{} has been set as the welcome channel!".format(channel.mention))
elif selection == "goodbyeschannel":
goodbyes["goodbye-channel"] = channel.id
changes = "goodbyes"
await ctx.send("{} has been set as the goodbye channel!".format(channel.mention))
elif selection == "custommessage":
greets["custom-message"] = changes
changes = "greets"
await ctx.send("Custom message set to '{}'".format(changes))
else:
return await ctx.send("No valid option given.")

if changes == "greets":
return self.guild_settings.update(greets, "greets")
elif changes == "goodbyes":
return self.guild_settings.update(goodbyes, "goodbyes")


@settings.command() @settings.command()
async def twitch(self, ctx, selection, *, changes = None): async def twitch(self, ctx, selection, *, changes = None):
channel: Sets the channel to shill in. channel: Sets the channel to shill in.
""" """
selection = selection.lower() selection = selection.lower()
twitch = self.guild_settings.twitch

if selection == "enable": if selection == "enable":
self.serverconfig[self.guild_id]["twitch"]["enabled"] = 1
twitch["enabled"] = 1
await ctx.send("'twitch' was enabled!") await ctx.send("'twitch' was enabled!")
elif selection == "disable": elif selection == "disable":
self.serverconfig[self.guild_id]["twitch"]["enabled"] = 0
twitch["enabled"] = 0
await ctx.send("'twitch' was disabled :cry:") await ctx.send("'twitch' was disabled :cry:")
elif selection == "channel": elif selection == "channel":
channel = self.get_channel(ctx, changes) channel = self.get_channel(ctx, changes)
self.serverconfig[self.guild_id]["twitch"]["channel"] = channel.id
twitch["channel"] = channel.id
await ctx.send("{} has been set as the twitch shilling channel!".format(channel.mention)) await ctx.send("{} has been set as the twitch shilling channel!".format(channel.mention))
# Is lacking whitelist options. Might be added or might be depreciated. # Is lacking whitelist options. Might be added or might be depreciated.
# Turns out this is handled in the cog and I don't think it needs changing but may be confusing. # Turns out this is handled in the cog and I don't think it needs changing but may be confusing.
else: else:
return await ctx.send("No valid option given.") return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
return self.guild_settings.update(twitch, "twitch")


@settings.command(aliases=["perms"]) @settings.command(aliases=["perms"])
async def permrole(self, ctx, selection, *, changes = None): async def permrole(self, ctx, selection, *, changes = None):
""" """
selection = selection.lower() selection = selection.lower()
role = discord.utils.find(lambda u: u.name == changes, ctx.message.guild.roles) role = discord.utils.find(lambda u: u.name == changes, ctx.message.guild.roles)
perm_roles = self.guild_settings.perm_roles

if selection == "addadmin": if selection == "addadmin":
if role.id not in self.serverconfig[self.guild_id]["perm_roles"]["admin"]:
self.serverconfig[self.guild_id]["perm_roles"]["admin"].append(role.id)
if role.id not in perm_roles["admin"]:
perm_roles["admin"].append(role.id)
await ctx.send("'{}' has been added to the Admin role list.".format(role.name)) await ctx.send("'{}' has been added to the Admin role list.".format(role.name))
else: else:
return await ctx.send("'{}' is already in the list.".format(role.name)) return await ctx.send("'{}' is already in the list.".format(role.name))
elif selection == "addmod": elif selection == "addmod":
if role.id not in self.serverconfig[self.guild_id]["perm_roles"]["mod"]:
self.serverconfig[self.guild_id]["perm_roles"]["mod"].append(role.id)
if role.id not in perm_roles["mod"]:
perm_roles["mod"].append(role.id)
await ctx.send("'{}' has been added to the Mod role list.".format(role.name)) await ctx.send("'{}' has been added to the Mod role list.".format(role.name))
else: else:
return await ctx.send("'{}' is already in the list.".format(role.name)) return await ctx.send("'{}' is already in the list.".format(role.name))
elif selection == "removeadmin": elif selection == "removeadmin":
try: try:
self.serverconfig[self.guild_id]["perm_roles"]["admin"].remove(role.id)
perm_roles["admin"].remove(role.id)
await ctx.send("'{}' has been removed from the Admin role list.".format(role.name)) await ctx.send("'{}' has been removed from the Admin role list.".format(role.name))
except ValueError: except ValueError:
return await ctx.send("That role was not in the list.") return await ctx.send("That role was not in the list.")
elif selection == "removemod": elif selection == "removemod":
try: try:
self.serverconfig[self.guild_id]["perm_roles"]["mod"].remove(role.id)
perm_roles["mod"].remove(role.id)
await ctx.send("'{}' has been removed from the Mod role list.".format(role.name)) await ctx.send("'{}' has been removed from the Mod role list.".format(role.name))
except ValueError: except ValueError:
return await ctx.send("That role was not in the list.") return await ctx.send("That role was not in the list.")


else: else:
return await ctx.send("No valid option given.") return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
return self.guild_settings.update(perm_roles, "perm_roles")


@settings.command() @settings.command()
async def gss(self, ctx, selection, *, changes = None): async def gss(self, ctx, selection, *, changes = None):
"""Custom Cog for the GaySoundsShitposts Discord Server.""" """Custom Cog for the GaySoundsShitposts Discord Server."""
selection = selection.lower() selection = selection.lower()
gss = self.guild_settings.gss

if selection == "loggingchannel": if selection == "loggingchannel":
channel = self.get_channel(ctx, changes) channel = self.get_channel(ctx, changes)
self.serverconfig[self.guild_id]["gss"]["log_channel"] = channel.id
gss["log_channel"] = channel.id
await ctx.send("Logging Channel set to '{}'".format(channel.name)) await ctx.send("Logging Channel set to '{}'".format(channel.name))
elif selection == "requireddays": elif selection == "requireddays":
self.serverconfig[self.guild_id]["gss"]["required_days"] = int(changes)
gss["required_days"] = int(changes)
await ctx.send("Required days set to '{}'".format(str(changes))) await ctx.send("Required days set to '{}'".format(str(changes)))
elif selection == "requiredscore": elif selection == "requiredscore":
self.serverconfig[self.guild_id]["gss"]["required_score"] = int(changes)
gss["required_score"] = int(changes)
await ctx.send("Required score set to '{}'".format(str(changes))) await ctx.send("Required score set to '{}'".format(str(changes)))
else: else:
return await ctx.send("No valid option given.") return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
return self.guild_settings.update(gss, "gss")




@settings.command() @settings.command()
;settings nsfw addchannel #nsfw_stuff ;settings nsfw addchannel #nsfw_stuff
""" """
selection = selection.lower() selection = selection.lower()
nsfw = self.guild_settings.nsfw

if selection == "enable": if selection == "enable":
self.serverconfig[self.guild_id]["nsfw"]["enabled"] = 1
nsfw["enabled"] = 1
await ctx.send("'nsfw' was enabled!") await ctx.send("'nsfw' was enabled!")
elif selection == "disable": elif selection == "disable":
self.serverconfig[self.guild_id]["nsfw"]["enabled"] = 0
nsfw["enabled"] = 0
await ctx.send("'nsfw' was disabled :cry:") await ctx.send("'nsfw' was disabled :cry:")
elif selection == "addchannel": elif selection == "addchannel":
channel = self.get_channel(ctx, changes) channel = self.get_channel(ctx, changes)
if channel.id not in self.serverconfig[self.guild_id]["nsfw"]["channels"]:
self.serverconfig[self.guild_id]["nsfw"]["channels"].append(channel.id)
if channel.id not in nsfw["channels"]:
nsfw["channels"].append(channel.id)
await ctx.send("'{}' has been added to the nsfw channel list.".format(channel.name)) await ctx.send("'{}' has been added to the nsfw channel list.".format(channel.name))
else: else:
return await ctx.send("'{}' is already in the list.".format(channel.name)) return await ctx.send("'{}' is already in the list.".format(channel.name))
elif selection == "removechannel": elif selection == "removechannel":
channel = self.get_channel(ctx, changes) channel = self.get_channel(ctx, changes)
try: try:
self.serverconfig[self.guild_id]["nsfw"]["channels"].remove(channel.id)
nsfw["channels"].remove(channel.id)
await ctx.send("'{}' has been removed from the nsfw channel list.".format(channel.name)) await ctx.send("'{}' has been removed from the nsfw channel list.".format(channel.name))
except ValueError: except ValueError:
return await ctx.send("That role was not in the list.") return await ctx.send("That role was not in the list.")
elif selection == "addbadtag": elif selection == "addbadtag":
if changes not in self.serverconfig[self.guild_id]["nsfw"]["blacklist"]:
self.serverconfig[self.guild_id]["nsfw"]["blacklist"].append(changes)
if changes not in nsfw["nsfw"]["blacklist"]:
nsfw["blacklist"].append(changes)
await ctx.send("'{}' has been added to the blacklisted tag list.".format(changes)) await ctx.send("'{}' has been added to the blacklisted tag list.".format(changes))
else: else:
return await ctx.send("'{}' is already in the list.".format(changes)) return await ctx.send("'{}' is already in the list.".format(changes))
elif selection == "removebadtag": elif selection == "removebadtag":
try: try:
self.serverconfig[self.guild_id]["nsfw"]["blacklist"].remove(changes)
nsfw["blacklist"].remove(changes)
await ctx.send("'{}' has been removed from the blacklisted tag list.".format(changes)) await ctx.send("'{}' has been removed from the blacklisted tag list.".format(changes))
except ValueError: except ValueError:
return await ctx.send("That tag was not in the blacklisted tag list.") return await ctx.send("That tag was not in the blacklisted tag list.")
else: else:
return await ctx.send("No valid option given.") return await ctx.send("No valid option given.")
return self.con.update_config(self.serverconfig)
return self.guild_settings.update(nsfw, "nsfw")


@checks.is_admin_or_mod() @checks.is_admin_or_mod()
@bot.command() @bot.command()
async def serverisanal(self, ctx): async def serverisanal(self, ctx):
"""Tells the bot where the server is anal or not. """Tells the bot where the server is anal or not.
This only changes if roxbot can do the suck and spank commands outside of the specified nsfw channels.""" This only changes if roxbot can do the suck and spank commands outside of the specified nsfw channels."""
self.serverconfig = self.con.load_config()
is_anal = self.serverconfig[self.guild_id]["is_anal"]["y/n"]
if is_anal == 0:
self.serverconfig[self.guild_id]["is_anal"]["y/n"] = 1
self.con.update_config(self.serverconfig)
return await ctx.send("I now know this server is anal")
is_anal = self.guild_settings.is_anal
if is_anal["y/n"] == 0:
is_anal["y/n"] = 1
self.guild_settings.update(is_anal, "is_anal")
await ctx.send("I now know this server is anal")
else: else:
self.serverconfig[self.guild_id]["is_anal"]["y/n"] = 0
self.con.update_config(self.serverconfig)
return await ctx.send("I now know this server is NOT anal")
is_anal["y/n"] = 0
self.guild_settings.update(is_anal, "is_anal")
await ctx.send("I now know this server is NOT anal")
return self.guild_settings.update()




def setup(bot_client): def setup(bot_client):

+ 9
- 3
main.py View File

print(server) print(server)
print("") print("")


# In the next two functions, I was gunna user bot.settings for something but I don't think it's possible.
# So while I don't use it, the function still will do their jobs of adding and removing the settings.


@bot.event @bot.event
async def on_server_join(guild): async def on_server_join(guild):
bot.settings = gs.get(guild)

bot.settings = gs.get_all(bot.guilds)


@bot.event @bot.event
async def on_server_remove(guild): async def on_server_remove(guild):
gs.remove_guild(guild) gs.remove_guild(guild)
bot.settings = gs.get(bot.guilds)
bot.settings = gs.get_all(bot.guilds)


@bot.event @bot.event
async def on_message(message): async def on_message(message):
"""
Checks if the user is blacklisted, if not, process the message for commands as usual.
:param message:
:return:
"""
if blacklisted(message.author): if blacklisted(message.author):
return return
return await bot.process_commands(message) return await bot.process_commands(message)

Loading…
Cancel
Save