Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add auto clean up support for clean messages. #297

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions GearBot/Bot/TheRealGearBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 23 additions & 6 deletions GearBot/Cogs/Moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,21 +882,27 @@ 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()
@commands.bot_has_permissions(manage_messages=True)
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")
Expand All @@ -907,13 +913,15 @@ 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")
@commands.guild_only()
@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")
Expand All @@ -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")
Expand All @@ -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:
Expand All @@ -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")
Expand All @@ -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
Expand Down
5 changes: 4 additions & 1 deletion GearBot/Util/Configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down
24 changes: 23 additions & 1 deletion GearBot/Util/MessageUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -79,9 +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):
settings = Configuration.get_var(message.guild.id, "MSG_AUTO_DELETE").get(name, None)
if settings is None:
return
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}"
5 changes: 3 additions & 2 deletions config/template.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"VERSION": 22,
"VERSION": 23,
"GENERAL": {
"LANG": "en_US",
"PERM_DENIED_MESSAGE": true,
Expand Down Expand Up @@ -61,5 +61,6 @@
"TRUSTED_ROLES": [],
"TRUSTED_USERS": []
},
"SERVER_LINKS": []
"SERVER_LINKS": [],
"MSG_AUTO_DELETE": {}
}