From 5ef2b679228ef8ad937b967b69c3ed50e1304a9f Mon Sep 17 00:00:00 2001 From: Tristan Farkas <15787558+trilleplay@users.noreply.github.com> Date: Sat, 5 Oct 2019 16:43:12 +0200 Subject: [PATCH 1/2] Add auto clean up support for clean messages. --- GearBot/Bot/TheRealGearBot.py | 1 + GearBot/Cogs/Moderation.py | 29 +++++++++++++++++++++++------ GearBot/Util/Configuration.py | 5 ++++- GearBot/Util/MessageUtils.py | 26 +++++++++++++++++++++++++- config/template.json | 5 +++-- 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/GearBot/Bot/TheRealGearBot.py b/GearBot/Bot/TheRealGearBot.py index 5d6e45c1..aaff599a 100644 --- a/GearBot/Bot/TheRealGearBot.py +++ b/GearBot/Bot/TheRealGearBot.py @@ -77,6 +77,7 @@ async def initialize(bot, startup=False): bot.being_cleaned.clear() await Configuration.initialize(bot) DashConfig.initialize(bot) + MessageUtils.initialize(bot) except Exception as ex: #make sure we always unlock, even when something went wrong! bot.locked = False diff --git a/GearBot/Cogs/Moderation.py b/GearBot/Cogs/Moderation.py index d8ead53d..99cbfe7f 100644 --- a/GearBot/Cogs/Moderation.py +++ b/GearBot/Cogs/Moderation.py @@ -882,8 +882,12 @@ async def clean(self, ctx): async def clean_user(self, ctx, users: Greedy[DiscordUser], amount: RangedInt(1) = 50): """clean_user_help""" if len(users) is 0: - await MessageUtils.send_to(ctx, 'NO', 'clean_missing_targets') + m = await MessageUtils.send_to(ctx, 'NO', 'clean_missing_targets') + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) + await MessageUtils.cleanup_message("Moderation_clean", m) + return await self._clean(ctx, amount, lambda m: any(m.author.id == user.id for user in users)) + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) @clean.command("bots") @commands.guild_only() @@ -891,12 +895,14 @@ async def clean_user(self, ctx, users: Greedy[DiscordUser], amount: RangedInt(1) async def clean_bots(self, ctx, amount: RangedInt(1) = 50): """clean_bots_help""" await self._clean(ctx, amount, lambda m: m.author.bot) + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) @clean.command("all") @commands.guild_only() @commands.bot_has_permissions(manage_messages=True) async def clean_all(self, ctx, amount: RangedInt(1, 5000)): """clean_all_help""" + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) await self._clean(ctx, amount, lambda m: True, check_amount=amount) @clean.command("last") @@ -907,6 +913,7 @@ async def clean_last(self, ctx, duration: Duration, excess=""): if duration.unit is None: duration.unit = excess until = datetime.datetime.utcfromtimestamp(time.time() - duration.to_seconds(ctx)) + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) await self._clean(ctx, 5000, lambda m: True, after=until) @clean.command("until") @@ -914,6 +921,7 @@ async def clean_last(self, ctx, duration: Duration, excess=""): @commands.bot_has_permissions(manage_messages=True) async def clean_until(self, ctx, message:Message(local_only=True)): """clean_until_help""" + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) await self._clean(ctx, 5000, lambda m: True, after=Object(message.id-1)) @clean.command("between") @@ -923,6 +931,7 @@ async def clean_between(self, ctx, start: Message(local_only=True), end: Message """clean_between_help""" a = min(start.id, end.id) b = max(start.id, end.id) + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) await self._clean(ctx, 5000, lambda m: True , before=Object(b+1), after=Object(a+1)) @clean.command("everywhere") @@ -931,12 +940,16 @@ async def clean_between(self, ctx, start: Message(local_only=True), end: Message async def clean_everywhere(self, ctx, users: Greedy[DiscordUser], amount: RangedInt(1) = 50): """clean_everywhere_help""" if len(users) is 0: - await MessageUtils.send_to(ctx, 'NO', 'clean_missing_targets') + m = await MessageUtils.send_to(ctx, 'NO', 'clean_missing_targets') + await MessageUtils.cleanup_message("Moderation_clean", m) + return total = 0 if any(channel.id in self.bot.being_cleaned for channel in ctx.guild.text_channels): - await MessageUtils.send_to(ctx, "NO", "already_cleaning") + m = await MessageUtils.send_to(ctx, "NO", "already_cleaning") + await MessageUtils.cleanup_message("Moderation_clean", m) return self.bot.being_cleaned[ctx.channel.id] = set() + await MessageUtils.cleanup_message("Moderation_clean", ctx.message) message = await MessageUtils.send_to(ctx, "REFRESH", "processing") failed = set() for channel in ctx.guild.text_channels: @@ -955,13 +968,15 @@ def check(message): failed.add(channel) finally: self.bot.loop.create_task(self.finish_cleaning(channel.id, ctx.guild.id)) - await MessageUtils.try_edit(message, 'YES', 'purge_everywhere_complete', count=total, channels=len(ctx.guild.text_channels) - len(failed), failed=len(failed)) + m = await MessageUtils.try_edit(message, 'YES', 'purge_everywhere_complete', count=total, channels=len(ctx.guild.text_channels) - len(failed), failed=len(failed)) + await MessageUtils.cleanup_message("Moderation_clean", message) async def _clean(self, ctx, amount, checker, before=None, after=None, check_amount=None): counter = 0 if ctx.channel.id in self.bot.being_cleaned: - await MessageUtils.send_to(ctx, "NO", "already_cleaning") + m = await MessageUtils.send_to(ctx, "NO", "already_cleaning") + await MessageUtils.cleanup_message("Moderation_clean", m) return self.bot.being_cleaned[ctx.channel.id] = set() message = await MessageUtils.send_to(ctx, "REFRESH", "processing") @@ -978,11 +993,13 @@ def check(message): # sleep for a sec just in case the other bot is still purging so we don't get removed as well await asyncio.sleep(1) try: - await MessageUtils.try_edit(message, 'NO', 'purge_fail_not_found') + m = await MessageUtils.try_edit(message, 'NO', 'purge_fail_not_found') + await MessageUtils.cleanup_message("Moderation_clean", m) except discord.NotFound: pass # sometimes people remove channels mid purge else: await MessageUtils.try_edit(message, "YES", "purge_confirmation", count=len(deleted)) + await MessageUtils.cleanup_message("Moderation_clean", message) except Exception as ex: self.bot.loop.create_task(self.finish_cleaning(ctx.channel.id, ctx.guild.id)) raise ex diff --git a/GearBot/Util/Configuration.py b/GearBot/Util/Configuration.py index 57b35e82..505fab3b 100644 --- a/GearBot/Util/Configuration.py +++ b/GearBot/Util/Configuration.py @@ -303,6 +303,9 @@ def v22(config): config["PERM_OVERRIDES"]["ServerAdmin"] =config["PERM_OVERRIDES"]["Serveradmin"] del config["PERM_OVERRIDES"]["Serveradmin"] +def v23(config): + config["MSG_AUTO_DELETE"] = {} + def add_logging(config, *args): for cid, info in config["LOG_CHANNELS"].items(): if "FUTURE_LOGS" in info: @@ -325,7 +328,7 @@ def move_keys(config, section, *keys): # migrators for the configs, do NOT increase the version here, this is done by the migration loop -MIGRATORS = [initial_migration, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22] +MIGRATORS = [initial_migration, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23] BOT = None diff --git a/GearBot/Util/MessageUtils.py b/GearBot/Util/MessageUtils.py index 22ce8c46..ff750439 100644 --- a/GearBot/Util/MessageUtils.py +++ b/GearBot/Util/MessageUtils.py @@ -2,15 +2,23 @@ import time from collections import namedtuple from datetime import datetime +import asyncio from discord import Object, HTTPException, MessageType -from Util import Translator, Emoji, Archive +from Util import Translator, Emoji, Archive, Configuration from database import DBUtils from database.DatabaseConnector import LoggedMessage + +def initialize(gearbot): + global bot + bot = gearbot + + Message = namedtuple("Message", "messageid author content channel server attachments type pinned") + def is_cache_enabled(bot): return bot.redis_pool is not None @@ -79,6 +87,22 @@ async def try_edit(message, emoji: str, string_name: str, embed=None, **kwargs): return await send_to(message.channel, emoji, string_name, embed=embed, **kwargs) +async def cleanup_message(name, message, actual_cleanup=False, wait_time=0): + if actual_cleanup: + await asyncio.sleep(wait_time) + await message.delete() + settings = Configuration.get_var(message.guild.id, "MSG_AUTO_DELETE").get(name, None) + if settings is None: + return + if settings["delete_self"]: + if bot.user.id == message.author.id: + asyncio.run_coroutine_threadsafe(cleanup_message(name, message, True, settings["wait_time"]), bot.loop) + return + if settings["delete_user"]: + if bot.user.id != message.author.id: + asyncio.run_coroutine_threadsafe(cleanup_message(name, message, True, settings["wait_time"]), bot.loop) + + def day_difference(a, b, location): diff = a - b return Translator.translate('days_ago', location, days=diff.days, date=a) diff --git a/config/template.json b/config/template.json index 9fb98da4..0c05fdf8 100644 --- a/config/template.json +++ b/config/template.json @@ -1,5 +1,5 @@ { - "VERSION": 22, + "VERSION": 23, "GENERAL": { "LANG": "en_US", "PERM_DENIED_MESSAGE": true, @@ -61,5 +61,6 @@ "TRUSTED_ROLES": [], "TRUSTED_USERS": [] }, - "SERVER_LINKS": [] + "SERVER_LINKS": [], + "MSG_AUTO_DELETE": {} } From 9ed641f2f385bed32367560dbf914d6d056fa175 Mon Sep 17 00:00:00 2001 From: Tristan Farkas <15787558+trilleplay@users.noreply.github.com> Date: Mon, 28 Oct 2019 09:36:31 +0100 Subject: [PATCH 2/2] Clean up function and config structure. --- GearBot/Util/MessageUtils.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/GearBot/Util/MessageUtils.py b/GearBot/Util/MessageUtils.py index ff750439..1af78b6d 100644 --- a/GearBot/Util/MessageUtils.py +++ b/GearBot/Util/MessageUtils.py @@ -87,25 +87,23 @@ async def try_edit(message, emoji: str, string_name: str, embed=None, **kwargs): return await send_to(message.channel, emoji, string_name, embed=embed, **kwargs) -async def cleanup_message(name, message, actual_cleanup=False, wait_time=0): - if actual_cleanup: - await asyncio.sleep(wait_time) - await message.delete() +async def cleanup_message(name, message): settings = Configuration.get_var(message.guild.id, "MSG_AUTO_DELETE").get(name, None) if settings is None: return - if settings["delete_self"]: - if bot.user.id == message.author.id: - asyncio.run_coroutine_threadsafe(cleanup_message(name, message, True, settings["wait_time"]), bot.loop) - return - if settings["delete_user"]: - if bot.user.id != message.author.id: - asyncio.run_coroutine_threadsafe(cleanup_message(name, message, True, settings["wait_time"]), bot.loop) + if settings["delete"]: + bot.loop.create_task(sleep_and_delete(message, settings["wait_time"])) + + +async def sleep_and_delete(message, wait_time): + await asyncio.sleep(wait_time) + await message.delete() def day_difference(a, b, location): diff = a - b return Translator.translate('days_ago', location, days=diff.days, date=a) + def construct_jumplink(guild_id, channel_id, message_id): return f"https://discordapp.com/channels/{guild_id}/{channel_id}/{message_id}"