Last active
October 2, 2017 06:13
-
-
Save Tobotimus/929301f325b485d2271e9d858dea4ed8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async def delete_n_messages(channel, amount, check=None, is_bot=True): | |
"""Delete a specific amount of messages. | |
Only messages from the past 14 days will be deleted. | |
If the bot is not a bot account, messages will be deleted one at a time. | |
Parameters | |
---------- | |
amount: int | |
The maximum amount of messages which will be deleted. | |
check: callable | |
Same as ``check`` in ``discord.TextChannel.purge``. | |
is_bot: bool | |
Whether or not the bot is a bot account. | |
Returns | |
------- | |
int | |
The number of messages which were deleted. | |
""" | |
if check is None: | |
check = lambda m: True | |
strategy = _slow_deletion | |
if is_bot: | |
strategy = _mass_purge | |
return await strategy(channel, amount, check) | |
async def _mass_purge(channel, amount, check): | |
iterator = channel.history(limit=None) | |
remaining = amount | |
cur_count = 0 | |
to_delete = [] | |
minimum_time = ( # I definitely know how this works Kappa | |
int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22) | |
async for msg in iterator: | |
if cur_count == 100: | |
# we've reached a full 'queue' | |
await channel.delete_messages(to_delete) | |
cur_count = 0 | |
await asyncio.sleep(1) | |
if msg.id < minimum_time or remaining <= 0: | |
# older than 14 days | |
break | |
if check(msg): | |
cur_count += 1 | |
to_delete.append(msg) | |
remaining -= 1 | |
if cur_count >= 2: | |
# more than 2 messages -> bulk delete | |
await channel.delete_messages(to_delete) | |
elif cur_count == 1: | |
# delete a single message | |
await to_delete[-1].delete() | |
return amount - remaining | |
async def _slow_deletion(channel, amount, check): | |
iterator = channel.history(limit=None) | |
remaining = amount | |
minimum_time = ( | |
int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22) | |
async for msg in iterator: | |
if msg.id < minimum_time or remaining <= 0: | |
# older than 14 days | |
break | |
if check(msg): | |
await msg.delete() | |
remaining -= 1 | |
return amount - remaining |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment