Finished Config command group

This commit is contained in:
2021-07-18 23:16:58 +01:00
parent b6203566b3
commit e62342bc9a
12 changed files with 508 additions and 166 deletions

View File

@ -54,48 +54,5 @@ class Control(commands.Cog, name='Cog Control Commands'):
elif status:
await ctx.reply(f"```The Bot's configurations for the guild {ctx.guild.name} are in order. The Bot is ready to interact with the guild.```")
@commands.command(
name='lockconfig',
description='Administrator command that locks the /config commands, preventing any accidental changes to configurations.',
brief='Toggle locking /config command.',
aliases=['configlock','lock','lockdownconfig']
)
async def _lockconfig(self, ctx:commands.Context, toggle:str):
if toggle == 'on':
o = ''
if self.client.get_cog('Configuration Commands') is not None:
unloadCog(f'./{cogsDir}/slashcommands/config.py')
o = ''.join([o,'Configuration Lock turned on. `/config` command has been disabled.'])
else:
o = ''.join([o,'`/config` command has already been disabled.'])
if self.client.get_cog('Manipulate Timeslots') is not None:
unloadCog(f'./{cogsDir}/slashcommands/secondary/manipulate_timeslots.py')
o = ''.join([o,'\nTimeslot configuration sub-commands have been disabled.'])
else:
o = ''.join([o,'\nTimeslot configuration sub-commands have already been disabled.'])
await ctx.reply(f'```{o}```')
await self.client.slash.sync_all_commands()
elif toggle == 'off':
o = ''
if self.client.get_cog('Configuration Commands') is None:
loadCog(f'./{cogsDir}/slashcommands/config.py')
await self.client.slash.sync_all_commands()
o = ''.join([o,'Configuration Lock turned off. `/config` command has been re-enabled.'])
else:
o = ''.join([o,'`/config` command has already been enabled.'])
if self.client.get_cog('Manipulate Timeslots') is None:
if all([len(yaml_load(configFile)[x]['timeslots']) > 0 for x in yaml_load(configFile)]):
loadCog(f'./{cogsDir}/slashcommands/secondary/manipulate_timeslots.py')
await self.client.slash.sync_all_commands()
o = ''.join([o,'\nTimeslot configuration sub-commands have been re-enabled.'])
else:
o = ''.join([o,'\nTimeslot configuration sub-commands are not re-enabled because there are no configured timeslots for the guild.'])
else:
o = ''.join([o,'\nTimeslot configuration sub-commands have already been enabled.'])
await ctx.reply(f'```{o}```')
await self.client.slash.sync_all_commands()
else:
raise commands.CommandError('Invalid argument. `lockconfig` command only accepts the arguments `on` or `off`.')
def setup(client):
client.add_cog(Control(client))

View File

@ -1,58 +0,0 @@
import os
from dotenv import load_dotenv # Import OS variables from Dotenv file.
load_dotenv() # Load Dotenv. Delete this for production
import asyncio # Discord Py Dependency
import discord # Main Lib
from discord.ext import commands # Commands module
from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash Command Library
from discord_slash.utils.manage_commands import create_choice, create_option # Slash Command features
from deepdiff import DeepDiff
from pprint import pprint
from bot import loadCog, unloadCog, checkConfig, parseConfigCheck, yaml_load, configFile
##### Dev Cog
class Dev(commands.Cog, name='Developer Commands'):
def __init__(self, client):
self.client = client
#### Check if user is an administrator
async def cog_check(self, ctx):
for role in ctx.author.roles:
if role.permissions.administrator:
return True
return ctx.author.guild_permissions.administrator
@commands.command(
name='debug',
description='Toggles debug feature for the guild. Enter either `on` or `off`.',
brief='Toggle debug features.'
)
async def _debug(self, ctx, toggle:str):
if toggle.lower() == 'on':
loadCog(f'./debug/debug.py')
await ctx.reply(f'```Debug commands enabled. Use them carefully.```')
elif toggle.lower() == 'off':
unloadCog(f'./debug/debug.py')
await ctx.reply(f'``Debug commands disabled.``')
else:
raise commands.CommandError(message='Invalid argument.')
# await ctx.reply(f'```Invalid argument.```')
@commands.command(
name='testconfig',
description='Tests the completeness of the configuration values of the current guild by comparing it to a configuration blueprint.',
brief='Tests config values for current guild.',
aliases=['configtest']
)
async def _testconfig(self, ctx):
checkConfig(ctx.guild)
status, output = checkConfig(ctx.guild)
conf = yaml_load(configFile)
if not status:
await ctx.reply(f"```The Bot's configurations are incomplete for the guild {ctx.guild.name}. Some limited functions will still be available, but most features cannot be used until the configurations are complete.\n{parseConfigCheck(output)}\nYou can set these configuration values using the `/config` command.```")
elif status:
await ctx.reply(f"```The Bot's configurations for the guild {ctx.guild.name} are in order. The Bot is ready to interact with the guild.```")
def setup(client):
client.add_cog(Dev(client))

View File

@ -6,11 +6,12 @@ from discord.ext import commands # Commands module
from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash Command Library
from discord_slash.utils.manage_commands import create_choice, create_option, create_permission # Slash Command features
from discord_slash.model import SlashCommandPermissionType
import re
from bot import configFile, yaml_load, yaml_dump
from bot import configFile, yaml_load, yaml_dump, loadCog, unloadCog, reloadCog, cogsDir, slash
##### Configuration Cog
class Configuration(commands.Cog):
class Configuration(commands.Cog, name='Configuration Commands'):
def __init__(self, client):
self.client = client
@ -168,5 +169,117 @@ class Configuration(commands.Cog):
yaml_dump(conf, configFile)
await ctx.send(f'```Notifications for posts in the `{channel}` channel for the guild `{ctx.guild.name}` have been set to `{notifications}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='timeslots',
name='add',
description='Add a timeslot at which the Guild will host games.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
subcommand_group_description='Manages timeslots available for games on the guild.',
guild_ids=guild_ids,
options=[
create_option(
name='key',
description='Alphanumeric time code 10 chars max.',
option_type=3,
required=True,
),
create_option(
name='name',
description='A longer, descriptive name of when the timeslot is',
option_type=3,
required=True
)
]
)
async def _config_timeslots_add(self, ctx:SlashContext, key:str, name:str):
sanitisedKey = re.sub(r"\W+",'', key[:9].lower())
if not key.isalnum():
await ctx.send(f'```Key value {key} is not a valid alphanumeric time code. Sanitising to `{sanitisedKey}`.```')
conf = yaml_load(configFile)
if 'timeslots' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['timeslots'] = {}
if sanitisedKey in conf[str(ctx.guild.id)]['timeslots']:
await ctx.send(f'```Key value {sanitisedKey} has already been defined for guild `{ctx.guild.name}` for `{conf[str(ctx.guild.id)]["timeslots"][sanitisedKey]}`. Please use the `remove` or `modify` sub-commands to amend it.```')
return
conf[str(ctx.guild.id)]['timeslots'][sanitisedKey] = name
yaml_dump(conf, configFile)
await ctx.send(f'```Timeslot `{name}` with the key `{sanitisedKey}` has been added for the guild `{ctx.guild.name}`.```')
if all([len(yaml_load(configFile)[x]['timeslots']) > 0 for x in yaml_load(configFile)]):
if self.client.get_cog('Manipulate Timeslots') is None:
loadCog(f'./{cogsDir}/slashcommands/secondary/manipulate_timeslots.py')
await self.client.slash.sync_all_commands()
@cog_ext.cog_subcommand(
base='config',
subcommand_group='membership',
name='add',
description='Add a membership type for the Guild.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
subcommand_group_description='Manages the different categories of membership available to the Guild.',
guild_ids=guild_ids,
options=[
create_option(
name='name',
description='Name of membership type.',
option_type=3,
required=True,
),
create_option(
name='role_exists',
description='Does the role for this member type already exist?',
option_type=5,
required=True
),
create_option(
name='role',
description='Assign the role if it already exists.',
option_type=8,
required=False
)
]
)
async def _config_membership_add(self, ctx:SlashContext, name:str, role_exists:bool, role:discord.Role=None):
if role_exists and role is None:
await ctx.send(f'```If the role for membership type `{name}` already exists, you must assign it. If it has not been assigned, the Bot will create one.```')
return
if not role_exists and role is not None:
await ctx.send(f'```You have specified a role for `{name}` does not already exist but have also specified a role to assign. Please either assign a role if it exists, or leave it blank if does not.```')
return
conf = yaml_load(configFile)
if 'membership' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['membership'] = []
if role is not None:
if role.id in conf[str(ctx.guild.id)]['membership']:
await ctx.send(f'```The role {name} has already been assigned to a membership type for guild `{ctx.guild.name}`. Please use the `remove` sub-command to delete it or assign a different role.```')
return
if any([ctx.guild.get_role(m).name == name for m in conf[str(ctx.guild.id)]['membership']]):
await ctx.send(f'```The membership type {name} has already been assigned a role for guild `{ctx.guild.name}`. Please use the `remove` sub-command to delete the role or assign a different membership type.```')
return
if not role_exists:
r = await ctx.guild.create_role(
name=name,
permissions=discord.Permissions(read_messages=True,use_slash_commands=True),
mentionable=False
)
if role is not None:
await role.edit(
name=name,
permissions=discord.Permissions(read_messages=True,use_slash_commands=True),
mentionable=False,
reason=f'`/config membership add` command issued by {ctx.author.display_name}'
)
conf[str(ctx.guild.id)]['membership'].append(role.id) if role is not None else conf[str(ctx.guild.id)]['membership'].append(r.id)
yaml_dump(conf, configFile)
await ctx.send(f'```Membership type `{role.name if role is not None else r.name}` has been registered for the guild `{ctx.guild.name}`.```')
if all([len(yaml_load(configFile)[x]['membership']) > 0 for x in yaml_load(configFile)]):
if self.client.get_cog('Edit Membership') is None:
loadCog(f'./{cogsDir}/slashcommands/secondary/edit_membership.py')
await self.client.slash.sync_all_commands()
def setup(client):
client.add_cog(Configuration(client))

View File

@ -0,0 +1,18 @@
import os # OS Locations
import yaml # YAML parser for Bot config files
import asyncio # Discord Py Dependency
import discord # Main Lib
from discord.ext import commands # Commands module
from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash Command Library
from discord_slash.utils.manage_commands import create_choice, create_option, create_permission # Slash Command features
from discord_slash.model import SlashCommandPermissionType
from bot import configFile, yaml_load, yaml_dump
##### Game Management Commands
class Game_Management(commands.Cog, name='Game Management Commands'):
def __init__(self, client):
self.client = client
def setup(client):
client.add_cog(Game_Management(client))

View File

@ -0,0 +1,95 @@
import os # OS Locations
import yaml # YAML parser for Bot config files
import asyncio # Discord Py Dependency
import discord # Main Lib
from discord.ext import commands # Commands module
from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash Command Library
from discord_slash.utils.manage_commands import create_choice, create_option, create_permission # Slash Command features
from discord_slash.model import SlashCommandPermissionType
from discord_slash.client import SlashCommand
from bot import configFile, yaml_load, yaml_dump, reloadCog, cogsDir, unloadCog
#### Separate cog to remove and modify membership registrations that is reloaded if timeslots are added or removed
class EditMembership(commands.Cog, name='Edit Membership'):
def __init__(self, client):
self.client = client
#### Only emable for guilds with registered membership types
#### N.B.: if there are no guilds with any membership types, then this will throw an exception.
#### The solution I have implemented is that this will be classed as a 'secondary' cog: it will not be loaded by default, and will only be loaded if at least one guild has a membership role registered.
#### If the deletion of membership roles removes memberships from all guilds, it will unload the cog and delete the commands until a new membership role is defined.
guild_ids=[int(guildKey) for guildKey in yaml_load(configFile) if len(yaml_load(configFile)[guildKey]['membership']) > 0]
conf = yaml_load(configFile)
permissions = {}
for guildID in guild_ids:
permissions[guildID] = []
permissions[guildID].append(create_permission(id=conf[str(guildID)]['owner'],id_type=SlashCommandPermissionType.USER,permission=True))
for admin in conf[str(guildID)]['roles']['admin']:
permissions[guildID].append(create_permission(id=admin,id_type=SlashCommandPermissionType.ROLE,permission=True))
@cog_ext.cog_subcommand(
base='config',
subcommand_group='membership',
name='remove',
description='Remove a registered membership role.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Adds a time slot available to the channel for games.',
guild_ids=guild_ids,
options=[
create_option(
name='role',
description='The role of the membership type you want to delete.',
option_type=8,
required=True
)
]
)
async def _config_membership_remove(self, ctx:SlashContext, role:discord.Role):
conf = yaml_load(configFile)
if 'membership' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['timeslots'] = {}
if role.id in conf[str(ctx.guild.id)]['membership']:
conf[str(ctx.guild.id)]['membership'].remove(role.id)
yaml_dump(conf, configFile)
await ctx.send(f'```Membership type {role.name} has been deleted for the guild `{ctx.guild.name}`.```')
await role.delete(reason=f'`/config membership remove` command issued by `{ctx.author.display_name}`.')
if not all([len(yaml_load(configFile)[x]['membership']) > 0 for x in yaml_load(configFile)]):
unloadCog(f'./{cogsDir}/slashcommands/secondary/edit_membership.py')
await self.client.slash.sync_all_commands()
elif len(conf[str(ctx.guild.id)]['membership']) > 0:
output = f'Role `{role.name}` is not a registered membership role in the guild `{ctx.guild.name}`. Please select a valid membership role.\n\n Eligible roles are:\n'
for m in conf[str(ctx.guild.id)]['membership']:
output = ''.join([output, f'\n{ctx.guild.get_role(m).name}'])
await ctx.send(''.join(['```',output,'```']))
else:
await ctx.send(f'```No roles have been registered as membership types for the guild `{ctx.guild.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='membership',
name='list',
description='List the existing game memberships on the server.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Adds a time slot available to the channel for games.',
guild_ids=guild_ids,
)
async def _config_timeslots_list(self, ctx:SlashContext):
conf = yaml_load(configFile)
if 'membership' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['membership'] = {}
if len(conf[str(ctx.guild.id)]['membership']) > 0:
output = f'The following membership types have been registered for the guild {ctx.guild.name}:\n'
for m in conf[str(ctx.guild.id)]['membership']:
output = ''.join([output, f'\n{ctx.guild.get_role(m).name}'])
await ctx.send(''.join(['```',output,'```']))
else:
await ctx.send(f'```No roles have been registered as membership types for the guild `{ctx.guild.name}`.```')
def setup(client):
client.add_cog(EditMembership(client))

