Started writing /commands.

Completed channel group of config subcommands
Fixed bugs in config initialisation function
This commit is contained in:
2021-07-17 13:56:04 +01:00
parent 51a01bab49
commit 78bc73c023
11 changed files with 259 additions and 41 deletions

View File

@ -9,7 +9,14 @@ from bot import configFile, yaml_load, yaml_dump
class Prefix(commands.Cog, name='Server Command Prefix'):
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 = 'changeprefix',
aliases = ['prefix'],
@ -20,7 +27,7 @@ class Prefix(commands.Cog, name='Server Command Prefix'):
conf = yaml_load(configFile)
conf[str(ctx.guild.id)]['prefix'] = prefix.lower()
yaml_dump(conf, configFile)
await ctx.send(f"`{self.client.user.name}`'s prefix for native bot commands has been changed to `{prefix}` for the guild `{ctx.guild.name}`.\n`Note: This will not affect /commands.`")
await ctx.send(f"```{self.client.user.name}'s prefix for native bot commands has been changed to `{prefix}` for the guild `{ctx.guild.name}`.\n\nNote: This will not affect /commands.```")
def setup(client):
client.add_cog(Prefix(client))

View File

@ -16,6 +16,13 @@ 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`.',

View File

@ -16,7 +16,10 @@ class on_command_error(commands.Cog, name='On Command Error'):
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, discord.DiscordException):
if isinstance(error, commands.CheckFailure):
if isinstance(error, commands.CommandNotFound):
print(f'Error: User {ctx.author.name}#{ctx.author.discriminator} / {ctx.author.display_name} entered an invalid command <{ctx.message.clean_content}> in the guild {ctx.guild.name}.')
await ctx.reply(f'```Error: This is not a valid command.```')
elif isinstance(error, commands.CheckFailure):
print(f'Error: User {ctx.author.name}#{ctx.author.discriminator} / {ctx.author.display_name} is not authorised to issue the command <{ctx.command.name}> in the guild {ctx.guild.name}.')
await ctx.reply(f'```Error: You are not authorised to issue this command.```')
else:

View File

@ -7,7 +7,7 @@ from discord_slash import SlashCommand, SlashContext, cog_ext, utils # Slash C
from discord_slash.utils.manage_commands import create_choice, create_option # Slash Command features
import logging
# logger and handler
from bot import checkConfig, clearConfig, configFile, parseConfigCheck, setConfig, yaml_dump, yaml_load
from bot import checkConfig, clearConfig, configFile, parseConfigCheck, setConfig, yaml_dump, yaml_load, loadCogs, unloadCogs
#### Actions for the Bot to take once it is ready to interact with commands.
class on_ready(commands.Cog, name='On Ready Events'):
@ -17,6 +17,9 @@ class on_ready(commands.Cog, name='On Ready Events'):
@commands.Cog.listener()
async def on_ready(self):
async def test(self):
await self.client.get_channel(865348933022515220).send('Foo')
#### Create any missing config entries for guilds
for guild in self.client.guilds:
setConfig(guild)
@ -32,6 +35,12 @@ class on_ready(commands.Cog, name='On Ready Events'):
conf = yaml_load(configFile)
if not status:
await guild.get_channel(conf[str(guild.id)]['channels']['mod']).send(f"```The Bot's configurations are incomplete for the guild `{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.```")
# #### Reload the /commands after the configs have finished loading.
# unloadCogs('slashcommands')
# loadCogs('slashcommands')
await test(self)
def setup(client):
client.add_cog(on_ready(client))

View File

@ -0,0 +1,36 @@
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 # Slash Command features
import logging
# logger and handler
from bot import configFile, yaml_load, yaml_dump
#### Error Handler Event Listener for Slash Command Errors
class on_slash_command_error(commands.Cog, name='On Command Error'):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_slash_command_error(self, ctx:SlashContext, error):
if isinstance(error, Exception):
await ctx.send(
content='```Invalid Command: {error}```',
tts=True,
hidden=True,
delete_after=10,
)
# if isinstance(error, commands.CommandNotFound):
# print(f'Error: User {ctx.author.name}#{ctx.author.discriminator} / {ctx.author.display_name} entered an invalid command <{ctx.message.clean_content}> in the guild {ctx.guild.name}.')
# await ctx.reply(f'```Error: This is not a valid command.```')
# elif isinstance(error, commands.CheckFailure):
# print(f'Error: User {ctx.author.name}#{ctx.author.discriminator} / {ctx.author.display_name} is not authorised to issue the command <{ctx.command.name}> in the guild {ctx.guild.name}.')
# await ctx.reply(f'```Error: You are not authorised to issue this command.```')
# else:
# print(f'User {ctx.author.name}#{ctx.author.discriminator} / {ctx.author.display_name} received error: "{error}" when attempting to issue command <{ctx.command.name}> in the guild {ctx.guild.name}.')
# await ctx.reply(f'```Error: {error}```')
def setup(client):
client.add_cog(on_slash_command_error(client))

View File

@ -4,32 +4,163 @@ 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 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
##### Configuration Cog
class Configuration(commands.Cog):
def __init__(self, client):
self.client = client
guild_ids=[int(guildKey) for guildKey in yaml_load(configFile)]
permissions = {}
conf = yaml_load(configFile)
for guildStr in conf:
permissions[int(guildStr)] = []
permissions[int(guildStr)].append(create_permission(id=conf[guildStr]['owner'],id_type=SlashCommandPermissionType.USER,permission=True))
for admin in conf[guildStr]['roles']['admin']:
permissions[int(guildStr)].append(create_permission(id=admin,id_type=SlashCommandPermissionType.ROLE,permission=True))
@cog_ext.cog_slash(
# base='botrole',
# subcommand_group='configure',
name='configure',
description='Parameter to define the role assigned to the dice bots.',
# base_description='Command to configure the various guild parameters.',
# subcommand_group_description='These are configuration commands to set up the various guild parameters.',
guild_ids=guild_ids
# options=[
# create_option(
# name='botrole',
# description='The role that the dice bots are assigned in order to access the text channels.'
# type=8,
# required=True
# )
# ]
name='hello',
description='Test command to see if registration works.',
guild_ids=guild_ids,
options=[
create_option(
name='input',
description='Choose a phrase that best goes with the opening Hello',
option_type=3,
required=True,
choices=[
create_choice(
name='...there',
value='there'
),
create_choice(
name='...world!',
value='world'
),
create_choice(
name='...beautiful!',
value='beautiful'
)
],
)
]
)
async def _configure(self, ctx:SlashContext, option):
await ctx.send(f'The `botrole` for the guild `{ctx.guild.name}` has been set to `{option}`.')
async def _hello(self, ctx:SlashContext, input):
await ctx.send(f'{input}')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='role',
name='bot',
description='Designate the role on the guild which the dice bots use to access game text channels.',
base_description='Commands for configuring the various parameters of the Guild',
base_default_permission=False,
base_permissions=permissions,
subcommand_group_description='Designates the various key command roles for the guild.',
guild_ids=guild_ids,
options=[
create_option(
name='role',
description='The role assigned to dice bots to access game channels.',
option_type=8,
required=True
)
]
)
async def _config_role_bot(self, ctx:SlashContext, role:discord.Role):
conf = yaml_load(configFile)
if 'roles' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['roles'] = {}
conf[str(ctx.guild.id)]['roles']['bots'] = int(role.id)
yaml_dump(conf, configFile)
await ctx.send(f'```The `botrole` for the guild `{ctx.guild.name}` has been set to `{role.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='channel',
name='signup',
description='Designate the channel where members can post their sign-up confirmation.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
subcommand_group_description='Designates the various key Bot channels for the guild.',
guild_ids=guild_ids,
options=[
create_option(
name='channel',
description='The channel assigned for members to verify their membership.',
option_type=7,
required=True
)
]
)
async def _config_channel_signup(self, ctx:SlashContext, channel:discord.TextChannel):
conf = yaml_load(configFile)
if 'channels' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['channels'] = {}
conf[str(ctx.guild.id)]['channels']['signup'] = int(channel.id)
yaml_dump(conf, configFile)
await ctx.send(f'```The `signup` channel for the guild `{ctx.guild.name}` has been set to `{channel.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='channel',
name='modlog',
description='Designate the channel for bot to post notifications for the admins.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Designates the various key Bot channels for the guild.',
guild_ids=guild_ids,
options=[
create_option(
name='channel',
description='The channel assigned for moderation notifications.',
option_type=7,
required=True
)
]
)
async def _config_channel_mod(self, ctx:SlashContext, channel:discord.TextChannel):
conf = yaml_load(configFile)
if 'channels' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['channels'] = {}
conf[str(ctx.guild.id)]['channels']['mod'] = int(channel.id)
yaml_dump(conf, configFile)
await ctx.send(f'```The `moderation log` channel for the guild `{ctx.guild.name}` has been set to `{channel.name}`.```')
@cog_ext.cog_subcommand(
base='config',
subcommand_group='channel',
name='help',
description='Designate the hel channel which the bot will monitor for member queries.',
# base_description='Commands for configuring the various parameters of the Guild',
# base_default_permission=False,
# base_permissions=permissions,
# subcommand_group_description='Designates the various key Bot channels for the guild.',
guild_ids=guild_ids,
options=[
create_option(
name='channel',
description='The channel monitored by the Bot for help queries.',
option_type=7,
required=True
)
]
)
async def _config_channel_help(self, ctx:SlashContext, channel:discord.TextChannel):
conf = yaml_load(configFile)
if 'channels' not in conf[str(ctx.guild.id)]:
conf[str(ctx.guild.id)]['channels'] = {}
conf[str(ctx.guild.id)]['channels']['help'] = int(channel.id)
yaml_dump(conf, configFile)
await ctx.send(f'```The `help` channel for the guild `{ctx.guild.name}` has been set to `{channel.name}`.```')
def setup(client):
client.add_cog(Configuration(client))