diff --git a/CHANGELOG.md b/CHANGELOG.md index 571ba0db..9b83a8dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to KoalaBot will be documented in this file. A lot of these commands will only be available to administrators ## [Unreleased] +### 29-07-2021 +Added new default behaviour for welcome messages, they do not happen by default unless one is updated with a welcome message. + +`k!setup` This blocks all possible sensitive commands until the command is called in the guild by an admin + +`k!verifyDM ` This toggles between having the verification welcome DM on or off ### Other - Testing updated to use builders in dpytest 0.5.0 ### Colour Role diff --git a/KoalaBot.py b/KoalaBot.py index a27b84f1..979ff815 100644 --- a/KoalaBot.py +++ b/KoalaBot.py @@ -97,6 +97,13 @@ def is_admin(ctx): return ctx.author.guild_permissions.administrator or is_dpytest +def terms_agreed(ctx): + """ + Global check to block access to commands if legal terms aren't agreed with + """ + return DBManager.fetch_guild_setup_status(database_manager, ctx.guild.id) != 0 + + def is_dm_channel(ctx): return isinstance(ctx.channel, discord.channel.DMChannel) @@ -160,6 +167,16 @@ async def on_command_error(ctx, error): elif isinstance(error, commands.CommandOnCooldown): await ctx.send(embed=error_embed(description=f"{ctx.author.mention}, this command is still on cooldown for " f"{str(error.retry_after)}s.")) + elif isinstance(error, commands.CheckFailure): + if database_manager.fetch_guild_setup_status(ctx.guild.id) == 0: + await ctx.send(embed=error_embed(description="In order to use this command. You must agree to the Terms & Conditions " \ + "of KoalaBot and confirm you have read and understand our Privacy Policy. " \ + "For legal documents relating to this, please view the following link: http://legal.koalabot.uk/ " \ + "Use k!setup to agree.")) + elif not is_admin(ctx): + await ctx.send(embed=error_embed(description="You do not have access to this command as you must be an admin")) + else: + await ctx.send(embed=error_embed(description="Have you enabled the extension")) else: await ctx.send(embed=error_embed(description=error)) diff --git a/cogs/Announce.py b/cogs/Announce.py index 8db84936..6405ee39 100644 --- a/cogs/Announce.py +++ b/cogs/Announce.py @@ -25,8 +25,6 @@ MAX_MESSAGE_LENGTH = 2000 - - def announce_is_enabled(ctx): """ A command used to check if the guild has enabled announce @@ -131,6 +129,7 @@ async def announce(self, ctx): if ctx.invoked_subcommand is None: await ctx.send(f"Please use `{KoalaBot.COMMAND_PREFIX}help announce` for more information") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="create") async def create(self, ctx): @@ -166,6 +165,7 @@ async def create(self, ctx): await ctx.send(embed=self.construct_embed(ctx.guild)) await ctx.send(self.receiver_msg(ctx.guild)) + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="changeTitle") async def change_title(self, ctx): @@ -185,6 +185,7 @@ async def change_title(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="changeContent") async def change_content(self, ctx): @@ -207,6 +208,7 @@ async def change_content(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="addRole", aliases=["add"]) async def add_role(self, ctx): @@ -216,7 +218,8 @@ async def add_role(self, ctx): :return: """ if self.has_active_msg(ctx.guild.id): - await ctx.send("Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") + await ctx.send( + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") message, channel = await wait_for_message(self.bot, ctx) if not message: await channel.send("Okay, I'll cancel the command.") @@ -230,6 +233,7 @@ async def add_role(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="removeRole", aliases=["remove"]) async def remove_role(self, ctx): @@ -239,7 +243,8 @@ async def remove_role(self, ctx): :return: """ if self.has_active_msg(ctx.guild.id): - await ctx.send("Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") + await ctx.send( + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") message, channel = await wait_for_message(self.bot, ctx) if not message: await channel.send("Okay, I'll cancel the command.") @@ -252,6 +257,7 @@ async def remove_role(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="preview") async def preview(self, ctx): @@ -266,6 +272,7 @@ async def preview(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="send") async def send(self, ctx): @@ -289,6 +296,7 @@ async def send(self, ctx): else: await ctx.send("There is currently no active announcement") + @commands.check(KoalaBot.terms_agreed) @commands.check(announce_is_enabled) @announce.command(name="cancel") async def cancel(self, ctx): diff --git a/cogs/BaseCog.py b/cogs/BaseCog.py index f51504a7..73d5b548 100644 --- a/cogs/BaseCog.py +++ b/cogs/BaseCog.py @@ -171,6 +171,7 @@ async def unload_cog(self, ctx, extension): await ctx.send(f'{extension} Cog Unloaded') @commands.command(name="enableExt", aliases=["enable_koala_ext"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) async def enable_koala_ext(self, ctx, koala_extension): """ @@ -195,6 +196,7 @@ async def enable_koala_ext(self, ctx, koala_extension): await ctx.send(embed=embed) @commands.command(name="disableExt", aliases=["disable_koala_ext"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) async def disable_koala_ext(self, ctx, koala_extension): """ @@ -215,6 +217,7 @@ async def disable_koala_ext(self, ctx, koala_extension): await ctx.send(embed=embed) @commands.command(name="listExt", aliases=["list_koala_ext"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) async def list_koala_ext(self, ctx): """ diff --git a/cogs/ColourRole.py b/cogs/ColourRole.py index 6c223d58..54490ba0 100644 --- a/cogs/ColourRole.py +++ b/cogs/ColourRole.py @@ -109,6 +109,7 @@ def get_colour_from_hex_str(self, colour_str: str) -> discord.Colour: @commands.cooldown(1, 15, commands.BucketType.member) @commands.check(is_allowed_to_change_colour) @commands.check(colour_is_enabled) + @commands.check(KoalaBot.terms_agreed) @commands.command(name="customColour", aliases=["custom_colour", "customColor", "custom_color"]) async def custom_colour(self, ctx: commands.Context, colour_str: str): """ @@ -399,6 +400,7 @@ def role_already_exists(ctx: commands.Context, colour_str: str): return role_name in [role.name for role in guild.roles] @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(colour_is_enabled) @commands.command(name="listProtectedRoleColours", aliases=["list_protected_role_colours", "listInvalidCustomColours", "listProtectedRoleColors", @@ -419,6 +421,7 @@ async def list_protected_role_colours(self, ctx: commands.Context): await ctx.send(msg[:-1]) @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(colour_is_enabled) @commands.command(name="listCustomColourAllowedRoles", aliases=["list_custom_colour_allowed_roles"]) @@ -468,6 +471,7 @@ def get_protected_roles(self, guild: discord.Guild) -> List[discord.Role]: @commands.check(KoalaBot.is_admin) @commands.check(colour_is_enabled) + @commands.check(KoalaBot.terms_agreed) @commands.command(name="addProtectedRoleColour", aliases=["add_protected_role_colour", "addInvalidCustomColourRole", "addInvalidCustomColorRole", "addProtectedRoleColor"]) @@ -488,6 +492,7 @@ async def add_protected_role_colour(self, ctx: commands.Context, *, role_str: st await self.rearrange_custom_colour_role_positions(ctx.guild) @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(colour_is_enabled) @commands.command(name="removeProtectedRoleColour", aliases=["remove_protected_role_colour", "removeProtectedRoleColor", @@ -509,6 +514,7 @@ async def remove_protected_role_colour(self, ctx: commands.Context, *, role_str: await self.rearrange_custom_colour_role_positions(ctx.guild) @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(colour_is_enabled) @commands.command(name="addCustomColourAllowedRole", aliases=["add_custom_colour_allowed_role", "addCustomColorAllowedRole"]) @@ -528,6 +534,7 @@ async def add_custom_colour_allowed_role(self, ctx: commands.Context, *, role_st await ctx.send(f"Added {role.mention} to the list of roles allowed to have a custom colour.") @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(colour_is_enabled) @commands.command(name="removeCustomColourAllowedRole", aliases=["remove_custom_colour_allowed_role", "removeCustomColorAllowedRole"]) diff --git a/cogs/IntroCog.py b/cogs/IntroCog.py index 3af598fa..bef14a38 100644 --- a/cogs/IntroCog.py +++ b/cogs/IntroCog.py @@ -25,12 +25,13 @@ BASE_LEGAL_MESSAGE = """This server utilizes KoalaBot. In joining this server, you agree to the Terms & Conditions of KoalaBot and confirm you have read and understand our Privacy Policy. For legal documents relating to this, please view the following link: http://legal.koalabot.uk/""" -DEFAULT_WELCOME_MESSAGE = "Hello. This is a default welcome message because the guild that this came from did not configure a welcome message! Please see below." +DEFAULT_WELCOME_MESSAGE = "" # Variables DBManager = KoalaDBManager.KoalaDBManager(KoalaBot.DATABASE_PATH, KoalaBot.DB_KEY) -def wait_for_message(bot: discord.Client, ctx: commands.Context, timeout=60.0) -> (discord.Message, discord.TextChannel): +def wait_for_message(bot: discord.Client, ctx: commands.Context, timeout=60.0) -> ( +discord.Message, discord.TextChannel): try: confirmation = bot.wait_for('message', timeout=timeout, check=lambda message: message.author == ctx.author) return confirmation @@ -72,7 +73,11 @@ def get_guild_welcome_message(guild_id: int): msg = DBManager.fetch_guild_welcome_message(guild_id) if msg is None: msg = DBManager.new_guild_welcome_message(guild_id) - return f"{msg}\r\n{BASE_LEGAL_MESSAGE}" + return msg + elif msg == "": + return msg + else: + return f"{msg}\r\n{BASE_LEGAL_MESSAGE}" def get_non_bot_members(guild: discord.Guild): @@ -88,25 +93,49 @@ class IntroCog(commands.Cog, name="KoalaBot"): """ def __init__(self, bot): + self.bot = bot + async def send_setup_message(self, guild): + """ + On bot joining guild, sends the basic legal information to the server, blocks access to the bot commands until + legal terms are agreed + :param guild: Guild object of the guild you are sending the setup message to. + """ + setup_message = "In order for KoalaBot to store data on this server, you must agree to the Terms & Conditions " \ + "of KoalaBot and confirm you have read and understand our Privacy Policy. " \ + "For legal documents relating to this, please view the following link: http://legal.koalabot.uk/ " \ + "Use k!setup to agree" + for channel in guild.text_channels: + if channel.permissions_for(guild.me).send_messages: + await channel.send(setup_message) + break + @commands.Cog.listener() async def on_guild_join(self, guild: discord.Guild): """ On bot joining guild, add this guild to the database of guild welcome messages. + Also sets up the status of the guild :param guild: Guild KoalaBot just joined """ DBManager.new_guild_welcome_message(guild.id) + DBManager.insert_setup_status(guild.id) KoalaBot.logger.info(f"KoalaBot joined new guild, id = {guild.id}, name = {guild.name}.") + await self.send_setup_message(guild) @commands.Cog.listener() async def on_member_join(self, member: discord.Member): """ - On member joining guild, send DM to member with welcome message. + On member joining guild, send DM to member with welcome message, if the server opts for this option :param member: Member which just joined guild """ - await KoalaBot.dm_group_message([member], get_guild_welcome_message(member.guild.id)) - KoalaBot.logger.info(f"New member {member.name} joined guild id {member.guild.id}. Sent them welcome message.") + if get_guild_welcome_message(member.guild.id) == "" or get_guild_welcome_message(member.guild.id) is None: + KoalaBot.logger.info( + f"New member {member.name} joined guild id {member.guild.id}. No welcome message set up.") + else: + await KoalaBot.dm_group_message([member], get_guild_welcome_message(member.guild.id)) + KoalaBot.logger.info( + f"New member {member.name} joined guild id {member.guild.id}. Sent them welcome message.") @commands.Cog.listener() async def on_guild_remove(self, guild: discord.Guild): @@ -114,9 +143,11 @@ async def on_guild_remove(self, guild: discord.Guild): On bot leaving guild, remove the guild from the database of guild welcome messages :param guild: Guild KoalaBot just left """ + DBManager.remove_guild_status(guild.id) count = DBManager.remove_guild_welcome_message(guild.id) KoalaBot.logger.info( - f"KoalaBot left guild, id = {guild.id}, name = {guild.name}. Removed {count} rows from GuildWelcomeMessages") + f"KoalaBot left guild, id = {guild.id}, name = {guild.name}. Removed {count} rows from GuildWelcomeMessages" + f"Removed guild status for id = {guild.id}") @commands.cooldown(1, 60, commands.BucketType.guild) @commands.check(KoalaBot.is_admin) @@ -145,13 +176,15 @@ async def send_welcome_message(self, ctx): return False @commands.cooldown(1, 60, commands.BucketType.guild) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.command(name="welcomeUpdateMsg", aliases=["update_welcome_message"]) async def update_welcome_message(self, ctx, *, new_message: str): - """ + """` Allows admins to change their customisable part of the welcome message of a guild. Has a 60 second cooldown per guild. + :param ctx: Context of the command :param new_message: New customised part of the welcome message """ @@ -175,6 +208,7 @@ async def update_welcome_message(self, ctx, *, new_message: str): except None: await ctx.send("Something went wrong, please contact the bot developers for support.") else: + await ctx.send("Okay, I won't update the welcome message then.") @commands.check(KoalaBot.is_admin) @@ -190,6 +224,15 @@ async def on_update_error(self, ctx, error): if isinstance(error, discord.ext.commands.MissingRequiredArgument): await ctx.send('Please put in a welcome message to update to.') + @commands.check(KoalaBot.is_admin) + @commands.command() + async def setup(self, ctx): + """ + Allows access to configure the bot, once legal terms are agreed + """ + DBManager.update_guild_setup_status(ctx.guild.id) + await ctx.send("Terms and Conditions agreed, you can now configure the bot") + def setup(bot: KoalaBot) -> None: """ diff --git a/cogs/ReactForRole.py b/cogs/ReactForRole.py index 34a20ff6..9b8eb613 100644 --- a/cogs/ReactForRole.py +++ b/cogs/ReactForRole.py @@ -61,6 +61,7 @@ def __init__(self, bot: discord.Client): @commands.check(KoalaBot.is_guild_channel) @commands.check(KoalaBot.is_admin) + @commands.check(KoalaBot.terms_agreed) @commands.check(rfr_is_enabled) @commands.group(name="rfr", aliases=["reactForRole", "react_for_role"]) async def react_for_role_group(self, ctx: commands.Context): @@ -127,6 +128,7 @@ def attachment_img_content_type(mime: Optional[str]): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @react_for_role_group.command(name="create", aliases=["createMsg", "createMessage"]) async def rfr_create_message(self, ctx: commands.Context): """ @@ -201,6 +203,7 @@ async def rfr_create_message(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @react_for_role_group.command(name="delete", aliases=["deleteMsg", "deleteMessage"]) async def rfr_delete_message(self, ctx: commands.Context): """ @@ -229,6 +232,7 @@ async def edit_group(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="description", aliases=["desc"]) async def rfr_edit_description(self, ctx: commands.Context): """ @@ -255,6 +259,7 @@ async def rfr_edit_description(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="title") async def rfr_edit_title(self, ctx: commands.Context): """ @@ -281,6 +286,7 @@ async def rfr_edit_title(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="thumbnail", aliases=["image", "picture"]) async def rfr_edit_thumbnail(self, ctx: commands.Context): """ @@ -321,6 +327,7 @@ async def rfr_edit_thumbnail(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="inline") async def rfr_edit_inline(self, ctx: commands.Context): """ @@ -398,6 +405,7 @@ async def rfr_edit_inline(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="fixEmbed") async def rfr_fix_embed(self, ctx: commands.Context): """ @@ -442,6 +450,7 @@ async def rfr_fix_embed(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="addRoles") async def rfr_add_roles_to_msg(self, ctx: commands.Context): """ @@ -531,6 +540,7 @@ async def rfr_add_roles_to_msg(self, ctx: commands.Context): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @edit_group.command(name="removeRoles") async def rfr_remove_roles_from_msg(self, ctx: commands.Context): """ @@ -629,6 +639,7 @@ async def rfr_remove_roles_from_msg(self, ctx: commands.Context): @commands.Cog.listener() @commands.check(KoalaBot.is_guild_channel) + @commands.check(KoalaBot.terms_agreed) async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent): """ Event listener for adding a reaction. Doesn't need message to be in loaded cache. @@ -683,6 +694,7 @@ async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent): @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @react_for_role_group.command("addRequiredRole") async def rfr_add_guild_required_role(self, ctx: commands.Context, role_str: str): """ @@ -722,6 +734,7 @@ async def rfr_remove_guild_required_role(self, ctx: commands.Context, role_str: @commands.check(KoalaBot.is_admin) @commands.check(rfr_is_enabled) + @commands.check(KoalaBot.terms_agreed) @react_for_role_group.command("listRequiredRoles") async def rfr_list_guild_required_roles(self, ctx: commands.Context): """ diff --git a/cogs/TextFilter.py b/cogs/TextFilter.py index 4bd5cd20..6afed619 100644 --- a/cogs/TextFilter.py +++ b/cogs/TextFilter.py @@ -52,6 +52,7 @@ def __init__(self, bot, database_manager=None): @commands.command(name="filter", aliases=["filter_word"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def filter_new_word(self, ctx, word, filter_type="banned", too_many_arguments=None): """ Adds a new word to the filtered text list @@ -73,6 +74,7 @@ async def filter_new_word(self, ctx, word, filter_type="banned", too_many_argume @commands.command(name="filterRegex", aliases=["filter_regex"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def filter_new_regex(self, ctx, regex, filter_type="banned", too_many_arguments=None): """ Adds a new regex to the filtered text list @@ -100,6 +102,7 @@ async def filter_new_regex(self, ctx, regex, filter_type="banned", too_many_argu @commands.command(name="unfilter", aliases=["unfilter_word"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def unfilter_word(self, ctx, word, too_many_arguments=None): """ Remove an existing word/test from the filter list @@ -119,6 +122,7 @@ async def unfilter_word(self, ctx, word, too_many_arguments=None): @commands.command(name="filterList", aliases=["check_filtered_words", "checkFilteredWords"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def check_filtered_words(self, ctx): """ Get a list of filtered words on the current guild. @@ -134,6 +138,7 @@ async def check_filtered_words(self, ctx): "add_mod_channel", "addModChannel"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def setup_mod_channel(self, ctx, channel_id, too_many_arguments=None): """ Add a mod channel to the current guild @@ -154,6 +159,7 @@ async def setup_mod_channel(self, ctx, channel_id, too_many_arguments=None): @commands.command(name="modChannelRemove", aliases=["remove_mod_channel", "deleteModChannel", "removeModChannel"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def remove_mod_channel(self, ctx, channel_id, too_many_arguments=None): """ Remove a mod channel from the guild @@ -175,6 +181,7 @@ async def remove_mod_channel(self, ctx, channel_id, too_many_arguments=None): @commands.command(name="modChannelList", aliases=["list_mod_channels", "listModChannels"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def list_mod_channels(self, ctx): """ Get a list of filtered mod channels in the guild @@ -188,6 +195,7 @@ async def list_mod_channels(self, ctx): @commands.command(name="ignoreUser") @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def ignore_user(self, ctx, user, too_many_arguments=None): """ Add a new ignored user to the database @@ -210,6 +218,7 @@ async def ignore_user(self, ctx, user, too_many_arguments=None): @commands.command(name="ignoreChannel") @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def ignore_channel(self, ctx, channel, too_many_arguments=None): """ Add a new ignored channel to the database @@ -232,6 +241,7 @@ async def ignore_channel(self, ctx, channel, too_many_arguments=None): @commands.command(name="unignore", aliases=["remove_ignore", "removeIgnore"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def remove_ignore(self, ctx, ignore, too_many_arguments=None): """ Remove an ignore from the guild @@ -254,6 +264,7 @@ async def remove_ignore(self, ctx, ignore, too_many_arguments=None): @commands.command(name="ignoreList", aliases=["list_ignored", "listIgnored"]) @commands.check(KoalaBot.is_admin) @commands.check(text_filter_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def list_ignored(self, ctx): """ Get a list all ignored users/channels @@ -730,4 +741,4 @@ def setup(bot: KoalaBot) -> None: :param bot: The client of the KoalaBot """ - bot.add_cog(TextFilter(bot)) + bot.add_cog(TextFilter(bot)) \ No newline at end of file diff --git a/cogs/TwitchAlert.py b/cogs/TwitchAlert.py index def6bce8..ce6f20ae 100644 --- a/cogs/TwitchAlert.py +++ b/cogs/TwitchAlert.py @@ -86,6 +86,7 @@ def __init__(self, bot, database_manager=None): self.stop_loop = False @commands.command(name="twitchEditMsg", aliases=["edit_default_message"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def edit_default_message(self, ctx, raw_channel_id, *default_live_message): @@ -130,6 +131,7 @@ async def edit_default_message(self, ctx, raw_channel_id, *default_live_message) await ctx.send(embed=new_embed) @commands.command(name="twitchViewMsg", aliases=["view_default_message"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def view_default_message(self, ctx, raw_channel_id=None): @@ -161,6 +163,7 @@ async def view_default_message(self, ctx, raw_channel_id=None): await ctx.send(embed=new_embed) @commands.command(name="twitchAdd", aliases=['add_user_to_twitch_alert']) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def add_user_to_twitch_alert(self, ctx, raw_channel_id, twitch_username=None, *custom_live_message): @@ -213,6 +216,7 @@ async def add_user_to_twitch_alert(self, ctx, raw_channel_id, twitch_username=No await ctx.send(embed=new_embed) @commands.command(name="twitchRemove", aliases=['remove_user_from_twitch_alert']) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def remove_user_from_twitch_alert(self, ctx, raw_channel_id, twitch_username=None): @@ -246,6 +250,7 @@ async def remove_user_from_twitch_alert(self, ctx, raw_channel_id, twitch_userna await ctx.send(embed=new_embed) @commands.command(name="twitchAddTeam", aliases=["add_team_to_twitch_alert"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def add_team_to_twitch_alert(self, ctx, raw_channel_id, team_name=None, *custom_live_message): @@ -297,6 +302,7 @@ async def add_team_to_twitch_alert(self, ctx, raw_channel_id, team_name=None, *c await ctx.send(embed=new_embed) @commands.command(name="twitchRemoveTeam", aliases=["remove_team_from_twitch_alert"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def remove_team_from_twitch_alert(self, ctx, raw_channel_id, team_name=None): @@ -330,6 +336,7 @@ async def remove_team_from_twitch_alert(self, ctx, raw_channel_id, team_name=Non await ctx.send(embed=new_embed) @commands.command(name="twitchList", aliases=["list_twitch_alert"]) + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(twitch_is_enabled) async def list_twitch_alert(self, ctx, raw_channel_id=None): diff --git a/cogs/Verification.py b/cogs/Verification.py index 2f59e52c..64100458 100644 --- a/cogs/Verification.py +++ b/cogs/Verification.py @@ -25,9 +25,9 @@ load_dotenv() GMAIL_EMAIL = os.environ.get('GMAIL_EMAIL') GMAIL_PASSWORD = os.environ.get('GMAIL_PASSWORD') -# Variables +# Variables def verify_is_enabled(ctx): @@ -44,6 +44,7 @@ def verify_is_enabled(ctx): return result or (str(ctx.author) == KoalaBot.TEST_USER and KoalaBot.is_dpytest) + class Verification(commands.Cog, name="Verify"): def __init__(self, bot, db_manager=None): @@ -127,6 +128,14 @@ def send_email(email, token): async def on_ready(self): await self.assign_roles_on_startup() + @commands.Cog.listener() + async def on_guild_join(self, guild): + self.DBManager.insert_email_list_status(guild.id) + + @commands.Cog.listener() + async def on_guild_remove(self, guild: discord.Guild): + self.DBManager.remove_dm_email_list_status(guild.id) + @commands.Cog.listener() async def on_member_join(self, member): """ @@ -150,14 +159,35 @@ async def on_member_join(self, member): if results and not blacklisted: await member.add_roles(role) message_string = f"""Welcome to {member.guild.name}. This guild has verification enabled. -Please verify one of the following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. -This email is stored so you don't need to verify it multiple times across servers.""" - await member.send( - content=message_string + "\n" + "\n".join([f"`{x}` for `@{y}`" for x, y in roles.items()])) + Please verify one of the following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. + This email is stored so you don't need to verify it multiple times across servers.""" + if self.DBManager.fetch_dm_email_list_status(member.guild.id): + await member.send( + content=message_string + "\n" + "\n".join([f"`{x}` for `@{y}`" for x, y in roles.items()])) + + @commands.check(KoalaBot.is_admin) + @commands.command(name="verifyDM", aliases=["toggleVerifyDM"]) + @commands.check(verify_is_enabled) + @commands.check(KoalaBot.terms_agreed) + async def toggle_email_list_dm(self, ctx, toggle): + """ + Updates the database with the argument that the user of the command supplies + :param ctx: this will be the context of the command. + :param toggle: boolean, turns DM on or off. + """ + if toggle == "True": + self.DBManager.update_dm_email_list_status(ctx.guild.id, 1) + await ctx.send(f"Users in {ctx.guild.name} will be messaged by the bot to verify their email" + f" on joining the guild") + else: + self.DBManager.update_dm_email_list_status(ctx.guild.id, 0) + await ctx.send(f"Users in {ctx.guild.name} will no longer be messaged by the bot to verify their email" + f" on joining the guild") @commands.check(KoalaBot.is_admin) @commands.command(name="verifyAdd", aliases=["addVerification"]) @commands.check(verify_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def enable_verification(self, ctx, suffix=None, role=None): """ Set up a role and email pair for KoalaBot to verify users with @@ -167,7 +197,8 @@ async def enable_verification(self, ctx, suffix=None, role=None): :return: """ if not role or not suffix: - raise self.InvalidArgumentError(f"Please provide the correct arguments\n(`{KoalaBot.COMMAND_PREFIX}enable_verification <@role>`") + raise self.InvalidArgumentError( + f"Please provide the correct arguments\n(`{KoalaBot.COMMAND_PREFIX}enable_verification <@role>`") try: role_id = int(role[3:-1]) @@ -194,6 +225,7 @@ async def enable_verification(self, ctx, suffix=None, role=None): @commands.check(KoalaBot.is_admin) @commands.command(name="verifyRemove", aliases=["removeVerification"]) @commands.check(verify_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def disable_verification(self, ctx, suffix=None, role=None): """ Disable an existing verification listener @@ -217,7 +249,6 @@ async def disable_verification(self, ctx, suffix=None, role=None): (ctx.guild.id, role_id, suffix)) await ctx.send(f"Emails ending with {suffix} no longer give {role}") - @commands.check(KoalaBot.is_dm_channel) @commands.command(name="verify") async def verify(self, ctx, email): @@ -304,6 +335,7 @@ async def get_emails(self, ctx, user_id: int): @commands.command(name="verifyList", aliases=["checkVerifications"]) @commands.check(verify_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def check_verifications(self, ctx): """ List the current verification setup for the server @@ -332,6 +364,7 @@ async def check_verifications(self, ctx): @commands.check(KoalaBot.is_admin) @commands.command(name="reVerify") @commands.check(verify_is_enabled) + @commands.check(KoalaBot.terms_agreed) async def re_verify(self, ctx, role): """ Removes a role from all users who have it and marks them as needing to re-verify before giving it back @@ -356,7 +389,8 @@ async def re_verify(self, ctx, role): await member.remove_roles(role) self.DBManager.db_execute_commit("INSERT INTO to_re_verify VALUES (?, ?)", (member.id, role.id)) - await ctx.send("That role has now been removed from all users and they will need to re-verify the associated email.") + await ctx.send( + "That role has now been removed from all users and they will need to re-verify the associated email.") class InvalidArgumentError(Exception): pass @@ -444,4 +478,3 @@ def setup(bot: KoalaBot) -> None: else: bot.add_cog(Verification(bot)) print("Verification is ready.") - diff --git a/cogs/Voting.py b/cogs/Voting.py index a5d30a1f..bd1b5f5f 100644 --- a/cogs/Voting.py +++ b/cogs/Voting.py @@ -220,6 +220,7 @@ async def vote(self, ctx): if ctx.invoked_subcommand is None: await ctx.send(f"Please use `{KoalaBot.COMMAND_PREFIX}help vote` for more information") + @commands.check(KoalaBot.terms_agreed) @commands.check(KoalaBot.is_admin) @commands.check(vote_is_enabled) @vote.command(name="create") @@ -245,6 +246,7 @@ async def start_vote(self, ctx, *, title): self.vote_manager.create_vote(ctx.author.id, ctx.guild.id, title) await ctx.send(f"Vote titled `{title}` created for guild {ctx.guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") + @commands.check(KoalaBot.terms_agreed) @currently_configuring() @commands.check(vote_is_enabled) @vote.command(name="addRole") @@ -259,6 +261,7 @@ async def add_role(self, ctx, *, role: discord.Role): await ctx.send(f"Vote will be sent to those with the {role.name} role") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="removeRole") async def remove_role(self, ctx, *, role: discord.Role): @@ -292,6 +295,7 @@ async def set_chair(self, ctx, *, chair: discord.Member = None): await ctx.send(f"Results will be sent to the channel vote is closed in") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="setChannel") async def set_channel(self, ctx, *, channel: discord.VoiceChannel = None): @@ -309,6 +313,7 @@ async def set_channel(self, ctx, *, channel: discord.VoiceChannel = None): await ctx.send("Removed channel restriction on vote") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="addOption") async def add_option(self, ctx, *, option_string): @@ -333,6 +338,7 @@ async def add_option(self, ctx, *, option_string): await ctx.send(f"Option {header} with description {body} added to vote") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="removeOption") async def remove_option(self, ctx, index: int): @@ -345,6 +351,7 @@ async def remove_option(self, ctx, index: int): await ctx.send(f"Option number {index} removed") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="setEndTime") async def set_end_time(self, ctx, *, time_string): @@ -369,6 +376,7 @@ async def set_end_time(self, ctx, *, time_string): await ctx.send(f"Vote set to end at {time.strftime('%Y-%m-%d %H:%M:%S', end_time_readable)} UTC") @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @commands.check(vote_is_enabled) @vote.command(name="preview") async def preview_vote(self, ctx): @@ -380,6 +388,7 @@ async def preview_vote(self, ctx): await add_reactions(vote, msg) @commands.check(vote_is_enabled) + @commands.check(KoalaBot.terms_agreed) @has_current_votes() @vote.command(name="cancel") async def cancel_vote(self, ctx, *, title): @@ -395,6 +404,7 @@ async def cancel_vote(self, ctx, *, title): await ctx.send(f"Vote {title} has been cancelled.") @commands.check(vote_is_enabled) + @commands.check(KoalaBot.terms_agreed) @has_current_votes() @vote.command("list", aliases=["currentVotes"]) async def check_current_votes(self, ctx): @@ -411,6 +421,7 @@ async def check_current_votes(self, ctx): await ctx.send(embed=embed) @currently_configuring() + @commands.check(KoalaBot.terms_agreed) @vote.command(name="send") async def send_vote(self, ctx): """ @@ -446,6 +457,7 @@ async def send_vote(self, ctx): await ctx.send(f"Sent vote to {len(users)} users") @commands.check(vote_is_enabled) + @commands.check(KoalaBot.terms_agreed) @has_current_votes() @vote.command(name="close") async def close(self, ctx, *, title): @@ -476,6 +488,7 @@ async def close(self, ctx, *, title): await ctx.send(embed=embed) @commands.check(vote_is_enabled) + @commands.check(KoalaBot.terms_agreed) @has_current_votes() @vote.command(name="checkResults") async def check_results(self, ctx, *, title): diff --git a/documentation.json b/documentation.json index 11504a22..f7b0fe07 100644 --- a/documentation.json +++ b/documentation.json @@ -46,6 +46,11 @@ "command": "support", "parameters": [], "description": "Returns a link to the KoalaBot Support Discord Server" + }, + { + "command": "setup", + "parameters": [], + "description": "Allows access to configure the bot, once legal terms are agreed" } ] }, @@ -336,7 +341,12 @@ "command": "confirm", "parameters": ["token"], "description": "Send to KoalaBot in dms to confirm the verification of an email" - } + }, + { + "command": "verifyDM", + "parameters": ["toggle"], + "description": "Toggle the verify DM for a guild, that sends the user a list of emails to verify" + } ] }, { diff --git a/tests/test_Announce.py b/tests/test_Announce.py index cb7ab8f6..fef92f2e 100644 --- a/tests/test_Announce.py +++ b/tests/test_Announce.py @@ -14,8 +14,7 @@ # Varibales KoalaBot.is_dpytest = True - - +DBManager = KoalaBot.database_manager @pytest.fixture(autouse=True) @@ -26,6 +25,7 @@ def utils_cog(bot: discord.ext.commands.Bot): print("Tests starting") return utils_cog + @pytest.fixture(autouse=True) def announce_cog(bot: discord.ext.commands.Bot): announce_cog = Announce.Announce(bot) @@ -66,6 +66,8 @@ async def test_create_legal_message(bot: discord.Client, announce_cog): guild: discord.Guild = bot.guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) msg_mock: discord.Message = dpytest.back.make_message('testMessage', author, channel) with mock.patch('discord.client.Client.wait_for', mock.AsyncMock(return_value=msg_mock)): @@ -85,6 +87,8 @@ async def test_create_illegal_message(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) long_content = "" for i in range(2001): long_content = long_content + "a" @@ -94,7 +98,8 @@ async def test_create_illegal_message(announce_cog): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce create', channel=channel) assert dpytest.verify().message().content("Please enter a message, I'll wait for 60 seconds, no rush.") - assert dpytest.verify().message().content("The content is more than 2000 characters long, and exceeds the limit") + assert dpytest.verify().message().content( + "The content is more than 2000 characters long, and exceeds the limit") assert not announce_cog.has_active_msg(guild.id) @@ -103,6 +108,8 @@ async def test_create_multiple_message(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) msg_mock: discord.Message = dpytest.back.make_message('testMessage', author, channel) with mock.patch('discord.client.Client.wait_for', mock.AsyncMock(return_value=msg_mock)): @@ -121,8 +128,9 @@ async def test_create_multiple_message(announce_cog): mock.AsyncMock(return_value=msg2_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce create', channel=channel) - assert dpytest.verify().message().content("There is currently an active announcement being created, you can use 'k!announce cancel' " - "or 'k!announce send' to complete it") + assert dpytest.verify().message().content( + "There is currently an active announcement being created, you can use 'k!announce cancel' " + "or 'k!announce send' to complete it") assert announce_cog.has_active_msg(guild.id) assert announce_cog.messages[guild.id].description == "testMessage" assert announce_cog.messages[guild.id].title == "" @@ -133,6 +141,8 @@ async def test_create_message_after_send_before_30_days(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) msg_mock: discord.Message = dpytest.back.make_message('testMessage', author, channel) with mock.patch('discord.client.Client.wait_for', mock.AsyncMock(return_value=msg_mock)): @@ -156,13 +166,16 @@ async def test_create_message_after_send_before_30_days(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce create', channel=channel) - assert dpytest.verify().message().content("You have recently sent an announcement and cannot use this function for 30 days") + assert dpytest.verify().message().content( + "You have recently sent an announcement and cannot use this function for 30 days") assert not announce_cog.has_active_msg(guild.id) @pytest.mark.asyncio async def test_create_message_timeout(): guild: discord.Guild = dpytest.get_config().guilds[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.channels[0] with mock.patch('discord.client.Client.wait_for', mock.AsyncMock(return_value=None)): @@ -172,19 +185,23 @@ async def test_create_message_timeout(): assert dpytest.verify().message().content("Okay, I'll cancel the command.") -@pytest.mark.parametrize("command_word, prompt_message", [("changeTitle", "Please enter the new title, I'll wait for 60 seconds, no rush."), - ("changeContent", "Please enter the new message, I'll wait for 60 seconds, no rush."), ("addRole", - "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush."), - ("add", - "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush."), - ("remove", - "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush."), - ("removeRole", - "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.")]) +@pytest.mark.parametrize("command_word, prompt_message", + [("changeTitle", "Please enter the new title, I'll wait for 60 seconds, no rush."), + ("changeContent", "Please enter the new message, I'll wait for 60 seconds, no rush."), + ("addRole", + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush."), + ("add", + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush."), + ("remove", + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush."), + ("removeRole", + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.")]) @pytest.mark.asyncio async def test_other_timeout(command_word, prompt_message, announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) with mock.patch('discord.client.Client.wait_for', mock.AsyncMock(return_value=None)): @@ -202,6 +219,8 @@ async def test_other_timeout(command_word, prompt_message, announce_cog): async def test_functions_no_active(command_word): guild: discord.Guild = dpytest.get_config().guilds[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce ' + command_word, channel=channel) assert dpytest.verify().message().content("There is currently no active announcement") @@ -213,6 +232,8 @@ async def test_change_title(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) assert announce_cog.has_active_msg(guild.id) assert announce_cog.messages[guild.id].description == "testMessage" @@ -234,6 +255,8 @@ async def test_change_message(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) assert announce_cog.has_active_msg(guild.id) assert announce_cog.messages[guild.id].description == "testMessage" @@ -255,6 +278,8 @@ async def test_change_long_message(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) assert announce_cog.has_active_msg(guild.id) assert announce_cog.messages[guild.id].description == "testMessage" @@ -267,7 +292,8 @@ async def test_change_long_message(announce_cog): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce changeContent', channel=channel) assert dpytest.verify().message().content("Please enter the new message, I'll wait for 60 seconds, no rush.") - assert dpytest.verify().message().content("The content is more than 2000 characters long, and exceeds the limit") + assert dpytest.verify().message().content( + "The content is more than 2000 characters long, and exceeds the limit") assert announce_cog.has_active_msg(guild.id) assert announce_cog.messages[guild.id].description == "testMessage" @@ -279,6 +305,8 @@ async def test_add_possible_role(number_of_roles, announce_cog): author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] roles = guild.roles + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) assert announce_cog.roles[guild.id] == [] role_list = "" @@ -291,7 +319,8 @@ async def test_add_possible_role(number_of_roles, announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce add', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == role_id_list @@ -302,6 +331,8 @@ async def test_add_non_existent_role(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) assert announce_cog.roles[guild.id] == [] msg_mock: discord.Message = dpytest.back.make_message("12345", author, channel) @@ -309,7 +340,8 @@ async def test_add_non_existent_role(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce add', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [] @@ -320,6 +352,8 @@ async def test_add_same_role(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) roles = guild.roles make_message(guild, announce_cog) role_list = str(roles[0].id) + " " + str(roles[0].id) @@ -329,7 +363,8 @@ async def test_add_same_role(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce add', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to tag separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [roles[0].id] @@ -340,6 +375,8 @@ async def test_remove_role_from_none(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) roles = guild.roles make_message(guild, announce_cog) assert announce_cog.roles[guild.id] == [] @@ -348,7 +385,8 @@ async def test_remove_role_from_none(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce remove', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [] @@ -357,7 +395,8 @@ async def test_remove_role_from_none(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce remove', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [] @@ -370,6 +409,8 @@ async def test_remove_existing_role(announce_cog): channel: discord.TextChannel = guild.channels[0] roles = guild.roles make_message(guild, announce_cog) + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) announce_cog.roles[guild.id] = [roles[0].id] assert announce_cog.roles[guild.id] == [roles[0].id] msg_mock: discord.Message = dpytest.back.make_message(str(roles[0].id), author, channel) @@ -377,7 +418,8 @@ async def test_remove_existing_role(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce remove', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [] @@ -388,6 +430,8 @@ async def test_remove_non_existent_role(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) guild.roles.append(await guild.create_role(name="testrole")) assert len(guild.roles) == 2 roles = guild.roles @@ -399,7 +443,8 @@ async def test_remove_non_existent_role(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce remove', channel=channel) - assert dpytest.verify().message().content("Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") + assert dpytest.verify().message().content( + "Please enter the roles you want to remove separated by space, I'll wait for 60 seconds, no rush.") assert dpytest.verify().message() assert announce_cog.has_active_msg(guild.id) assert announce_cog.roles[guild.id] == [roles[0].id] @@ -431,6 +476,8 @@ def test_embed_consistent_with_url(announce_cog): async def test_preview_consistent(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) embed: discord.Embed = announce_cog.construct_embed(guild) await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce preview', @@ -443,6 +490,8 @@ async def test_preview_consistent(announce_cog): async def test_cancel(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] channel: discord.TextChannel = guild.channels[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) make_message(guild, announce_cog) announce_cog.roles[guild.id] = [123, 234] assert guild.id in announce_cog.messages.keys() @@ -469,6 +518,8 @@ def test_receiver_msg(announce_cog): async def test_announce_db_first_creation(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.channels[0] assert announce_cog.announce_database_manager.get_last_use_date(guild.id) is None msg_mock: discord.Message = dpytest.back.make_message('testMessage', author, channel) @@ -495,6 +546,8 @@ async def test_announce_db_first_creation(announce_cog): async def test_announce_db_update_time_from_legal_use(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.channels[0] assert announce_cog.announce_database_manager.get_last_use_date(guild.id) is None announce_cog.announce_database_manager.set_last_use_date(guild.id, int( @@ -526,6 +579,8 @@ async def test_announce_db_update_time_from_legal_use(announce_cog): async def test_announce_db_no_update_time_from_illegal_use(announce_cog): guild: discord.Guild = dpytest.get_config().guilds[0] author: discord.Member = guild.members[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.channels[0] assert announce_cog.announce_database_manager.get_last_use_date(guild.id) is None current_time = int(time.time()) @@ -536,7 +591,8 @@ async def test_announce_db_no_update_time_from_illegal_use(announce_cog): mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce create', channel=channel) - assert dpytest.verify().message().content("You have recently sent an announcement and cannot use this function for 30 days") + assert dpytest.verify().message().content( + "You have recently sent an announcement and cannot use this function for 30 days") assert not announce_cog.has_active_msg(guild.id) assert announce_cog.announce_database_manager.get_last_use_date(guild.id) == current_time await dpytest.message(KoalaBot.COMMAND_PREFIX + 'announce send', diff --git a/tests/test_BaseCog.py b/tests/test_BaseCog.py index 27b9e51a..a9ed456e 100644 --- a/tests/test_BaseCog.py +++ b/tests/test_BaseCog.py @@ -21,11 +21,12 @@ from cogs import BaseCog from tests.utils_testing.TestUtils import assert_activity - # Constants # Variables +DBManager = KoalaBot.database_manager + @pytest.fixture(scope='session', autouse=True) def setup_is_dpytest(): @@ -49,18 +50,25 @@ async def base_cog(bot): async def test_on_ready(base_cog: BaseCog.BaseCog): await base_cog.on_ready() assert dpytest.verify().activity().matches(discord.Activity(type=discord.ActivityType.playing, - name=KoalaBot.COMMAND_PREFIX + "help" + KoalaBot.KOALA_PLUG)) + name=KoalaBot.COMMAND_PREFIX + "help" + KoalaBot.KOALA_PLUG)) @pytest.mark.asyncio async def test_change_activity(): + guild = dpytest.get_config().guilds[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "change_activity watching you") - assert dpytest.verify().activity().matches(discord.Activity(type=discord.ActivityType.watching, name="you" + KoalaBot.KOALA_PLUG)) + assert dpytest.verify().activity().matches( + discord.Activity(type=discord.ActivityType.watching, name="you" + KoalaBot.KOALA_PLUG)) assert dpytest.verify().message().content("I am now watching you") @pytest.mark.asyncio async def test_invalid_change_activity(): + guild = dpytest.get_config().guilds[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "change_activity oof you") assert dpytest.verify().message().content("That is not a valid activity, sorry!\nTry 'playing' or 'watching'") diff --git a/tests/test_ColourRole.py b/tests/test_ColourRole.py index 4ae7820c..25b6a5de 100644 --- a/tests/test_ColourRole.py +++ b/tests/test_ColourRole.py @@ -29,8 +29,9 @@ # Constants # Variables -#role_colour_cog: ColourRole.ColourRole = None -#utils_cog: TestUtilsCog.TestUtilsCog = None +# role_colour_cog: ColourRole.ColourRole = None +# utils_cog: TestUtilsCog.TestUtilsCog = None +kDBManager = KoalaBot.database_manager DBManager = ColourRoleDBManager(KoalaBot.database_manager) DBManager.create_tables() @@ -43,6 +44,7 @@ def utils_cog(bot): print("Tests starting") return utils_cog + @pytest.fixture(autouse=True) def role_colour_cog(bot): role_colour_cog = ColourRole.ColourRole(bot) @@ -51,6 +53,7 @@ def role_colour_cog(bot): print("Tests starting") return role_colour_cog + async def make_list_of_roles(guild: discord.Guild, length: int) -> List[discord.Role]: arr: List[discord.Role] = [] for i in range(length): @@ -332,6 +335,8 @@ async def test_get_guild_protected_colours(num_roles, utils_cog, role_colour_cog async def test_list_protected_roles(num_total, num_protected): guild: discord.Guild = dpytest.get_config().guilds[0] roles = await make_list_of_roles(guild, num_total) + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) expected = "Roles whose colour is protected are:\r" if num_total == 0 or num_protected == 0: protected = [] @@ -357,6 +362,8 @@ async def test_list_protected_roles(num_total, num_protected): async def test_list_custom_colour_allowed_roles(num_total, num_protected): guild: discord.Guild = dpytest.get_config().guilds[0] roles = await make_list_of_roles(guild, num_total) + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) expected = "Roles allowed to have a custom colour are:\r" if num_total == 0 or num_protected == 0: allowed = [] @@ -439,6 +446,8 @@ async def test_prune_member_old_colour_roles(num_members, role_colour_cog): async def test_add_protected_role_colour(): guild: discord.Guild = dpytest.get_config().guilds[0] role = await make_list_of_roles(guild, 1) + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) assert independent_get_protected_colours(guild.id) == [] await dpytest.message(KoalaBot.COMMAND_PREFIX + "add_protected_role_colour " + str(role[0].id)) assert independent_get_protected_colours(guild.id) == [role[0].id] @@ -447,6 +456,8 @@ async def test_add_protected_role_colour(): @pytest.mark.asyncio async def test_add_custom_colour_allowed_role(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = await make_list_of_roles(guild, 1) assert independent_get_colour_change_roles(guild.id) == [] await dpytest.message(KoalaBot.COMMAND_PREFIX + "add_custom_colour_allowed_role " + str(role[0].id)) @@ -456,6 +467,8 @@ async def test_add_custom_colour_allowed_role(): @pytest.mark.asyncio async def test_remove_protected_role_colour(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] assert independent_get_protected_colours(guild.id) == [] DBManager.add_guild_protected_colour_role(guild.id, role.id) @@ -467,6 +480,8 @@ async def test_remove_protected_role_colour(): @pytest.mark.asyncio async def test_remove_custom_colour_allowed_role(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] assert independent_get_colour_change_roles(guild.id) == [] DBManager.add_colour_change_role_perms(guild.id, role.id) @@ -478,6 +493,8 @@ async def test_remove_custom_colour_allowed_role(): @pytest.mark.asyncio async def test_custom_colour_check_failure(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] DBManager.add_colour_change_role_perms(guild.id, role.id) with pytest.raises(commands.CheckFailure): @@ -492,6 +509,9 @@ async def test_custom_colour_check_failure(): @pytest.mark.asyncio async def test_custom_colour_no_allowed_role(): + guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) with pytest.raises(commands.CheckFailure): await dpytest.message(KoalaBot.COMMAND_PREFIX + "custom_colour ab1234") assert "KoalaBot[0xAB1234]" not in [role.name for role in dpytest.get_config().guilds[0].roles] @@ -508,6 +528,8 @@ async def test_custom_colour_no_allowed_role(): @pytest.mark.asyncio async def test_custom_colour_no_no_colour_role(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] DBManager.add_colour_change_role_perms(guild.id, role.id) member: discord.Member = dpytest.get_config().members[0] @@ -521,6 +543,8 @@ async def test_custom_colour_no_no_colour_role(): @pytest.mark.asyncio async def test_custom_colour_colour_is_protected(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] DBManager.add_colour_change_role_perms(guild.id, role.id) member: discord.Member = dpytest.get_config().members[0] @@ -535,6 +559,8 @@ async def test_custom_colour_colour_is_protected(): @pytest.mark.asyncio async def test_custom_colour_invalid_colour_str(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] DBManager.add_colour_change_role_perms(guild.id, role.id) member: discord.Member = dpytest.get_config().members[0] @@ -548,6 +574,8 @@ async def test_custom_colour_invalid_colour_str(): @pytest.mark.asyncio async def test_custom_colour_valid(): guild: discord.Guild = dpytest.get_config().guilds[0] + kDBManager.insert_setup_status(guild.id) + kDBManager.update_guild_setup_status(guild.id) role = (await make_list_of_roles(guild, 1))[0] DBManager.add_colour_change_role_perms(guild.id, role.id) member: discord.Member = dpytest.get_config().members[0] diff --git a/tests/test_IntroCog.py b/tests/test_IntroCog.py index 5ac69985..adc57d67 100644 --- a/tests/test_IntroCog.py +++ b/tests/test_IntroCog.py @@ -40,9 +40,11 @@ def utils_cog(bot): print("Tests starting") return utils_cog + @pytest.fixture(autouse=True) def intro_cog(bot): intro_cog = IntroCog.IntroCog(bot) + intro_cog.terms_agreed = True bot.add_cog(intro_cog) dpytest.configure(bot) print("Tests starting") @@ -108,16 +110,18 @@ async def test_on_guild_remove(bot): bot_member = test_config.guilds[0].get_member(client.user.id) dpytest.backend.delete_member(bot_member) val = DBManager.fetch_guild_welcome_message(guild.id) + with pytest.raises(IndexError): + status = DBManager.fetch_guild_setup_status(guild.id) assert val is None @pytest.mark.parametrize("guild_id, expected", - [(101, f"fake guild welcome message"), (1250, IntroCog.DEFAULT_WELCOME_MESSAGE), + [(1250, IntroCog.DEFAULT_WELCOME_MESSAGE), (9999, IntroCog.DEFAULT_WELCOME_MESSAGE)]) @pytest.mark.asyncio async def test_get_guild_welcome_message(guild_id, expected): val = IntroCog.get_guild_welcome_message(guild_id) - assert val == f"{expected}\r\n{IntroCog.BASE_LEGAL_MESSAGE}", val + assert val == "" @pytest.mark.asyncio @@ -153,7 +157,7 @@ async def test_on_member_join(): await asyncio.sleep(0.25) welcome_message = IntroCog.get_guild_welcome_message(guild.id) await dpytest.member_join(1) - assert dpytest.verify().message().content(welcome_message) + assert dpytest.verify().message().nothing() DBManager.update_guild_welcome_message(guild.id, 'This is an updated welcome message.') await asyncio.sleep(0.25) welcome_message = IntroCog.get_guild_welcome_message(guild.id) @@ -161,6 +165,17 @@ async def test_on_member_join(): assert dpytest.verify().message().content(welcome_message) +@pytest.mark.asyncio +async def test_on_member_join_no_message(): + test_config = dpytest.get_config() + client = test_config.client + guild = dpytest.back.make_guild('TestMemberJoinNoMsg', id_num=1234) + test_config.guilds.append(guild) + await dpytest.member_join(1, client.user) + await dpytest.member_join(1) + assert dpytest.verify().message().nothing() + + @pytest.mark.asyncio async def test_wait_for_message(utils_cog): bot = dpytest.get_config().client @@ -212,12 +227,13 @@ async def test_confirm_message(msg_content, expected): @pytest.mark.asyncio async def test_send_welcome_message(): + guild = dpytest.get_config().guilds[0] msg_mock = dpytest.back.make_message('y', dpytest.get_config().members[0], dpytest.get_config().channels[0]) with mock.patch('cogs.IntroCog.wait_for_message', mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + "send_welcome_message") assert dpytest.verify().message().content("This will DM 1 people. Are you sure you wish to do this? Y/N") assert dpytest.verify().message().content("Okay, sending out the welcome message now.") - assert dpytest.verify().message().content(f"{IntroCog.DEFAULT_WELCOME_MESSAGE}\r\n{IntroCog.BASE_LEGAL_MESSAGE}") + assert dpytest.verify().message().content("") @pytest.mark.asyncio @@ -246,12 +262,16 @@ async def test_cancel_update_welcome_message(): old_message = IntroCog.get_guild_welcome_message(guild.id) new_message = "this is a non default message" msg_mock = dpytest.back.make_message('n', dpytest.get_config().members[0], dpytest.get_config().channels[0]) + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) + status = DBManager.fetch_guild_setup_status(guild.id) with mock.patch('cogs.IntroCog.wait_for_message', mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message " + new_message) assert dpytest.verify().message().content(f"""Your current welcome message is:\n\r{old_message}""") - assert dpytest.verify().message().content(f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + - """\n\rWould you like to update the message? Y/N?""") + assert dpytest.verify().message().content( + f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + + """\n\rWould you like to update the message? Y/N?""") assert dpytest.verify().message().content("Okay, I won't update the welcome message then.") assert dpytest.verify().message().nothing() assert DBManager.fetch_guild_welcome_message(guild.id) != new_message @@ -263,14 +283,18 @@ async def test_update_welcome_message(): old_message = IntroCog.get_guild_welcome_message(guild.id) new_message = "this is a non default message" msg_mock = dpytest.back.make_message('y', dpytest.get_config().members[0], dpytest.get_config().channels[0]) + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) with mock.patch('cogs.IntroCog.wait_for_message', mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message " + new_message) assert dpytest.verify().message().content(f"""Your current welcome message is:\n\r{old_message}""") - assert dpytest.verify().message().content(f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + - """\n\rWould you like to update the message? Y/N?""") + assert dpytest.verify().message().content( + f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + + """\n\rWould you like to update the message? Y/N?""") assert dpytest.verify().message().content("Okay, updating the welcome message of the guild in the database now.") - assert dpytest.verify().message().content("Updated in the database, your new welcome message is this is a non default message.") + assert dpytest.verify().message().content( + "Updated in the database, your new welcome message is this is a non default message.") assert dpytest.verify().message().nothing() assert DBManager.fetch_guild_welcome_message(guild.id) == new_message @@ -281,16 +305,21 @@ async def test_update_welcome_message_too_long(): guild = dpytest.get_config().guilds[0] old_message = IntroCog.get_guild_welcome_message(guild.id) new_message = "".join(random.choice(string.ascii_letters) for _ in range(1800)) + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) msg_mock = dpytest.back.make_message('y', dpytest.get_config().members[0], dpytest.get_config().channels[0]) with mock.patch('cogs.IntroCog.wait_for_message', mock.AsyncMock(return_value=msg_mock)): await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message " + new_message) - assert dpytest.verify().message().content("Your welcome message is too long to send, sorry. The maximum character limit is 1600.") + assert dpytest.verify().message().content( + "Your welcome message is too long to send, sorry. The maximum character limit is 1600.") assert dpytest.verify().message().nothing() assert DBManager.fetch_guild_welcome_message(guild.id) != new_message @pytest.mark.asyncio async def test_update_welcome_message_no_args(): + DBManager.insert_setup_status(guild_id=dpytest.get_config().guilds[0].id) + DBManager.update_guild_setup_status(guild_id=dpytest.get_config().guilds[0].id) with pytest.raises(commands.MissingRequiredArgument): await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message") assert dpytest.verify().message().content("Please put in a welcome message to update to.") @@ -304,33 +333,70 @@ async def test_view_welcome_message(): assert dpytest.verify().message().content(f"""Your current welcome message is:\n\r{old_message}""") +@pytest.mark.asyncio +async def test_check_failure_error(): + guild_id = dpytest.get_config().guilds[0].id + KoalaBot.database_manager.insert_setup_status(guild_id) + with pytest.raises(commands.CheckFailure): + await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message") + + @pytest.mark.asyncio async def test_update_welcome_message_timeout(): guild = dpytest.get_config().guilds[0] old_message = IntroCog.get_guild_welcome_message(guild.id) new_message = "this is a non default message" + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) # msg_mock = dpytest.back.make_message('y', dpytest.get_config().members[0], dpytest.get_config().channels[0]) with mock.patch('cogs.IntroCog.wait_for_message', mock.AsyncMock(return_value=None)): await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message " + new_message) assert dpytest.verify().message().content(f"""Your current welcome message is:\n\r{old_message}""") - assert dpytest.verify().message().content(f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + - """\n\rWould you like to update the message? Y/N?""") + assert dpytest.verify().message().content( + f"""Your new welcome message will be:\n\r{new_message}\n\r{IntroCog.BASE_LEGAL_MESSAGE}""" + + """\n\rWould you like to update the message? Y/N?""") assert dpytest.verify().message().content("Timed out.") assert dpytest.verify().message().content("Okay, I won't update the welcome message then.") assert dpytest.verify().message().nothing() assert DBManager.fetch_guild_welcome_message(guild.id) != new_message +@pytest.mark.asyncio +async def test_no_setup(): + DBManager.insert_setup_status(guild_id=dpytest.get_config().guilds[0].id) + with pytest.raises(commands.CheckFailure): + await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message") + assert dpytest.verify().message().nothing() + + +@pytest.mark.asyncio +async def test_setup_command(): + DBManager.insert_setup_status(guild_id=dpytest.get_config().guilds[0].id) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setup") + assert dpytest.verify().message().content("Terms and Conditions agreed, you can now configure the bot") + with pytest.raises(commands.MissingRequiredArgument): + await dpytest.message(KoalaBot.COMMAND_PREFIX + "update_welcome_message") + assert dpytest.verify().message().content("Please put in a welcome message to update to.") + + +@pytest.mark.asyncio +async def test_intro_message(): + test_config = dpytest.get_config() + client = test_config.client + guild = dpytest.back.make_guild('TestGuildJoin', id_num=1250) + test_config.guilds.append(guild) + await dpytest.member_join(1, client.user) + await asyncio.sleep(0.3) + + + @pytest.fixture(scope='session', autouse=True) def setup_db(): DBManager.clear_all_tables(DBManager.fetch_all_tables()) yield DBManager - - - @pytest.fixture(scope='function', autouse=True) async def setup_clean_messages(): await dpytest.empty_queue() diff --git a/tests/test_KoalaBot.py b/tests/test_KoalaBot.py index 51c374bb..f992bfaa 100644 --- a/tests/test_KoalaBot.py +++ b/tests/test_KoalaBot.py @@ -57,7 +57,7 @@ def test_test_user_is_owner(test_ctx): def test_invalid_test_user_is_owner(test_ctx): - test_ctx.author = FakeAuthor(id=int(KoalaBot.BOT_OWNER)+1) + test_ctx.author = FakeAuthor(id=int(KoalaBot.BOT_OWNER) + 1) KoalaBot.is_dpytest = False assert not KoalaBot.is_owner(test_ctx) KoalaBot.is_dpytest = True @@ -73,7 +73,10 @@ def test_test_user_is_admin(test_ctx): def test_invalid_test_user_is_admin(test_ctx): - test_ctx.author = FakeAuthor(id=int(KoalaBot.BOT_OWNER)+2) + guild = dpytest.get_config().guilds[0] + DBManager.insert_setup_status(guild.id) + DBManager.update_guild_setup_status(guild.id) + test_ctx.author = FakeAuthor(id=int(KoalaBot.BOT_OWNER) + 2) KoalaBot.is_dpytest = False assert not KoalaBot.is_admin(test_ctx) KoalaBot.is_dpytest = True @@ -113,6 +116,14 @@ async def test_dm_single_group_message(): assert x == 1 +@pytest.mark.asyncio +async def test_terms_agreed(test_ctx): + guild_id = test_ctx.guild.id + KoalaBot.database_manager.insert_setup_status(guild_id) + KoalaBot.database_manager.update_guild_setup_status(guild_id) + assert KoalaBot.terms_agreed(test_ctx) + + @pytest.mark.asyncio async def test_dm_plural_group_message(): test_message = 'default message' diff --git a/tests/test_ReactForRole.py b/tests/test_ReactForRole.py index 704cb839..0c39691b 100644 --- a/tests/test_ReactForRole.py +++ b/tests/test_ReactForRole.py @@ -45,6 +45,7 @@ def utils_cog(bot): print("Tests starting") return utils_cog + @pytest.fixture(autouse=True) def rfr_cog(bot): rfr_cog = ReactForRole.ReactForRole(bot) @@ -122,6 +123,8 @@ def get_rfr_reaction_role_by_role_id(emoji_role_id: int, role_id: int) -> Option async def test_rfr_db_functions_guild_rfr_messages(): guild: discord.Guild = dpytest.get_config().guilds[0] channel: discord.TextChannel = dpytest.get_config().channels[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) msg_id = dpyfactory.make_id() # Test when no messages exist expected_full_list: List[Tuple[int, int, int, int]] = [] @@ -186,6 +189,8 @@ async def test_rfr_db_functions_guild_rfr_messages(): @pytest.mark.asyncio async def test_rfr_db_functions_rfr_message_emoji_roles(): guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = dpytest.get_config().channels[0] msg_id = dpyfactory.make_id() DBManager.add_rfr_message(guild.id, channel.id, msg_id) @@ -308,6 +313,8 @@ async def test_rfr_db_functions_rfr_message_emoji_roles(): @pytest.mark.asyncio async def test_rfr_db_functions_guild_rfr_required_roles(): guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) roles = [] for i in range(50): role: discord.Role = testutils.fake_guild_role(guild) @@ -335,6 +342,9 @@ async def test_get_rfr_message_from_prompts(bot, utils_cog, rfr_cog): channel_id = msg.channel.id msg_id = msg.id + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() with mock.patch('cogs.ReactForRole.ReactForRole.prompt_for_input', @@ -365,6 +375,8 @@ async def test_get_rfr_message_from_prompts(bot, utils_cog, rfr_cog): async def test_parse_emoji_and_role_input_str(num_rows, utils_cog, rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() for i in range(5): @@ -401,6 +413,8 @@ async def test_parse_emoji_or_roles_input_str(num_rows): image = discord.File("utils/discord.png", filename="discord.png") config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() input_str = "" @@ -436,10 +450,12 @@ async def test_parse_emoji_or_roles_input_str(num_rows): @pytest.mark.parametrize("msg_content", [None, "", "something", " "]) @pytest.mark.asyncio -async def test_prompt_for_input_str(msg_content,utils_cog,rfr_cog): +async def test_prompt_for_input_str(msg_content, utils_cog, rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() author: discord.Member = config.members[0] guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() @@ -448,14 +464,16 @@ async def test_prompt_for_input_str(msg_content,utils_cog,rfr_cog): with mock.patch('utils.KoalaUtils.wait_for_message', mock.AsyncMock(return_value=(None, channel))): result = await rfr_cog.prompt_for_input(ctx, "test") - assert dpytest.verify().message().content("Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") + assert dpytest.verify().message().content( + "Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") assert dpytest.verify().message().content("Okay, I'll cancel the command.") assert not result else: msg: discord.Message = dpytest.back.make_message(content=msg_content, author=author, channel=channel) with mock.patch('utils.KoalaUtils.wait_for_message', mock.AsyncMock(return_value=(msg, None))): result = await rfr_cog.prompt_for_input(ctx, "test") - assert dpytest.verify().message().content("Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") + assert dpytest.verify().message().content( + "Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") assert result == msg_content @@ -464,6 +482,8 @@ async def test_prompt_for_input_attachment(rfr_cog, utils_cog): config: dpytest.RunnerConfig = dpytest.get_config() author: discord.Member = config.members[0] guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() @@ -478,7 +498,8 @@ async def test_prompt_for_input_attachment(rfr_cog, utils_cog): message: discord.Message = discord.Message(state=dpytest.back.get_state(), channel=channel, data=message_dict) with mock.patch('utils.KoalaUtils.wait_for_message', mock.AsyncMock(return_value=(message, channel))): result = await rfr_cog.prompt_for_input(ctx, "test") - assert dpytest.verify().message().content("Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") + assert dpytest.verify().message().content( + "Please enter test so I can progress further. I'll wait 60 seconds, don't worry.") assert isinstance(result, discord.Attachment) assert result.url == attach.url @@ -487,6 +508,8 @@ async def test_prompt_for_input_attachment(rfr_cog, utils_cog): async def test_overwrite_channel_add_reaction_perms(rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] with mock.patch('discord.ext.test.backend.FakeHttp.edit_channel_permissions') as mock_edit_channel_perms: for i in range(15): @@ -506,6 +529,9 @@ async def test_wait_for_message_not_none(msg_content, utils_cog, rfr_cog): ctx = utils_cog.get_last_ctx() config: dpytest.RunnerConfig = dpytest.get_config() bot: discord.Client = config.client + guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) import threading t2 = threading.Timer(interval=0.1, function=dpytest.message, args=(msg_content)) t2.start() @@ -520,6 +546,9 @@ async def test_wait_for_message_none(utils_cog, rfr_cog): ctx: commands.Context = utils_cog.get_last_ctx() config: dpytest.RunnerConfig = dpytest.get_config() bot: discord.Client = config.client + guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) msg, channel = await wait_for_message(bot, ctx, 0.2) assert not msg assert channel == ctx.channel @@ -527,6 +556,9 @@ async def test_wait_for_message_none(utils_cog, rfr_cog): @pytest.mark.asyncio async def test_is_user_alive(utils_cog, rfr_cog): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() with mock.patch('utils.KoalaUtils.wait_for_message', @@ -543,6 +575,8 @@ async def test_get_embed_from_message(rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() author: discord.Member = config.members[0] guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] test_embed_dict: dict = {'title': 'title', 'description': 'descr', 'type': 'rich', 'url': 'https://www.google.com'} bot: discord.Client = config.client @@ -561,6 +595,8 @@ async def test_get_embed_from_message(rfr_cog): async def test_get_number_of_embed_fields(rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] test_embed_dict: dict = {'title': 'title', 'description': 'descr', 'type': 'rich', 'url': 'https://www.google.com'} bot: discord.Client = config.client @@ -581,6 +617,8 @@ async def test_get_first_emoji_from_str(): ctx: commands.Context = utils_cog.get_last_ctx() config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) guild_emoji = testutils.fake_guild_emoji(guild) guild_emoji = discord.Emoji(guild=guild, state=None, data={'name': "AAA", 'image': None, 'id': dpyfactory.make_id(), @@ -603,6 +641,8 @@ async def test_get_first_emoji_from_str(): async def test_rfr_create_message(bot): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed_channel: discord.TextChannel = dpytest.back.make_text_channel('EmbedChannel', guild) author: discord.Member = config.members[0] @@ -650,6 +690,8 @@ async def test_rfr_create_message(bot): async def test_rfr_delete_message(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] message: discord.Message = await dpytest.message("rfr") msg_id = message.id @@ -673,6 +715,8 @@ async def test_rfr_delete_message(): async def test_rfr_edit_description(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") client: discord.Client = config.client @@ -696,6 +740,8 @@ async def test_rfr_edit_description(): async def test_rfr_edit_title(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") client: discord.Client = config.client @@ -719,6 +765,8 @@ async def test_rfr_edit_title(): async def test_rfr_edit_thumbnail_attach(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") embed.set_thumbnail( @@ -729,7 +777,8 @@ async def test_rfr_edit_thumbnail_attach(): "https://media.discordapp.net/attachments/some_number/random_number/test.jpg", "https://media.discordapp.net/attachments/some_number/random_number/test.jpg", height=1000, - width=1000, content_type="image/jpeg")) + width=1000, + content_type="image/jpeg")) msg_id = message.id bad_attach = "something that's not an attachment" DBManager.add_rfr_message(guild.id, channel.id, msg_id) @@ -751,6 +800,8 @@ async def test_rfr_edit_thumbnail_attach(): async def test_rfr_edit_thumbnail_bad_attach(attach): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") embed.set_thumbnail( @@ -764,7 +815,8 @@ async def test_rfr_edit_thumbnail_bad_attach(attach): mock.AsyncMock(return_value=(message, channel))): with mock.patch('cogs.ReactForRole.ReactForRole.get_embed_from_message', return_value=embed): with mock.patch('cogs.ReactForRole.ReactForRole.prompt_for_input', return_value=attach): - with pytest.raises((aiohttp.ClientError, aiohttp.InvalidURL, commands.BadArgument, commands.CommandInvokeError)) as exc: + with pytest.raises((aiohttp.ClientError, aiohttp.InvalidURL, commands.BadArgument, + commands.CommandInvokeError)) as exc: await dpytest.message("k!rfr edit thumbnail") assert embed.thumbnail.url == "https://media.discordapp.net/attachments/611574654502699010/756152703801098280/IMG_20200917_150032.jpg" @@ -779,6 +831,8 @@ async def test_rfr_edit_thumbnail_bad_attach(attach): async def test_rfr_edit_thumbnail_links(image_url): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") embed.set_thumbnail( @@ -802,7 +856,9 @@ async def test_rfr_edit_thumbnail_links(image_url): @pytest.mark.asyncio async def test_rfr_edit_inline_all(arg): config: dpytest.RunnerConfig = dpytest.get_config() - guild: discord.Guild = config.guilds[0] + guild: discord.Guild = config.guilds[0] # + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed1: discord.Embed = discord.Embed(title="title", description="description") embed1.add_field(name="field1", value="value1", inline=True) @@ -838,6 +894,8 @@ async def test_rfr_edit_inline_specific(): async def test_rfr_add_roles_to_msg(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") client: discord.Client = config.client @@ -872,6 +930,8 @@ async def test_rfr_add_roles_to_msg(): async def test_rfr_remove_roles_from_msg(): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel: discord.TextChannel = guild.text_channels[0] embed: discord.Embed = discord.Embed(title="title", description="description") client: discord.Client = config.client @@ -914,6 +974,8 @@ async def test_rfr_remove_roles_from_msg(): async def test_can_have_rfr_role(num_roles, num_required, rfr_cog): config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) r_list = [] for i in range(num_roles): role = testutils.fake_guild_role(guild) diff --git a/tests/test_TextFilter.py b/tests/test_TextFilter.py index 38d54792..84a86e48 100644 --- a/tests/test_TextFilter.py +++ b/tests/test_TextFilter.py @@ -23,10 +23,11 @@ from utils.KoalaColours import * from utils.KoalaUtils import is_int + # Variables -#base_cog = None -#tf_cog = None -#utils_cog = None +# base_cog = None +# tf_cog = None +# utils_cog = None def se5tup_function(): @@ -41,9 +42,13 @@ def se5tup_function(): bot.add_cog(tf_cog) bot.add_cog(utils_cog) dpytest.configure(bot) + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) print("Tests starting") return dpytest.get_config() + @pytest.fixture(scope="function", autouse=True) def utils_cog(bot): utils_cog = LastCtxCog.LastCtxCog(bot) @@ -52,6 +57,7 @@ def utils_cog(bot): print("Tests starting") return utils_cog + @pytest.fixture(scope="function", autouse=True) def base_cog(bot): base_cog = BaseCog.BaseCog(bot) @@ -60,6 +66,7 @@ def base_cog(bot): print("Tests starting") return base_cog + @pytest.fixture(scope="function", autouse=True) async def tf_cog(bot): tf_cog = TextFilter.TextFilter(bot) @@ -69,28 +76,36 @@ async def tf_cog(bot): print("Tests starting") return tf_cog + def assertBannedWarning(word): - assert dpytest.verify().message().content("Watch your language! Your message: '*" + word + "*' in " + dpytest.get_config().guilds[0].channels[0].mention + " has been deleted by KoalaBot.") + assert dpytest.verify().message().content( + "Watch your language! Your message: '*" + word + "*' in " + dpytest.get_config().guilds[0].channels[ + 0].mention + " has been deleted by KoalaBot.") def assertRiskyWarning(word): - assert dpytest.verify().message().content("Watch your language! Your message: '*" + word + "*' in " + dpytest.get_config().guilds[0].channels[0].mention + " contains a 'risky' word. This is a warning.") + assert dpytest.verify().message().content( + "Watch your language! Your message: '*" + word + "*' in " + dpytest.get_config().guilds[0].channels[ + 0].mention + " contains a 'risky' word. This is a warning.") def assertEmailWarning(word): - assert dpytest.verify().message().content("Be careful! Your message: '*"+word+"*' in "+dpytest.get_config().guilds[0].channels[0].mention+" includes personal information and has been deleted by KoalaBot.") + assert dpytest.verify().message().content( + "Be careful! Your message: '*" + word + "*' in " + dpytest.get_config().guilds[0].channels[ + 0].mention + " includes personal information and has been deleted by KoalaBot.") def assertFilteredConfirmation(word, type): - assert dpytest.verify().message().content("*"+word+"* has been filtered as **"+type+"**.") + assert dpytest.verify().message().content("*" + word + "* has been filtered as **" + type + "**.") def assertNewIgnore(id): - assert dpytest.verify().message().content("New ignore added: "+id) + assert dpytest.verify().message().content("New ignore added: " + id) def assertRemoveIgnore(id): - assert dpytest.verify().message().content("Ignore removed: "+id) + assert dpytest.verify().message().content("Ignore removed: " + id) + def createNewModChannelEmbed(channel): embed = discord.Embed() @@ -101,6 +116,7 @@ def createNewModChannelEmbed(channel): embed.add_field(name="Channel IDs", value=str(channel.id)) return embed + def listModChannelEmbed(channels): embed = discord.Embed() embed.title = "Koala Moderation - Mod Channels" @@ -110,6 +126,7 @@ def listModChannelEmbed(channels): embed.add_field(name="Name & Channel ID", value=channel.mention + " " + str(channel.id)) return embed + def listIgnoredEmbed(ignored): embed = discord.Embed() embed.title = "Koala Moderation - Ignored Users/Channels" @@ -119,6 +136,7 @@ def listIgnoredEmbed(ignored): embed.add_field(name="Name & ID", value=ig.mention + " " + str(ig.id)) return embed + def removeModChannelEmbed(channel): embed = discord.Embed() embed.title = "Koala Moderation - Mod Channel Removed" @@ -128,13 +146,15 @@ def removeModChannelEmbed(channel): embed.add_field(name="Channel ID", value=str(channel.id)) return embed + def createFilteredString(text): createTextString = "" for current in text: - createTextString+=current+"\n" + createTextString += current + "\n" return createTextString -def filteredWordsEmbed(words,filter,regex): + +def filteredWordsEmbed(words, filter, regex): wordString = createFilteredString(words) filterString = createFilteredString(filter) regexString = createFilteredString(regex) @@ -147,66 +167,98 @@ def filteredWordsEmbed(words,filter,regex): embed.add_field(name="Is Regex", value=regexString) return embed + def cleanup(guildId, tf_cog): - tf_cog.tf_database_manager.database_manager.db_execute_commit(f"DELETE FROM TextFilter WHERE guild_id=(\"{guildId}\");") + tf_cog.tf_database_manager.database_manager.db_execute_commit( + f"DELETE FROM TextFilter WHERE guild_id=(\"{guildId}\");") + @pytest.mark.asyncio() async def test_filter_new_word_correct_database(tf_cog): - old = len(tf_cog.tf_database_manager.database_manager.db_execute_select(f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'no';")) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word no", channel=dpytest.get_config().guilds[0].channels[0]) - assertFilteredConfirmation("no","banned") - assert len(tf_cog.tf_database_manager.database_manager.db_execute_select(f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'no';")) == old + 1 + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) + old = len(tf_cog.tf_database_manager.database_manager.db_execute_select( + f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'no';")) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word no", + channel=dpytest.get_config().guilds[0].channels[0]) + assertFilteredConfirmation("no", "banned") + assert len(tf_cog.tf_database_manager.database_manager.db_execute_select( + f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'no';")) == old + 1 cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_filter_empty_word(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word") + @pytest.mark.asyncio() async def test_filter_too_many_arguments(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word a b c d e f g") + @pytest.mark.asyncio() async def test_filter_risky_word(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word yup risky") - assertFilteredConfirmation("yup","risky") + assertFilteredConfirmation("yup", "risky") await dpytest.message("yup test") assertRiskyWarning("yup test") cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_unrecognised_filter_type(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word testy unknown") + @pytest.mark.asyncio() async def test_filter_email_regex(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + r"filter_regex [a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]") - assertFilteredConfirmation(r"[a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]","banned") + assertFilteredConfirmation(r"[a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]", "banned") cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_invalid_regex(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_regex [") cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_normal_filter_does_not_recognise_regex(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter \"^verify [a-zA-Z0-9]+@soton.ac.uk$\"") assertFilteredConfirmation("^verify [a-zA-Z0-9]+@soton.ac.uk$", "banned") await dpytest.message("verify abc@soton.ac.uk") assert dpytest.verify().message().nothing() - + + @pytest.mark.asyncio() async def test_filter_various_emails_with_regex(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + r"filter_regex [a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]") - assertFilteredConfirmation(r"[a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]","banned") + assertFilteredConfirmation(r"[a-z0-9]+[\._]?[a-z0-9]+[@]+[herts]+[.ac.uk]", "banned") # Should delete and warn await dpytest.message("hey stefan@herts.ac.uk") @@ -226,53 +278,73 @@ async def test_filter_various_emails_with_regex(tf_cog): cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_unfilter_word_correct_database(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word unfilterboi") - assertFilteredConfirmation("unfilterboi","banned") - - old = len(tf_cog.tf_database_manager.database_manager.db_execute_select(f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'unfilterboi';")) + assertFilteredConfirmation("unfilterboi", "banned") + + old = len(tf_cog.tf_database_manager.database_manager.db_execute_select( + f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'unfilterboi';")) await dpytest.message(KoalaBot.COMMAND_PREFIX + "unfilter_word unfilterboi") - - assert len(tf_cog.tf_database_manager.database_manager.db_execute_select(f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'unfilterboi';")) == old - 1 + + assert len(tf_cog.tf_database_manager.database_manager.db_execute_select( + f"SELECT filtered_text FROM TextFilter WHERE filtered_text = 'unfilterboi';")) == old - 1 assert dpytest.verify().message().content("*unfilterboi* has been unfiltered.") cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_unfilter_empty(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "unfilter_word") + @pytest.mark.asyncio() async def test_unfilter_too_many_arguments(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "unfilter_word a b c d e") + @pytest.mark.asyncio() async def test_list_filtered_words(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word listing1") - assertFilteredConfirmation("listing1","banned") + assertFilteredConfirmation("listing1", "banned") await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word listing2 risky") - assertFilteredConfirmation("listing2","risky") + assertFilteredConfirmation("listing2", "risky") await dpytest.message(KoalaBot.COMMAND_PREFIX + "check_filtered_words") - assert_embed = filteredWordsEmbed(['listing1','listing2'],['banned','risky'], ['0','0']) + assert_embed = filteredWordsEmbed(['listing1', 'listing2'], ['banned', 'risky'], ['0', '0']) assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_list_filtered_words_empty(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) await dpytest.message(KoalaBot.COMMAND_PREFIX + "check_filtered_words") - assert_embed = filteredWordsEmbed([],[],[]) + assert_embed = filteredWordsEmbed([], [], []) assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_add_mod_channel(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=dpytest.get_config().guilds[0]) dpytest.get_config().channels.append(channel) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+str(channel.id)) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + str(channel.id)) assert_embed = createNewModChannelEmbed(channel) assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) @@ -280,75 +352,105 @@ async def test_add_mod_channel(tf_cog): @pytest.fixture def text_filter_db_manager(): - return TextFilter.TextFilterDBManager(KoalaDBManager.KoalaDBManager(KoalaBot.DATABASE_PATH, KoalaBot.DB_KEY), dpytest.get_config()) + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) + return TextFilter.TextFilterDBManager(KoalaDBManager.KoalaDBManager(KoalaBot.DATABASE_PATH, KoalaBot.DB_KEY), + dpytest.get_config()) @pytest.mark.asyncio() async def test_add_mod_channel_tag(text_filter_db_manager, tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=dpytest.get_config().guilds[0]) dpytest.get_config().channels.append(channel) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel <#"+str(channel.id)+">") + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel <#" + str(channel.id) + ">") assert_embed = createNewModChannelEmbed(channel) assert dpytest.verify().message().embed(embed=assert_embed) - result = text_filter_db_manager.database_manager.db_execute_select("SELECT channel_id FROM TextFilterModeration WHERE guild_id = ?;", args=[channel.guild.id]) + result = text_filter_db_manager.database_manager.db_execute_select( + "SELECT channel_id FROM TextFilterModeration WHERE guild_id = ?;", args=[channel.guild.id]) assert is_int(result[0][0]) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_add_mod_channel_empty(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel") + @pytest.mark.asyncio() async def test_add_mod_channel_unrecognised_channel(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel 123") + @pytest.mark.asyncio() async def test_add_mod_channel_too_many_arguments(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=dpytest.get_config().guilds[0]) dpytest.get_config().channels.append(channel) with pytest.raises(Exception): - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+str(channel.id)+" a b c d e") + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + str(channel.id) + " a b c d e") + @pytest.mark.asyncio() async def test_remove_mod_channel(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=dpytest.get_config().guilds[0]) channelId = str(channel.id) dpytest.get_config().channels.append(channel) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+channelId) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + channelId) assert_embed = createNewModChannelEmbed(channel) assert dpytest.verify().message().embed(embed=assert_embed) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeModChannel "+channelId) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeModChannel " + channelId) assert_embed = removeModChannelEmbed(channel) assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_remove_mod_channel_empty(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeModChannel") + @pytest.mark.asyncio() async def test_remove_mod_channel_too_many_arguments(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeModChannel 123 a b c d e") + @pytest.mark.asyncio() async def test_remove_mod_channel_unrecognised_channel(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeModChannel 123 a b c d e") + @pytest.mark.asyncio() async def test_list_channels(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=dpytest.get_config().guilds[0]) dpytest.get_config().channels.append(channel) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+str(channel.id)) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + str(channel.id)) assert_embed = createNewModChannelEmbed(channel) assert dpytest.verify().message().embed(embed=assert_embed) @@ -357,32 +459,38 @@ async def test_list_channels(tf_cog): assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_list_multiple_channels(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel1 = dpytest.backend.make_text_channel(name="TestChannel1", guild=dpytest.get_config().guilds[0]) channel2 = dpytest.backend.make_text_channel(name="TestChannel2", guild=dpytest.get_config().guilds[0]) dpytest.get_config().channels.append(channel1) dpytest.get_config().channels.append(channel2) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+str(channel1.id)) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + str(channel1.id)) assert_embed = createNewModChannelEmbed(channel1) assert dpytest.verify().message().embed(embed=assert_embed) - await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel "+str(channel2.id)) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "setupModChannel " + str(channel2.id)) assert_embed = createNewModChannelEmbed(channel2) assert dpytest.verify().message().embed(embed=assert_embed) await dpytest.message(KoalaBot.COMMAND_PREFIX + "listModChannels") - assert_embed = listModChannelEmbed([channel1,channel2]) + assert_embed = listModChannelEmbed([channel1, channel2]) assert dpytest.verify().message().embed(embed=assert_embed) cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_ignore_channel(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) channel1 = dpytest.backend.make_text_channel(name="TestChannel1", guild=dpytest.get_config().guilds[0]) await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word ignoreme") - assertFilteredConfirmation("ignoreme","banned") + assertFilteredConfirmation("ignoreme", "banned") await dpytest.message(KoalaBot.COMMAND_PREFIX + "ignoreChannel " + channel1.mention) assertNewIgnore(channel1.mention) @@ -396,10 +504,13 @@ async def test_ignore_channel(tf_cog): cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_ignore_user(tf_cog): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) message = await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word ignoreuser") - assertFilteredConfirmation("ignoreuser","banned") + assertFilteredConfirmation("ignoreuser", "banned") # Should be deleted and warned await dpytest.message("ignoreuser") @@ -412,17 +523,24 @@ async def test_ignore_user(tf_cog): await dpytest.message("ignoreuser") cleanup(dpytest.get_config().guilds[0].id, tf_cog) + @pytest.mark.asyncio() async def test_ignore_empty_user(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) with pytest.raises(Exception): await dpytest.message(KoalaBot.COMMAND_PREFIX + "ignoreUser") + @pytest.mark.asyncio() async def test_unignore_channel(): + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) message = await dpytest.message(KoalaBot.COMMAND_PREFIX + "filter_word ignoreuser") - assertFilteredConfirmation("ignoreuser","banned") + assertFilteredConfirmation("ignoreuser", "banned") - await dpytest.message(KoalaBot.COMMAND_PREFIX + "ignoreChannel " + dpytest.get_config().guilds[0].channels[0].mention) + await dpytest.message( + KoalaBot.COMMAND_PREFIX + "ignoreChannel " + dpytest.get_config().guilds[0].channels[0].mention) assertNewIgnore(dpytest.get_config().guilds[0].channels[0].mention) # Should be ignored @@ -435,9 +553,13 @@ async def test_unignore_channel(): await dpytest.message("ignoreuser") assertBannedWarning("ignoreuser") + @pytest.mark.asyncio() async def test_list_ignored(): - mes = await dpytest.message(KoalaBot.COMMAND_PREFIX + "ignoreChannel " + dpytest.get_config().guilds[0].channels[0].mention) + KoalaBot.database_manager.insert_setup_status(dpytest.get_config().guilds[0].id) + KoalaBot.database_manager.update_guild_setup_status(dpytest.get_config().guilds[0].id) + mes = await dpytest.message( + KoalaBot.COMMAND_PREFIX + "ignoreChannel " + dpytest.get_config().guilds[0].channels[0].mention) assertNewIgnore(dpytest.get_config().guilds[0].channels[0].mention) await dpytest.message(KoalaBot.COMMAND_PREFIX + "ignoreUser " + mes.author.mention) @@ -446,11 +568,13 @@ async def test_list_ignored(): await dpytest.message(KoalaBot.COMMAND_PREFIX + "listIgnored") assert listIgnoredEmbed([dpytest.get_config().guilds[0].channels[0], mes.author]) + @pytest.fixture(autouse=True) async def clear_queue(): await dpytest.empty_queue() yield dpytest + @pytest.fixture(scope='session', autouse=True) def setup_is_dpytest(): KoalaBot.is_dpytest = True diff --git a/tests/test_TwitchAlert.py b/tests/test_TwitchAlert.py index ba139ab7..c068f54b 100644 --- a/tests/test_TwitchAlert.py +++ b/tests/test_TwitchAlert.py @@ -35,10 +35,10 @@ def setup_module(): try: if os.name == 'nt': - print("Windows Detected: Deleting windows_"+DB_PATH) - os.remove("windows_"+DB_PATH) + print("Windows Detected: Deleting windows_" + DB_PATH) + os.remove("windows_" + DB_PATH) else: - print("Windows Not Detected: Deleting "+DB_PATH) + print("Windows Not Detected: Deleting " + DB_PATH) os.remove(DB_PATH) KoalaBot.is_dpytest = True except FileNotFoundError: @@ -104,6 +104,9 @@ async def twitch_cog(bot): @mock.patch("utils.KoalaUtils.random_id", mock.MagicMock(return_value=7357)) @pytest.mark.asyncio(order=1) async def test_edit_default_message_default_from_none(twitch_cog): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) this_channel = dpytest.get_config().channels[0] assert_embed = discord.Embed(title="Default Message Edited", description=f"Guild: {dpytest.get_config().guilds[0].id}\n" @@ -117,6 +120,9 @@ async def test_edit_default_message_default_from_none(twitch_cog): @mock.patch("utils.KoalaUtils.random_id", mock.MagicMock(return_value=7357)) @pytest.mark.asyncio(order=2) async def test_edit_default_message_existing(twitch_cog): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) this_channel = dpytest.get_config().channels[0] assert_embed = discord.Embed(title="Default Message Edited", description=f"Guild: {dpytest.get_config().guilds[0].id}\n" @@ -129,6 +135,9 @@ async def test_edit_default_message_existing(twitch_cog): @pytest.mark.asyncio(order=3) async def test_add_user_to_twitch_alert(twitch_cog): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) assert_embed = discord.Embed(title="Added User to Twitch Alert", description=f"Channel: {dpytest.get_config().channels[0].id}\n" f"User: monstercat\n" @@ -144,6 +153,8 @@ async def test_add_user_to_twitch_alert(twitch_cog): async def test_add_user_to_twitch_alert_wrong_guild(twitch_cog): guild = dpytest.backend.make_guild(name="TestGuild") channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) member = await dpytest.member_join(1, name="TestUser", discrim=1) @@ -161,6 +172,8 @@ async def test_add_user_to_twitch_alert_custom_message(twitch_cog): test_custom_message = "We be live gamers!" guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -189,6 +202,8 @@ async def test_remove_user_from_twitch_alert_with_message(twitch_cog): # Creates guild and channels and adds user and bot guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -218,6 +233,8 @@ async def test_remove_user_from_twitch_alert_with_message(twitch_cog): @pytest.mark.asyncio(order=3) async def test_remove_user_from_twitch_alert_wrong_guild(twitch_cog): guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -235,6 +252,8 @@ async def test_remove_user_from_twitch_alert_wrong_guild(twitch_cog): async def test_add_team_to_twitch_alert(twitch_cog): # Creates guild and channels and adds user and bot guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -255,6 +274,8 @@ async def test_add_team_to_twitch_alert(twitch_cog): async def test_add_team_to_twitch_alert_with_message(twitch_cog): # Creates guild and channels and adds user and bot guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -275,6 +296,8 @@ async def test_add_team_to_twitch_alert_with_message(twitch_cog): async def test_add_team_to_twitch_alert_wrong_guild(twitch_cog): # Creates guild and channels and adds user and bot guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -294,6 +317,8 @@ async def test_remove_team_from_twitch_alert_with_message(twitch_cog): # Creates guild and channels and adds user and bot guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -317,6 +342,8 @@ async def test_remove_team_from_twitch_alert_with_message(twitch_cog): @pytest.mark.asyncio(order=3) async def test_remove_team_from_twitch_alert_wrong_guild(twitch_cog): guild = dpytest.backend.make_guild(name="TestGuild") + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild) dpytest.get_config().guilds.append(guild) dpytest.get_config().channels.append(channel) @@ -346,6 +373,9 @@ async def test_on_ready(twitch_cog: TwitchAlert.TwitchAlert): @pytest.mark.skip(reason="Issues with testing inside asyncio event loop, not implemented") @pytest.mark.asyncio async def test_loop_check_live(twitch_cog): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) this_channel = dpytest.get_config().channels[0] expected_embed = discord.Embed(colour=KoalaBot.KOALA_GREEN, title="<:twitch:734024383957434489> Monstercat is now streaming!", @@ -394,7 +424,7 @@ async def test_get_new_twitch_oauth(twitch_api_handler): @pytest.mark.asyncio async def test_requests_get(twitch_api_handler): assert (await twitch_api_handler.requests_get("https://api.twitch.tv/helix/streams?", - params=(('user_login', 'monstercat'),))).get("data") is not None + params=(('user_login', 'monstercat'),))).get("data") is not None @pytest.mark.asyncio @@ -542,6 +572,7 @@ def test_add_team_to_ta_custom_message(twitch_alert_db_manager_tables, channel_i assert twitch_alert_db_manager_tables.get_parent_database_manager().db_execute_select(sql_select_team) == \ [("Message here",)] + @pytest.mark.asyncio() async def test_remove_team_from_ta(twitch_alert_db_manager_tables): test_add_team_to_ta_custom_message(twitch_alert_db_manager_tables, channel_id=590, guild_id=591) @@ -603,7 +634,7 @@ async def test_update_all_teams_members(twitch_alert_db_manager_tables): @pytest.mark.asyncio() async def test_delete_all_offline_streams(twitch_alert_db_manager_tables, bot: discord.ext.commands.Bot): - message_id = (await dpytest.message("test_msg",bot.guilds[0].channels[0])).id + message_id = (await dpytest.message("test_msg", bot.guilds[0].channels[0])).id sql_add_message = "INSERT INTO UserInTwitchAlert(channel_id, twitch_username, custom_message, message_id) " \ f"VALUES({bot.guilds[0].channels[0].id},'monstercat',Null,{message_id}) " twitch_alert_db_manager_tables.get_parent_database_manager().db_execute_commit(sql_add_message) diff --git a/tests/test_Verification.py b/tests/test_Verification.py index 1fe829d9..2fb26e50 100644 --- a/tests/test_Verification.py +++ b/tests/test_Verification.py @@ -9,6 +9,7 @@ # Built-in/Generic Imports import asyncio # Libs +import discord import discord.ext.test as dpytest import pytest from discord.ext import commands @@ -44,8 +45,12 @@ def setup_function(): db_manager.db_execute_commit("CREATE TABLE to_re_verify (u_id, r_id)") db_manager.db_execute_commit("CREATE TABLE roles (s_id, r_id, email_suffix)") db_manager.insert_extension("Verify", 0, True, True) + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) print("Tests starting") + @pytest.fixture(autouse=True) def cog(bot): cog = Verification.Verification(bot, db_manager) @@ -63,6 +68,7 @@ def cog(bot): print("Tests starting") return cog + @pytest.mark.asyncio async def test_member_join_no_verify(): await dpytest.member_join() @@ -73,16 +79,19 @@ async def test_member_join_no_verify(): async def test_member_join_verif_enabled(): test_config = dpytest.get_config() guild = dpytest.back.make_guild("testMemberJoin", id_num=1234) + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) test_config.guilds.append(guild) dpytest.back.make_role("testRole", guild, id_num=555) db_manager.db_execute_commit(f"INSERT INTO roles VALUES (1234, 555, '{TEST_EMAIL_DOMAIN}')") - welcome_message = f"""Welcome to testMemberJoin. This guild has verification enabled. -Please verify one of the following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. -This email is stored so you don't need to verify it multiple times across servers. -`{TEST_EMAIL_DOMAIN}` for `@testRole`""" + # welcome_message = f"""Welcome to testMemberJoin. This guild has verification enabled. Please verify one of the + # following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. + # This email is stored so you don't need to verify it multiple times across servers. `{TEST_EMAIL_DOMAIN}` for + # `@testRole`""" await dpytest.member_join(1) await asyncio.sleep(0.25) - assert dpytest.verify().message().content(welcome_message) + assert dpytest.verify().message().contains().content("""This email is stored so you don't need to verify it multiple times across servers. +`koalabot.uk` for `@testRole`""") db_manager.db_execute_commit("DELETE FROM roles WHERE s_id=1234") @@ -90,6 +99,8 @@ async def test_member_join_verif_enabled(): async def test_member_join_already_verified(bot): test_config = dpytest.get_config() guild = dpytest.back.make_guild("testMemberJoin", id_num=1234) + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) bot.guilds.append(guild) test_user = dpytest.back.make_user("TestUser", 1234, id_num=999) @@ -98,11 +109,11 @@ async def test_member_join_already_verified(bot): db_manager.db_execute_commit(f"INSERT INTO roles VALUES (1234, 555, '{TEST_EMAIL_DOMAIN}')") await dpytest.member_join(guild, test_user) await asyncio.sleep(0.25) - welcome_message = f"""Welcome to testMemberJoin. This guild has verification enabled. -Please verify one of the following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. -This email is stored so you don't need to verify it multiple times across servers. -`{TEST_EMAIL_DOMAIN}` for `@testRole`""" - assert dpytest.verify().message().content(welcome_message) + # welcome_message = f"""Welcome to testMemberJoin. This guild has verification enabled. Please verify one of the + # following emails to get the appropriate role using `{KoalaBot.COMMAND_PREFIX}verify your_email@example.com`. + # This email is stored so you don't need to verify it multiple times across servers. `{TEST_EMAIL_DOMAIN}` for + # `@testRole`""" + assert dpytest.verify().message().contains().content(TEST_EMAIL_DOMAIN) member = guild.get_member(test_user.id) assert role in member.roles db_manager.db_execute_commit("DELETE FROM verified_emails WHERE u_id=999") @@ -113,9 +124,12 @@ async def test_member_join_already_verified(bot): async def test_enable_verification(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) role = dpytest.back.make_role("testRole", guild, id_num=555) await dpytest.message(KoalaBot.COMMAND_PREFIX + f"addVerification {TEST_EMAIL_DOMAIN} <@&555>") - assert dpytest.verify().message().content(f"Verification enabled for <@&555> for emails ending with `{TEST_EMAIL_DOMAIN}`") + assert dpytest.verify().message().content( + f"Verification enabled for <@&555> for emails ending with `{TEST_EMAIL_DOMAIN}`") entry = db_manager.db_execute_select("SELECT * FROM roles WHERE s_id=? AND r_id=?", (guild.id, role.id)) assert entry @@ -126,6 +140,8 @@ async def test_enable_verification(): async def test_disable_verification(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) role = dpytest.back.make_role("testRole", guild, id_num=555) db_manager.db_execute_commit(f"INSERT INTO roles VALUES ({guild.id}, 555, 'egg.com')") await dpytest.message(KoalaBot.COMMAND_PREFIX + "removeVerification egg.com <@&555>") @@ -139,11 +155,14 @@ async def test_disable_verification(): async def test_verify(): test_config = dpytest.get_config() guild = test_config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) member = guild.members[0] dm = await member.create_dm() await dpytest.message(KoalaBot.COMMAND_PREFIX + f"verify {TEST_EMAIL}", dm) assert dpytest.verify().message().content("Please verify yourself using the command you have been emailed") - entry = db_manager.db_execute_select(f"SELECT * FROM non_verified_emails WHERE u_id={member.id} AND email='{TEST_EMAIL}'") + entry = db_manager.db_execute_select( + f"SELECT * FROM non_verified_emails WHERE u_id={member.id} AND email='{TEST_EMAIL}'") assert entry @@ -151,14 +170,18 @@ async def test_verify(): async def test_confirm(): test_config = dpytest.get_config() guild = test_config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) member = guild.members[0] role = dpytest.back.make_role("testRole", guild, id_num=555) db_manager.db_execute_commit(f"INSERT INTO roles VALUES ({guild.id}, 555, 'egg.com')") db_manager.db_execute_commit(f"INSERT INTO non_verified_emails VALUES ({member.id}, 'test@egg.com', 'testtoken')") dm = await member.create_dm() await dpytest.message(KoalaBot.COMMAND_PREFIX + "confirm testtoken", dm) - verified = db_manager.db_execute_select(f"SELECT * FROM verified_emails WHERE u_id={member.id} AND email='test@egg.com'") - exists = db_manager.db_execute_select(f"SELECT * FROM non_verified_emails WHERE u_id={member.id} and email='test@egg.com'") + verified = db_manager.db_execute_select( + f"SELECT * FROM verified_emails WHERE u_id={member.id} AND email='test@egg.com'") + exists = db_manager.db_execute_select( + f"SELECT * FROM non_verified_emails WHERE u_id={member.id} and email='test@egg.com'") assert verified assert not exists await asyncio.sleep(0.5) @@ -172,6 +195,8 @@ async def test_confirm(): async def test_un_verify(): test_config = dpytest.get_config() guild = test_config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) role = dpytest.back.make_role("testRole", guild, id_num=555) member = test_config.members[0] await dpytest.add_role(member, role) @@ -180,7 +205,8 @@ async def test_un_verify(): dm = await member.create_dm() await dpytest.message(KoalaBot.COMMAND_PREFIX + "unVerify test@egg.com", dm) assert dpytest.verify().message().content("test@egg.com has been un-verified and relevant roles have been removed") - entry = db_manager.db_execute_select(f"SELECT * FROM verified_emails WHERE u_id={member.id} AND email='test@egg.com'") + entry = db_manager.db_execute_select( + f"SELECT * FROM verified_emails WHERE u_id={member.id} AND email='test@egg.com'") assert not entry assert role not in member.roles db_manager.db_execute_commit(f"DELETE FROM roles WHERE s_id={guild.id}") @@ -188,6 +214,9 @@ async def test_un_verify(): @pytest.mark.asyncio async def test_get_emails(): + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) db_manager.db_execute_commit(f"INSERT INTO verified_emails VALUES (123, '{TEST_EMAIL}')") await dpytest.message(KoalaBot.COMMAND_PREFIX + "getEmails 123") assert dpytest.verify().message().content(f"""This user has registered with:\n{TEST_EMAIL}""") @@ -198,6 +227,9 @@ async def test_get_emails(): async def test_re_verify(): test_config = dpytest.get_config() guild = test_config.guilds[0] + guild: discord.Guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) role = dpytest.back.make_role("testRole", guild, id_num=555) member = test_config.members[0] await dpytest.add_role(member, role) @@ -207,14 +239,96 @@ async def test_re_verify(): assert role not in member.roles blacklisted = db_manager.db_execute_select(f"SELECT * FROM to_re_verify WHERE u_id={member.id}") assert blacklisted - assert dpytest.verify().message().content("That role has now been removed from all users and they will need to re-verify the associated email.") + assert dpytest.verify().message().content( + "That role has now been removed from all users and they will need to re-verify the associated email.") db_manager.db_execute_commit(f"DELETE FROM verified_emails WHERE u_id={member.id}") db_manager.db_execute_commit(f"DELETE FROM roles WHERE s_id={guild.id}") db_manager.db_execute_commit(f"DELETE FROM to_re_verify WHERE u_id={member.id}") +@pytest.mark.asyncio +async def test_on_guild_leave(): + test_config = dpytest.get_config() + guild = test_config.guilds[0] + client = test_config.client + bot_member = test_config.guilds[0].get_member(client.user.id) + dpytest.backend.delete_member(bot_member) + with pytest.raises(IndexError): + db_manager.fetch_dm_email_list_status(guild.id) + + +@pytest.mark.asyncio +async def test_toggle_on_dm_list(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) + KoalaBot.database_manager.insert_email_list_status(guild.id) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "verifyDM True") + assert KoalaBot.database_manager.fetch_dm_email_list_status(guild.id) + assert dpytest.verify().message().contains().content(f"Users in {guild.name} will be messaged by the bot to verify their email") + + +@pytest.mark.asyncio +async def test_toggle_off_dm_list(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) + KoalaBot.database_manager.insert_email_list_status(guild.id) + await dpytest.message(KoalaBot.COMMAND_PREFIX + "verifyDM False") + f = KoalaBot.database_manager.fetch_dm_email_list_status(guild.id) + assert dpytest.verify().message().contains().content(f"Users in {guild.name} will no longer be messaged by the bot to verify their email") + + +@pytest.mark.asyncio +async def test_fetch_dm_email_list_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_email_list_status(guild.id) + assert KoalaBot.database_manager.fetch_dm_email_list_status(guild.id) == 1 + + +@pytest.mark.asyncio +async def test_update_dm_email_list_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_email_list_status(guild.id) + KoalaBot.database_manager.update_dm_email_list_status(guild.id, 0) + assert KoalaBot.database_manager.fetch_dm_email_list_status(guild.id) == 0 + + +@pytest.mark.asyncio +async def test_remove_dm_email_list_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_email_list_status(guild.id) + KoalaBot.database_manager.remove_dm_email_list_status(guild.id) + with pytest.raises(IndexError): + (KoalaBot.database_manager.fetch_dm_email_list_status(guild.id)) + + +@pytest.mark.asyncio +async def test_fetch_guild_setup_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + assert KoalaBot.database_manager.fetch_guild_setup_status(guild.id) == 0 + + +@pytest.mark.asyncio +async def test_update_guild_setup_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) + assert KoalaBot.database_manager.fetch_guild_setup_status(guild.id) == 1 + + +@pytest.mark.asyncio +async def test_remove_guild_setup_status(): + guild = dpytest.get_config().guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.remove_guild_status(guild.id) + with pytest.raises(IndexError): + (KoalaBot.database_manager.fetch_guild_setup_status(guild.id)) + + @pytest.fixture(scope='session', autouse=True) def setup_is_dpytest(): KoalaBot.is_dpytest = True yield - KoalaBot.is_dpytest = False \ No newline at end of file + KoalaBot.is_dpytest = False diff --git a/tests/test_Voting.py b/tests/test_Voting.py index 24607867..6b8b4d33 100644 --- a/tests/test_Voting.py +++ b/tests/test_Voting.py @@ -50,7 +50,6 @@ def populate_vote_tables(): db_manager.db_execute_commit("INSERT INTO VoteOptions VALUES (?, ?, ?, ?)", (112, 888, "vote1opt", "vote1body")) - @pytest.fixture(autouse=True) def cog(bot): global vote_manager @@ -66,6 +65,7 @@ def cog(bot): print("Tests starting") return cog + @pytest.fixture(scope='session', autouse=True) def setup_is_dpytest(): KoalaBot.is_dpytest = True @@ -77,8 +77,11 @@ def setup_is_dpytest(): async def test_discord_create_vote(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") - assert dpytest.verify().message().content(f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") + assert dpytest.verify().message().content( + f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") in_db = db_manager.db_execute_select("SELECT * FROM Votes")[0] assert in_db assert in_db[1] == guild.members[0].id @@ -89,22 +92,29 @@ async def test_discord_create_vote(): async def test_discord_create_vote_wrong(): config = dpytest.get_config() guild = config.guilds[0] - db_manager.db_execute_commit("INSERT INTO Votes VALUES (?, ?, ?, ?, ?, ?, ?)", (111, guild.members[0].id, guild.id, "Test Vote", None, None, None)) + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) + db_manager.db_execute_commit("INSERT INTO Votes VALUES (?, ?, ?, ?, ?, ?, ?)", + (111, guild.members[0].id, guild.id, "Test Vote", None, None, None)) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") assert dpytest.verify().message().content("You already have a vote with title Test Vote sent!") - await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + await dpytest.message( + f"{KoalaBot.COMMAND_PREFIX}vote create aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") assert dpytest.verify().message().content("Title too long") await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote 2") assert dpytest.verify().message().content( f"Vote titled `Test Vote 2` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote 3") - assert dpytest.verify().message().content(f"You already have an active vote in {guild.name}. Please send that with `{KoalaBot.COMMAND_PREFIX}vote send` before creating a new one.") + assert dpytest.verify().message().content( + f"You already have an active vote in {guild.name}. Please send that with `{KoalaBot.COMMAND_PREFIX}vote send` before creating a new one.") @pytest.mark.asyncio async def test_discord_vote_add_and_remove_role(cog): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") assert dpytest.verify().message().content( f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") @@ -113,7 +123,8 @@ async def test_discord_vote_add_and_remove_role(cog): vote = cog.vote_manager.get_configuring_vote(guild.members[0].id) assert guild.roles[0].id in vote.target_roles await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote removeRole {guild.roles[0].id}") - assert dpytest.verify().message().content(f"Vote will no longer be sent to those with the {guild.roles[0].name} role") + assert dpytest.verify().message().content( + f"Vote will no longer be sent to those with the {guild.roles[0].name} role") assert guild.roles[0].id not in vote.target_roles @@ -121,6 +132,8 @@ async def test_discord_vote_add_and_remove_role(cog): async def test_discord_set_chair(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") assert dpytest.verify().message().content( f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") @@ -130,10 +143,13 @@ async def test_discord_set_chair(): await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote setChair") assert dpytest.verify().message().content("Results will be sent to the channel vote is closed in") + @pytest.mark.asyncio async def test_discord_add_remove_option(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") assert dpytest.verify().message().content( f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") @@ -149,6 +165,8 @@ async def test_discord_add_remove_option(): async def test_discord_cancel_vote(): config = dpytest.get_config() guild = config.guilds[0] + KoalaBot.database_manager.insert_setup_status(guild.id) + KoalaBot.database_manager.update_guild_setup_status(guild.id) await dpytest.message(f"{KoalaBot.COMMAND_PREFIX}vote create Test Vote") assert dpytest.verify().message().content( f"Vote titled `Test Vote` created for guild {guild.name}. Use `{KoalaBot.COMMAND_PREFIX}help vote` to see how to configure it.") @@ -164,7 +182,8 @@ def test_option(): def test_votemanager_generate_opt_id(): - db_manager.db_execute_commit("INSERT INTO VoteOptions VALUES (?, ?, ?, ?)", (123, 100000000000000001, "test", "option")) + db_manager.db_execute_commit("INSERT INTO VoteOptions VALUES (?, ?, ?, ?)", + (123, 100000000000000001, "test", "option")) opt_id = vote_manager.generate_unique_opt_id() assert opt_id != 100000000000000001 diff --git a/utils/KoalaDBManager.py b/utils/KoalaDBManager.py index 175fd0d1..f37a6432 100644 --- a/utils/KoalaDBManager.py +++ b/utils/KoalaDBManager.py @@ -12,6 +12,7 @@ # Libs from dotenv import load_dotenv + load_dotenv() ENCRYPTED_DB = eval(os.environ.get('ENCRYPTED', "True")) if ENCRYPTED_DB: @@ -23,6 +24,7 @@ print("Database Encryption Enabled") from pysqlcipher3 import dbapi2 as sqlite3 + # Own modules @@ -129,13 +131,123 @@ def create_base_tables(self): welcome_message text );""" + sql_create_guild_setup_table = """ + CREATE TABLE IF NOT EXISTS GuildSetupStatus( + guild_id integer NOT NULL PRIMARY KEY, + accepted_setup BOOLEAN NOT NULL CHECK (accepted_setup IN (0, 1)) + ); + """ + + sql_create_guild_dm_email_list_status_table = """ + CREATE TABLE IF NOT EXISTS GuildDMEmailListStatus( + guild_id integer NOT NULL PRIMARY KEY, + dm_email_list_status BOOLEAN NOT NULL CHECK (dm_email_list_status IN (0, 1)) + ); + """ + self.db_execute_commit(sql_create_guild_welcome_messages_table) self.db_execute_commit(sql_create_koala_extensions_table) self.db_execute_commit(sql_create_guild_extensions_table) + self.db_execute_commit(sql_create_guild_setup_table) + self.db_execute_commit(sql_create_guild_dm_email_list_status_table) + + def insert_setup_status(self, guild_id): + """ + Adds a default setup status of 0 (false) for a guild + :param guild_id: guild ID + """ + self.db_execute_commit( + "INSERT INTO GuildSetupStatus VALUES (?, 0 );", + args=[guild_id]) + return self.fetch_guild_setup_status(guild_id) + + def fetch_guild_setup_status(self, guild_id): + """ + Gets the setup status for a guild + :param guild_id: guild ID + return: the guild setup status + """ + return ((self.db_execute_select(""" + SELECT accepted_setup + FROM GuildSetupStatus + WHERE guild_id = ? + """, args=[guild_id], pass_errors=True)[0][0])) + + def update_guild_setup_status(self, guild_id): + """ + Sets the guild setup status from 0 (false) to 1 (true) + :param guild_id: guild ID + """ + sql_update_guild_status =""" + UPDATE + GuildSetupStatus + SET + accepted_setup = 1 + WHERE + guild_id = ?""" + self.db_execute_commit(sql_update_guild_status, args=[guild_id]) + + def remove_guild_status(self, guild_id): + """ + Removes a guild from the GuildSetupStatus table + :param guild_id: guild ID + """ + sql_remove_guild_status = """ + DELETE FROM GuildSetupStatus + WHERE guild_id = ? + """ + self.db_execute_commit(sql_remove_guild_status, args=[guild_id], pass_errors=True) + + def insert_email_list_status(self, guild_id): + """ + Adds a default email list status of 1 (true) for a guild + :param guild_id: guild ID + """ + self.db_execute_commit( + "INSERT INTO GuildDMEmailListStatus VALUES (?, 1 );", + args=[guild_id]) + return self.fetch_dm_email_list_status(guild_id) + + def fetch_dm_email_list_status(self, guild_id): + """ + Gets the email list status for a guild + :param guild_id: guild ID + :return: the email list status (boolean) + """ + return (self.db_execute_select(""" + SELECT dm_email_list_status + FROM GuildDMEmailListStatus + WHERE guild_id = ? + """, args=[guild_id], pass_errors=True)[0][0]) != 0 + + def update_dm_email_list_status(self, guild_id, toggle): + """ + Sets the guild email list status to the value of toggle + :param guild_id: guild ID + :param toggle: The value to set the email list status to (0 or 1) + """ + sql_update_dm_email_list_status =""" + UPDATE + GuildDMEmailListStatus + SET + dm_email_list_status = ? + WHERE + guild_id = ?""" + self.db_execute_commit(sql_update_dm_email_list_status, args=[toggle, guild_id]) + + def remove_dm_email_list_status(self, guild_id): + """ + Removes a guild from the GuildDMEmailListStatus table + :param guild_id: guild ID + """ + sql_remove_dm_email_list_status = """ + DELETE FROM GuildDMEmailListStatus + WHERE guild_id = ? + """ + self.db_execute_commit(sql_remove_dm_email_list_status, args=[guild_id], pass_errors=True) def insert_extension(self, extension_id: str, subscription_required: int, available: bool, enabled: bool): sql_check_extension_exists = """SELECT * FROM KoalaExtensions WHERE extension_id = ?""" - if len(self.db_execute_select(sql_check_extension_exists, args=[extension_id])) > 0: sql_update_extension = """ UPDATE KoalaExtensions @@ -152,7 +264,6 @@ def insert_extension(self, extension_id: str, subscription_required: int, availa self.db_execute_commit(sql_insert_extension, args=[extension_id, subscription_required, available, enabled]) - def extension_enabled(self, guild_id, extension_id): sql_select_extension = "SELECT extension_id " \ "FROM GuildExtensions " \