View File

@ -0,0 +1,135 @@
import os # OS Locations
import yaml # YAML parser for Bot config files
import asyncio # Discord Py Dependency
import discord # Main Lib
from discord.ext import commands # Commands module
from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash Command Library
from discord_slash.utils.manage_commands import create_choice, create_option, create_permission # Slash Command features
from discord_slash.model import SlashCommandPermissionType
from discord_slash.client import SlashCommand
from bot import configFile, yaml_load, yaml_dump, reloadCog, cogsDir, unloadCog
#### Separate cog to remove and modify timeslots that is reloaded if timeslots are added or removed
class ManipulateTimeslots(commands.Cog, name='Manipulate Timeslots'):
def __init__(self, client):
self.client = client
#### Only emable for guilds with timeslots
#### N.B.: if there are no guilds with any timeslots, then this will throw an exception.
#### The solution I have implemented is that this will be classed as a 'secondary' cog: it will not be loaded by default, and will only be loaded if at least one guild has a timeslot configured.
#### If the deletion of timeslots removes timeslots from all guilds, it will unload the cog and delete the commands until a new timeslot is defined.
guild_ids=[int(guildKey) for guildKey in yaml_load(configFile) if len(yaml_load(configFile)[guildKey]['timeslots']) > 0]
conf = yaml_load(configFile)
permissions = {}
for guildID in guild_ids:
permissions[guildID] = []
permissions[guildID].append(create_permission(id=conf[str(guildID)]['owner'],id_type=SlashCommandPermissionType.USER,permission=True))
for admin in conf[str(guildID)]['roles']['admin']:
permissions[guildID].append(create_permission(id=admin,id_type=SlashCommandPermissionType.ROLE,permission=True))
@cog_ext.cog_subcommand(
base='config',
subcommand_group='timeslots',
name='remove',
description='Remove a configured game timeslot.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Adds a time slot available to the channel for games.',
guild_ids=guild_ids,
options=[
create_option(
name='timeslot',
description='The timeslot you wish to delete.',
option_type=3,
required=True
)
]
)
async def _config_timeslots_remove(self, ctx:SlashContext, timeslot:str):
conf = yaml_load(configFile)
if 'timeslots' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['timeslots'] = {}
if timeslot in conf[str(ctx.guild.id)]['timeslots']:
await ctx.send(f'```Timeslot {conf[str(ctx.guild.id)]["timeslots"][timeslot]} with the key `{timeslot}` has been deleted for the guild `{ctx.guild.name}`.```')
conf[str(ctx.guild.id)]['timeslots'].pop(timeslot, None)
yaml_dump(conf, configFile)
if not all([len(yaml_load(configFile)[x]['timeslots']) > 0 for x in yaml_load(configFile)]):
unloadCog(f'./{cogsDir}/slashcommands/secondary/manipulate_timeslots.py')
await self.client.slash.sync_all_commands()
elif len(conf[str(ctx.guild.id)]['timeslots']) > 0:
output = f'```Timeslot `{timeslot}` was not found in the guild `{ctx.guild.name}`. Please enter a valid key.\n\n Available timeslots are:\n(key): (timeslot name)'
for c in conf[str(ctx.guild.id)]['timeslots']:
output = ''.join([output, f'\n {c}: {conf[str(ctx.guild.id)]["timeslots"][c]}'])
await ctx.send(''.join([output,'```']))
else:
await ctx.send(f'```No timeslots have been defined for the guild `{ctx.guild.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='timeslots',
name='modify',
description='Modify the value of a configured gametime slot.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Adds a time slot available to the channel for games.',
guild_ids=guild_ids,
options=[
create_option(
name='key',
description='Key of timeslot being modified',
option_type=3,
required=True,
),
create_option(
name='name',
description='New value for timeslot name',
option_type=3,
required=True
)
]
)
async def _config_timeslots_modify(self, ctx:SlashContext, key:str, name:str):
conf = yaml_load(configFile)
if 'timeslots' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['timeslots'] = {}
if key in conf[str(ctx.guild.id)]['timeslots']:
await ctx.send(f'```Timeslot {conf[str(ctx.guild.id)]["timeslots"][key]} with the key `{key}` has been renamed to {name} for the guild `{ctx.guild.name}`.```')
conf[str(ctx.guild.id)]['timeslots'][key] = name
yaml_dump(conf, configFile)
elif len(conf[str(ctx.guild.id)]['timeslots']) > 0:
output = f'```Timeslot `{key}` was not found in the guild `{ctx.guild.name}`. Please enter a valid key.\n\n Available timeslots are:\n(key): (timeslot name)'
for c in conf[str(ctx.guild.id)]['timeslots']:
output = ''.join([output, f'\n {c}: {conf[str(ctx.guild.id)]["timeslots"][c]}'])
await ctx.send(''.join([output,'```']))
else:
await ctx.send(f'```No timeslots have been defined for the guild `{ctx.guild.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='timeslots',
name='list',
description='List the existing game timeslots on the server.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Adds a time slot available to the channel for games.',
guild_ids=guild_ids,
)
async def _config_timeslots_list(self, ctx:SlashContext):
conf = yaml_load(configFile)
if 'timeslots' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['timeslots'] = {}
if len(conf[str(ctx.guild.id)]['timeslots']) > 0:
output = f'```The following timeslots have been configured for the guild {ctx.guild.name}:\n(key): (timeslot name)'
for c in conf[str(ctx.guild.id)]['timeslots']:
output = ''.join([output, f'\n {c}: {conf[str(ctx.guild.id)]["timeslots"][c]}'])
await ctx.send(''.join([output,'```']))
else:
await ctx.send(f'```No timeslots have been defined for the guild `{ctx.guild.name}`.```')
def setup(client):
client.add_cog(ManipulateTimeslots(client))