From d86c695ee4fde4efb25a27285a9ec5b8f9c3237a Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:12:57 -0400 Subject: [PATCH 01/18] WIP auto e6 post command --- src/main/cogs/booru.py | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/main/cogs/booru.py b/src/main/cogs/booru.py index e91c96c..e99f45b 100644 --- a/src/main/cogs/booru.py +++ b/src/main/cogs/booru.py @@ -25,7 +25,7 @@ class MsG: self.LIMIT = 100 self.HISTORY_LIMIT = 100 self.RATE_LIMIT = u.RATE_LIMIT - self.queue = asyncio.Queue() + self.qualiqueue = asyncio.Queue() self.qualitifying = False self.favorites = u.setdefault('cogs/favorites.pkl', {'tags': set(), 'posts': set()}) @@ -36,11 +36,35 @@ class MsG: if u.tasks['auto_qual']: for channel in u.tasks['auto_qual']: temp = self.bot.get_channel(channel) - self.bot.loop.create_task(self.queue_for_qualitification(temp)) + self.bot.loop.create_task(self.qualiqueue_for_qualitification(temp)) print('AUTO-QUALITIFYING : #{}'.format(temp.name)) self.bot.loop.create_task(self._qualitify()) self.qualitifying = True + async def get_post(self, channel): + post_request = await u.fetch('https://e621.net/post/index.json', json=True) + + @commands.command() + async def auto_post(self, ctx): + try: + if ctx.channel.id not in u.tasks['auto_post']: + u.tasks['auto_post'].append(ctx.channel.id) + u.dump(u.tasks, 'cogs/tasks.pkl') + self.bot.loop.create_task(self.qualiqueue_for_qualitification(ctx.channel)) + if not self.qualitifying: + self.bot.loop.create_task(self._qualitify()) + self.qualitifying = True + + print('AUTO-POSTING : #{}'.format(ctx.channel.name)) + await ctx.send('**Auto-posting all images in {}.**'.format(ctx.channel.mention), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + else: + raise exc.Exists + + except exc.Exists: + await ctx.send('**Already auto-posting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + # Tag search @commands.command(aliases=['rel'], brief='e621 Search for related tags', description='e621 | NSFW\nReturn related tags for a number of given tags', usage='[related|rel]') @checks.del_ctx() @@ -351,7 +375,7 @@ class MsG: async def _qualitify(self): while self.qualitifying: - message = await self.queue.get() + message = await self.qualiqueue.get() for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): try: @@ -402,7 +426,7 @@ class MsG: try: while not self.bot.is_closed(): message = await self.bot.wait_for('message', check=check) - await self.queue.put(message) + await self.qualiqueue.put(message) await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') except exc.Abort: @@ -420,7 +444,7 @@ class MsG: if ctx.channel.id not in u.tasks['auto_qual']: u.tasks['auto_qual'].append(ctx.channel.id) u.dump(u.tasks, 'cogs/tasks.pkl') - self.bot.loop.create_task(self.queue_for_qualitification(ctx.channel)) + self.bot.loop.create_task(self.qualiqueue_for_qualitification(ctx.channel)) if not self.qualitifying: self.bot.loop.create_task(self._qualitify()) self.qualitifying = True From 8e0d8259fbfe1da00459b349b0465594d7162a2f Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:14:24 -0400 Subject: [PATCH 02/18] suppress ValueError > isdigit(), reaction order logic --- src/main/cogs/booru.py | 2286 ++++++++++++++++++++-------------------- 1 file changed, 1143 insertions(+), 1143 deletions(-) diff --git a/src/main/cogs/booru.py b/src/main/cogs/booru.py index e99f45b..1c0ac36 100644 --- a/src/main/cogs/booru.py +++ b/src/main/cogs/booru.py @@ -19,27 +19,27 @@ from utils import formatter, scraper class MsG: - def __init__(self, bot): - self.bot = bot - self.color = d.Color(0x1A1A1A) - self.LIMIT = 100 - self.HISTORY_LIMIT = 100 - self.RATE_LIMIT = u.RATE_LIMIT + def __init__(self, bot): + self.bot = bot + self.color = d.Color(0x1A1A1A) + self.LIMIT = 100 + self.HISTORY_LIMIT = 100 + self.RATE_LIMIT = u.RATE_LIMIT self.qualiqueue = asyncio.Queue() - self.qualitifying = False + self.qualitifying = False - self.favorites = u.setdefault('cogs/favorites.pkl', {'tags': set(), 'posts': set()}) - self.blacklists = u.setdefault( - 'cogs/blacklists.pkl', {'global_blacklist': set(), 'guild_blacklist': {}, 'user_blacklist': {}}) - self.aliases = u.setdefault('cogs/aliases.pkl', {}) + self.favorites = u.setdefault('cogs/favorites.pkl', {'tags': set(), 'posts': set()}) + self.blacklists = u.setdefault( + 'cogs/blacklists.pkl', {'global_blacklist': set(), 'guild_blacklist': {}, 'user_blacklist': {}}) + self.aliases = u.setdefault('cogs/aliases.pkl', {}) - if u.tasks['auto_qual']: - for channel in u.tasks['auto_qual']: - temp = self.bot.get_channel(channel) + if u.tasks['auto_qual']: + for channel in u.tasks['auto_qual']: + temp = self.bot.get_channel(channel) self.bot.loop.create_task(self.qualiqueue_for_qualitification(temp)) - print('AUTO-QUALITIFYING : #{}'.format(temp.name)) - self.bot.loop.create_task(self._qualitify()) - self.qualitifying = True + print('AUTO-QUALITIFYING : #{}'.format(temp.name)) + self.bot.loop.create_task(self._qualitify()) + self.qualitifying = True async def get_post(self, channel): post_request = await u.fetch('https://e621.net/post/index.json', json=True) @@ -65,1275 +65,1275 @@ class MsG: await ctx.send('**Already auto-posting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) await ctx.message.add_reaction('\N{CROSS MARK}') - # Tag search - @commands.command(aliases=['rel'], brief='e621 Search for related tags', description='e621 | NSFW\nReturn related tags for a number of given tags', usage='[related|rel]') - @checks.del_ctx() - async def related(self, ctx, *args): - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - related = [] + # Tag search + @commands.command(aliases=['rel'], brief='e621 Search for related tags', description='e621 | NSFW\nReturn related tags for a number of given tags', usage='[related|rel]') + @checks.del_ctx() + async def related(self, ctx, *args): + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] + related = [] - await dest.trigger_typing() + await dest.trigger_typing() - for tag in tags: - tag_request = await u.fetch('https://e621.net/tag/related.json', params={'tags': tag, 'type': 'general'}, json=True) - for rel in tag_request.get(tag, []): - related.append(rel[0]) + for tag in tags: + tag_request = await u.fetch('https://e621.net/tag/related.json', params={'tags': tag, 'type': 'general'}, json=True) + for rel in tag_request.get(tag, []): + related.append(rel[0]) - await dest.send('`{}` **related tags:**\n```\n{}```'.format(tag, formatter.tostring(related))) + await dest.send('`{}` **related tags:**\n```\n{}```'.format(tag, formatter.tostring(related))) - await asyncio.sleep(self.RATE_LIMIT) + await asyncio.sleep(self.RATE_LIMIT) - related.clear() + related.clear() - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - # Tag aliases - @commands.command(name='aliases', aliases=['alias'], brief='e621 Tag aliases', description='e621 | NSFW\nSearch aliases for given tag') - @checks.del_ctx() - async def tag_aliases(self, ctx, *args): - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - aliases = [] - - await dest.trigger_typing() - - for tag in tags: - alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) - for dic in alias_request: - aliases.append(dic['name']) - - await dest.send('`{}` **aliases:**\n```\n{}```'.format(tag, formatter.tostring(aliases))) - - await asyncio.sleep(self.RATE_LIMIT) - - aliases.clear() - - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @commands.command(name='getimage', aliases=['geti', 'gi']) - @checks.del_ctx() - async def get_image(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, urls = kwargs['destination'], kwargs['remaining'] - - if not urls: - raise exc.MissingArgument - - for url in urls: - try: - await dest.trigger_typing() - - await dest.send('{}'.format(await scraper.get_image(url))) - - finally: - await asyncio.sleep(self.RATE_LIMIT) - - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - except exc.MissingArgument: - await ctx.send('**Invalid url or file.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - # Reverse image searches a linked image using the public iqdb - @commands.command(name='reverse', aliases=['rev', 'ris'], brief='e621 Reverse image search', description='e621 | NSFW\nReverse-search an image with given URL') - @checks.del_ctx() - async def reverse_image_search(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, urls = kwargs['destination'], kwargs['remaining'] - c = 0 - - if not urls and not ctx.message.attachments: - raise exc.MissingArgument - - for url in urls: - try: - await dest.trigger_typing() - - await dest.send('**Probable match:**\n{}'.format(await scraper.get_post(url))) - - c += 1 - await asyncio.sleep(self.RATE_LIMIT) - - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - - for attachment in ctx.message.attachments: - try: - await dest.trigger_typing() - - await dest.send('**Probable match:**\n{}'.format(await scraper.get_post(attachment.url))) - - c += 1 - await asyncio.sleep(self.RATE_LIMIT) - - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - - if c: await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - else: - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.MissingArgument: - await ctx.send('**Invalid url or file.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + # Tag aliases + @commands.command(name='aliases', aliases=['alias'], brief='e621 Tag aliases', description='e621 | NSFW\nSearch aliases for given tag') + @checks.del_ctx() + async def tag_aliases(self, ctx, *args): + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] + aliases = [] - @commands.command(name='quality', aliases=['qual', 'qrev', 'qis']) - @checks.del_ctx() - async def quality_reverse_image_search(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, urls = kwargs['destination'], kwargs['remaining'] - c = 0 + await dest.trigger_typing() - if not urls and not ctx.message.attachments: - raise exc.MissingArgument + for tag in tags: + alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) + for dic in alias_request: + aliases.append(dic['name']) - for url in urls: - try: - await dest.trigger_typing() + await dest.send('`{}` **aliases:**\n```\n{}```'.format(tag, formatter.tostring(aliases))) - post = await scraper.get_post(url) + await asyncio.sleep(self.RATE_LIMIT) - await dest.send('**Probable match:**\n{}'.format(await scraper.get_image(post))) + aliases.clear() - c += 1 - await asyncio.sleep(self.RATE_LIMIT) - - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - - for attachment in ctx.message.attachments: - try: - await dest.trigger_typing() - - post = await scraper.get_post(attachment.url) - - await dest.send('**Probable match:**\n{}'.format(await scraper.get_image(post))) - - c += 1 - await asyncio.sleep(self.RATE_LIMIT) - - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - - if c: await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - else: - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.MissingArgument: - await ctx.send('**Invalid url or file.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + @commands.command(name='getimage', aliases=['geti', 'gi']) + @checks.del_ctx() + async def get_image(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args) + dest, urls = kwargs['destination'], kwargs['remaining'] - @commands.command(name='reversify', aliases=['revify', 'risify', 'rify']) - @checks.del_ctx() - async def reversify(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args, limit=self.HISTORY_LIMIT / 5) - dest, remove, limit = kwargs['destination'], kwargs['remove'], kwargs['limit'] - urls = [] - attachments = [] + if not urls: + raise exc.MissingArgument - if not ctx.author.permissions_in(ctx.channel).manage_messages: - dest = ctx.author + for url in urls: + try: + await dest.trigger_typing() - async for message in ctx.channel.history(limit=self.HISTORY_LIMIT * limit): - if len(urls) + len(attachments) >= limit: - break - if message.author.id != self.bot.user.id and re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content) is not None: - urls.append(message) - await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') - elif message.author.id != self.bot.user.id and message.attachments: - attachments.append(message) - await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + await dest.send('{}'.format(await scraper.get_image(url))) - if not urls and not attachments: - raise exc.NotFound + finally: + await asyncio.sleep(self.RATE_LIMIT) - for message in urls: - for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): - try: - await dest.trigger_typing() + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_post(match.group(0)))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + except exc.MissingArgument: + await ctx.send('**Invalid url or file.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - await asyncio.sleep(self.RATE_LIMIT) + # Reverse image searches a linked image using the public iqdb + @commands.command(name='reverse', aliases=['rev', 'ris'], brief='e621 Reverse image search', description='e621 | NSFW\nReverse-search an image with given URL') + @checks.del_ctx() + async def reverse_image_search(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args) + dest, urls = kwargs['destination'], kwargs['remaining'] + c = 0 - if remove: - with suppress(err.NotFound): - await message.delete() + if not urls and not ctx.message.attachments: + raise exc.MissingArgument - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') + for url in urls: + try: + await dest.trigger_typing() - for message in attachments: - for attachment in message.attachments: - try: - await dest.trigger_typing() + await dest.send('**Probable match:**\n{}'.format(await scraper.get_post(url))) - await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_post(attachment.url))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + c += 1 + await asyncio.sleep(self.RATE_LIMIT) - await asyncio.sleep(self.RATE_LIMIT) + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - if remove: - with suppress(err.NotFound): - await message.delete() + for attachment in ctx.message.attachments: + try: + await dest.trigger_typing() - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') + await dest.send('**Probable match:**\n{}'.format(await scraper.get_post(attachment.url))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + c += 1 + await asyncio.sleep(self.RATE_LIMIT) - except exc.NotFound: - await ctx.send('**No matches found.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.BoundsError as e: - await ctx.send('`{}` **invalid limit.** Images limited to 20'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - @commands.command(name='qualitify', aliases=['qualify', 'qrevify', 'qrisify', 'qify']) - @checks.del_ctx() - async def qualitify(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args, limit=self.HISTORY_LIMIT / 5) - dest, remove, limit = kwargs['destination'], kwargs['remove'], kwargs['limit'] - urls = [] - attachments = [] + if c: + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + else: + await ctx.message.add_reaction('\N{CROSS MARK}') - if not ctx.author.permissions_in(ctx.channel).manage_messages: - dest = ctx.author + except exc.MissingArgument: + await ctx.send('**Invalid url or file.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - async for message in ctx.channel.history(limit=self.HISTORY_LIMIT * limit): - if len(urls) + len(attachments) >= limit: - break - if message.author.id != self.bot.user.id and re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content) is not None: - urls.append(message) - await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') - elif message.author.id != self.bot.user.id and message.attachments: - attachments.append(message) - await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + @commands.command(name='quality', aliases=['qual', 'qrev', 'qis']) + @checks.del_ctx() + async def quality_reverse_image_search(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args) + dest, urls = kwargs['destination'], kwargs['remaining'] + c = 0 - if not urls and not attachments: - raise exc.NotFound + if not urls and not ctx.message.attachments: + raise exc.MissingArgument - for message in urls: - for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): - try: - await dest.trigger_typing() + for url in urls: + try: + await dest.trigger_typing() - post = await scraper.get_post(match.group(0)) + post = await scraper.get_post(url) - await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await dest.send('**Probable match:**\n{}'.format(await scraper.get_image(post))) - await asyncio.sleep(self.RATE_LIMIT) + c += 1 + await asyncio.sleep(self.RATE_LIMIT) - if remove: - with suppress(err.NotFound): - await message.delete() + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') + for attachment in ctx.message.attachments: + try: + await dest.trigger_typing() - for message in attachments: - for attachment in message.attachments: - try: - await dest.trigger_typing() + post = await scraper.get_post(attachment.url) - post = await scraper.get_post(attachment.url) + await dest.send('**Probable match:**\n{}'.format(await scraper.get_image(post))) - await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + c += 1 + await asyncio.sleep(self.RATE_LIMIT) - await asyncio.sleep(self.RATE_LIMIT) + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - if remove: - with suppress(err.NotFound): - await message.delete() + if c: + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + else: + await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.MatchError as e: - await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') + except exc.MissingArgument: + await ctx.send('**Invalid url or file.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @commands.command(name='reversify', aliases=['revify', 'risify', 'rify']) + @checks.del_ctx() + async def reversify(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args, limit=self.HISTORY_LIMIT / 5) + dest, remove, limit = kwargs['destination'], kwargs['remove'], kwargs['limit'] + urls = [] + attachments = [] - except exc.NotFound: - await ctx.send('**No matches found.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.BoundsError as e: - await ctx.send('`{}` **invalid limit.** Images limited to 20'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + if not ctx.author.permissions_in(ctx.channel).manage_messages: + dest = ctx.author - async def _qualitify(self): - while self.qualitifying: + async for message in ctx.channel.history(limit=self.HISTORY_LIMIT * limit): + if len(urls) + len(attachments) >= limit: + break + if message.author.id != self.bot.user.id and re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content) is not None: + urls.append(message) + await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + elif message.author.id != self.bot.user.id and message.attachments: + attachments.append(message) + await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + + if not urls and not attachments: + raise exc.NotFound + + for message in urls: + for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): + try: + await dest.trigger_typing() + + await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_post(match.group(0)))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + if remove: + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + for message in attachments: + for attachment in message.attachments: + try: + await dest.trigger_typing() + + await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_post(attachment.url))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + if remove: + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.NotFound: + await ctx.send('**No matches found.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.BoundsError as e: + await ctx.send('`{}` **invalid limit.** Images limited to 20'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + @commands.command(name='qualitify', aliases=['qualify', 'qrevify', 'qrisify', 'qify']) + @checks.del_ctx() + async def qualitify(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args, limit=self.HISTORY_LIMIT / 5) + dest, remove, limit = kwargs['destination'], kwargs['remove'], kwargs['limit'] + urls = [] + attachments = [] + + if not ctx.author.permissions_in(ctx.channel).manage_messages: + dest = ctx.author + + async for message in ctx.channel.history(limit=self.HISTORY_LIMIT * limit): + if len(urls) + len(attachments) >= limit: + break + if message.author.id != self.bot.user.id and re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content) is not None: + urls.append(message) + await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + elif message.author.id != self.bot.user.id and message.attachments: + attachments.append(message) + await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + + if not urls and not attachments: + raise exc.NotFound + + for message in urls: + for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): + try: + await dest.trigger_typing() + + post = await scraper.get_post(match.group(0)) + + await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + if remove: + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + for message in attachments: + for attachment in message.attachments: + try: + await dest.trigger_typing() + + post = await scraper.get_post(attachment.url) + + await dest.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + if remove: + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await ctx.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.NotFound: + await ctx.send('**No matches found.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.BoundsError as e: + await ctx.send('`{}` **invalid limit.** Images limited to 20'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + async def _qualitify(self): + while self.qualitifying: message = await self.qualiqueue.get() - for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): + for match in re.finditer('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', message.content): + try: + await message.channel.trigger_typing() + + post = await scraper.get_post(match.group(0)) + + await message.channel.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await message.channel.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + for attachment in message.attachments: + try: + await message.channel.trigger_typing() + + post = await scraper.get_post(attachment.url) + + await message.channel.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + await asyncio.sleep(self.RATE_LIMIT) + + with suppress(err.NotFound): + await message.delete() + + except exc.MatchError as e: + await message.channel.send('**No probable match for:** `{}`'.format(e), delete_after=10) + await message.add_reaction('\N{CROSS MARK}') + + print('STOPPED : qualitifying') + + async def queue_for_qualitification(self, channel): + def check(msg): + if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator: + raise exc.Abort + elif msg.channel is channel and message.author.id != self.bot.user.id and (re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', msg.content) is not None or msg.attachments): + return True + return False + try: - await message.channel.trigger_typing() - - post = await scraper.get_post(match.group(0)) - - await message.channel.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - await asyncio.sleep(self.RATE_LIMIT) - - with suppress(err.NotFound): - await message.delete() - - except exc.MatchError as e: - await message.channel.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') - - for attachment in message.attachments: - try: - await message.channel.trigger_typing() - - post = await scraper.get_post(attachment.url) - - await message.channel.send('**Probable match from** {}**:**\n{}'.format(message.author.display_name, await scraper.get_image(post))) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - await asyncio.sleep(self.RATE_LIMIT) - - with suppress(err.NotFound): - await message.delete() - - except exc.MatchError as e: - await message.channel.send('**No probable match for:** `{}`'.format(e), delete_after=10) - await message.add_reaction('\N{CROSS MARK}') - - print('STOPPED : qualitifying') - - async def queue_for_qualitification(self, channel): - def check(msg): - if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator: - raise exc.Abort - elif msg.channel is channel and message.author.id != self.bot.user.id and (re.search('(http[a-z]?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))', msg.content) is not None or msg.attachments): - return True - return False - - try: - while not self.bot.is_closed(): - message = await self.bot.wait_for('message', check=check) + while not self.bot.is_closed(): + message = await self.bot.wait_for('message', check=check) await self.qualiqueue.put(message) - await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + await message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') - except exc.Abort: - u.tasks['auto_qual'].remove(channel.id) - u.dump(u.tasks, 'cogs/tasks.pkl') - if not u.tasks['auto_qual']: - self.qualitifying = False - print('STOPPED : qualitifying #{}'.format(channel.name)) - await channel.send('**Stopped queueing messages for qualitification in** {}**.**'.format(channel.mention), delete_after=5) + except exc.Abort: + u.tasks['auto_qual'].remove(channel.id) + u.dump(u.tasks, 'cogs/tasks.pkl') + if not u.tasks['auto_qual']: + self.qualitifying = False + print('STOPPED : qualitifying #{}'.format(channel.name)) + await channel.send('**Stopped queueing messages for qualitification in** {}**.**'.format(channel.mention), delete_after=5) - @commands.command(name='autoqualitify', aliases=['autoqual']) - @commands.has_permissions(manage_channels=True) - async def auto_qualitify(self, ctx): - try: - if ctx.channel.id not in u.tasks['auto_qual']: - u.tasks['auto_qual'].append(ctx.channel.id) - u.dump(u.tasks, 'cogs/tasks.pkl') + @commands.command(name='autoqualitify', aliases=['autoqual']) + @commands.has_permissions(manage_channels=True) + async def auto_qualitify(self, ctx): + try: + if ctx.channel.id not in u.tasks['auto_qual']: + u.tasks['auto_qual'].append(ctx.channel.id) + u.dump(u.tasks, 'cogs/tasks.pkl') self.bot.loop.create_task(self.qualiqueue_for_qualitification(ctx.channel)) - if not self.qualitifying: - self.bot.loop.create_task(self._qualitify()) - self.qualitifying = True + if not self.qualitifying: + self.bot.loop.create_task(self._qualitify()) + self.qualitifying = True - print('AUTO-QUALITIFYING : #{}'.format(ctx.channel.name)) - await ctx.send('**Auto-qualitifying all images in {}.**'.format(ctx.channel.mention), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - else: - raise exc.Exists + print('AUTO-QUALITIFYING : #{}'.format(ctx.channel.name)) + await ctx.send('**Auto-qualitifying all images in {}.**'.format(ctx.channel.mention), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + else: + raise exc.Exists - except exc.Exists: - await ctx.send('**Already auto-qualitifying in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.Exists: + await ctx.send('**Already auto-qualitifying in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - def get_favorites(self, ctx, args): - if '-f' in args or '-favs' in args or '-faves' in args or '-favorites' in args: - if self.favorites.get(ctx.author.id, {}).get('tags', set()): - args = ['~{}'.format(tag) for tag in self.favorites[ctx.author.id]['tags']] - else: - raise exc.FavoritesNotFound + def get_favorites(self, ctx, args): + if '-f' in args or '-favs' in args or '-faves' in args or '-favorites' in args: + if self.favorites.get(ctx.author.id, {}).get('tags', set()): + args = ['~{}'.format(tag) for tag in self.favorites[ctx.author.id]['tags']] + else: + raise exc.FavoritesNotFound - return args + return args - async def return_pool(self, ctx, *, booru='e621', query=[]): - def on_message(msg): - if msg.content.lower() == 'cancel' and msg.author is ctx.author and msg.channel is ctx.channel: - raise exc.Abort - with suppress(ValueError): - if int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is ctx.author and msg.channel is ctx.channel: - return True - return False + async def return_pool(self, ctx, *, booru='e621', query=[]): + def on_message(msg): + if msg.content.lower() == 'cancel' and msg.author is ctx.author and msg.channel is ctx.channel: + raise exc.Abort + elif msg.content.isdigit(): + if int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is ctx.author and msg.channel is ctx.channel: + return True + return False - posts = {} - pool = {} + posts = {} + pool = {} - pools = [] - pool_request = await u.fetch('https://{}.net/pool/index.json'.format(booru), params={'query': ' '.join(query)}, json=True) - if len(pool_request) > 1: - for pool in pool_request: - pools.append(pool['name']) - match = await ctx.send('**Multiple pools found.** Type in the correct match.\n```\n{}```\nor `cancel` to cancel.'.format('\n'.join(['{} {}'.format(c, elem) for c, elem in enumerate(pools, 1)]))) - try: - selection = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) - except exc.Abort: - raise exc.Abort - finally: - await match.delete() - tempool = [pool for pool in pool_request if pool['name'] - == pools[int(selection.content) - 1]][0] - await selection.delete() - pool = {'name': tempool['name'], 'id': tempool['id']} - elif pool_request: - tempool = pool_request[0] - pool = {'name': pool_request[0]['name'], 'id': pool_request[0]['id']} - else: - raise exc.NotFound - - page = 1 - while len(posts) < tempool['post_count']: - posts_request = await u.fetch('https://{}.net/pool/show.json'.format(booru), params={'id': tempool['id'], 'page': page}, json=True) - for post in posts_request['posts']: - posts[post['id']] = {'author': post['author'], 'url': post['file_url']} - page += 1 - - return pool, posts - - # Creates reaction-based paginator for linked pools - @commands.command(name='pool', aliases=['e6pp'], brief='e621 pool paginator', description='e621 | NSFW\nShow pools in a page format', hidden=True) - @checks.del_ctx() - async def pool_paginator(self, ctx, *args): - def on_reaction(reaction, user): - if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Abort - elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.GoTo - elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Left - elif reaction.emoji == '\N{GROWING HEART}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Save - elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Right - return False - - def on_message(msg): - with suppress(ValueError): - if int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel: - return True - return False - - try: - kwargs = u.get_kwargs(ctx, args) - dest, query = kwargs['destination'], kwargs['remaining'] - starred = [] - c = 1 - - await dest.trigger_typing() - - pool, posts = await self.return_pool(ctx, booru='e621', query=query) - keys = list(posts.keys()) - values = list(posts.values()) - - embed = d.Embed( - title=values[c - 1]['author'], url='https://e621.net/post/show/{}'.format(keys[c - 1]), color=dest.me.color if isinstance(dest.channel, d.TextChannel) else self.color).set_image(url=values[c - 1]['url']) - embed.set_author(name=pool['name'], - url='https://e621.net/pool/show?id={}'.format(pool['id']), icon_url=ctx.author.avatar_url) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - - paginator = await dest.send(embed=embed) - - for emoji in ('\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}', '\N{LEFTWARDS BLACK ARROW}', '\N{GROWING HEART}', '\N{BLACK RIGHTWARDS ARROW}'): - await paginator.add_reaction(emoji) - await ctx.message.add_reaction('\N{OCTAGONAL SIGN}') - await asyncio.sleep(1) - - while not self.bot.is_closed(): - try: - done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=10 * 60), - self.bot.wait_for('reaction_remove', check=on_reaction, timeout=10 * 60)], return_when=asyncio.FIRST_COMPLETED) - for future in done: - future.result() - - except exc.GoTo: - await paginator.edit(content='**Enter image number...**') - number = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) - - c = int(number.content) - await number.delete() - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) - - except exc.Left: - if c > 1: - c -= 1 - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) - else: - await paginator.edit(content='**First image.**') - - except exc.Save: - if values[c - 1]['url'] not in starred: - starred.append(values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}') - else: - starred.remove(values[c - 1]['url']) - - await paginator.edit(content='\N{BROKEN HEART}') - - except exc.Right: - if c < len(keys): - c += 1 - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) - - except exc.Abort: - try: - await paginator.edit(content='**Exited paginator.**') - - except UnboundLocalError: - await dest.send('**Exited paginator.**') - - finally: - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except asyncio.TimeoutError: - try: - await paginator.edit(content='**Paginator timed out.**') - - except UnboundLocalError: - await dest.send('**Paginator timed out.**') - - finally: - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except exc.NotFound: - await ctx.send('**Pool not found.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.Timeout: - await ctx.send('**Request timed out.**') - await ctx.message.add_reaction('\N{CROSS MARK}') - - finally: - for url in starred: - await ctx.author.send('`{} / {}`\n{}'.format(starred.index(url) + 1, len(starred), url)) - if len(starred) > 5: - await asyncio.sleep(self.RATE_LIMIT) - - # Messy code that checks image limit and tags in blacklists - async def check_return_posts(self, ctx, *, booru='e621', tags=[], limit=1, previous={}): - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - blacklist = set() - # Creates temp blacklist based on context - for tag in self.blacklists['global_blacklist']: - blacklist.update(list(self.aliases[tag]) + [tag]) - for tag in self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set()): - blacklist.update(list(self.aliases[tag]) + [tag]) - for tag in self.blacklists['user_blacklist'].get(ctx.author.id, set()): - blacklist.update(list(self.aliases[tag]) + [tag]) - # Checks if tags are in local blacklists - if tags: - if (len(tags) > 5 and booru == 'e621') or (len(tags) > 4 and booru == 'e926'): - raise exc.TagBoundsError(formatter.tostring(tags[5:])) - for tag in tags: - if tag == 'swf' or tag == 'webm' or tag in blacklist: - raise exc.TagBlacklisted(tag) - - # Checks for blacklisted tags in endpoint blacklists - try/except is for continuing the parent loop - posts = {} - c = 0 - while len(posts) < limit: - if c == limit * 5 + self.LIMIT: - raise exc.Timeout - request = await u.fetch('https://{}.net/post/index.json'.format(booru), params={'tags': ','.join(['order:random'] + tags), 'limit': int(self.LIMIT * limit)}, json=True) - if len(request) == 0: - raise exc.NotFound(formatter.tostring(tags)) - if len(request) < limit: - limit = len(request) - - for post in request: - if 'swf' in post['file_ext'] or 'webm' in post['file_ext']: - continue - try: - for tag in blacklist: - if tag in post['tags']: - raise exc.Continue - except exc.Continue: - continue - if post['id'] not in posts.keys() and post['id'] not in previous.keys(): - posts[post['id']] = {'author': post['author'], 'url': post['file_url']} - if len(posts) == limit: - break - c += 1 - - return posts - - @commands.command(name='e621p', aliases=['e6p', '6p']) - @checks.del_ctx() - @checks.is_nsfw() - async def e621_paginator(self, ctx, *args): - def on_reaction(reaction, user): - if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Abort - elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.GoTo - elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Left - elif reaction.emoji == '\N{GROWING HEART}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Save - elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): - raise exc.Right - return False - - def on_message(msg): - with suppress(ValueError): - if int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel: - return True - return False - - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - limit = self.LIMIT / 5 - starred = [] - c = 1 - - tags = self.get_favorites(ctx, tags) - - await ctx.trigger_typing() - - posts = await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit) - keys = list(posts.keys()) - values = list(posts.values()) - - embed = d.Embed( - title=values[c - 1]['author'], url='https://e621.net/post/show/{}'.format(keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color).set_image(url=values[c - 1]['url']) - embed.set_author(name=formatter.tostring(tags, random=True), - url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - - paginator = await dest.send(embed=embed) - - for emoji in ('\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}', '\N{LEFTWARDS BLACK ARROW}', '\N{GROWING HEART}', '\N{BLACK RIGHTWARDS ARROW}'): - await paginator.add_reaction(emoji) - await ctx.message.add_reaction('\N{OCTAGONAL SIGN}') - await asyncio.sleep(1) - - while not self.bot.is_closed(): - try: - done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=10 * 60), - self.bot.wait_for('reaction_remove', check=on_reaction, timeout=10 * 60)], return_when=asyncio.FIRST_COMPLETED) - for future in done: - future.result() - - except exc.GoTo: - await paginator.edit(content='**Enter image number...**') - number = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) - - c = int(number.content) - await number.delete() - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) - - except exc.Left: - if c > 1: - c -= 1 - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) - else: - await paginator.edit(content='**First image.**') - - except exc.Save: - if values[c - 1]['url'] not in starred: - starred.append(values[c - 1]['url']) - - await paginator.edit(content='\N{HEAVY BLACK HEART}') - else: - starred.remove(values[c - 1]['url']) - - await paginator.edit(content='\N{BROKEN HEART}') - - except exc.Right: - if c % limit == 0: - await dest.trigger_typing() + pools = [] + pool_request = await u.fetch('https://{}.net/pool/index.json'.format(booru), params={'query': ' '.join(query)}, json=True) + if len(pool_request) > 1: + for pool in pool_request: + pools.append(pool['name']) + match = await ctx.send('**Multiple pools found.** Type in the correct match.\n```\n{}```\nor `cancel` to cancel.'.format('\n'.join(['{} {}'.format(c, elem) for c, elem in enumerate(pools, 1)]))) try: - posts.update(await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit, previous=posts)) + selection = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) + except exc.Abort: + raise exc.Abort + finally: + await match.delete() + tempool = [pool for pool in pool_request if pool['name'] + == pools[int(selection.content) - 1]][0] + await selection.delete() + pool = {'name': tempool['name'], 'id': tempool['id']} + elif pool_request: + tempool = pool_request[0] + pool = {'name': pool_request[0]['name'], 'id': pool_request[0]['id']} + else: + raise exc.NotFound - except exc.NotFound: - await paginator.edit(content='**No more images found.**') + page = 1 + while len(posts) < tempool['post_count']: + posts_request = await u.fetch('https://{}.net/pool/show.json'.format(booru), params={'id': tempool['id'], 'page': page}, json=True) + for post in posts_request['posts']: + posts[post['id']] = {'author': post['author'], 'url': post['file_url']} + page += 1 + return pool, posts + + # Creates reaction-based paginator for linked pools + @commands.command(name='pool', aliases=['e6pp'], brief='e621 pool paginator', description='e621 | NSFW\nShow pools in a page format', hidden=True) + @checks.del_ctx() + async def pool_paginator(self, ctx, *args): + def on_reaction(reaction, user): + if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Abort + elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.GoTo + elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Left + elif reaction.emoji == '\N{GROWING HEART}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Save + elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Right + return False + + def on_message(msg): + if msg.content.isdigit(): + if int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel: + return True + return False + + try: + kwargs = u.get_kwargs(ctx, args) + dest, query = kwargs['destination'], kwargs['remaining'] + starred = [] + c = 1 + + await dest.trigger_typing() + + pool, posts = await self.return_pool(ctx, booru='e621', query=query) keys = list(posts.keys()) values = list(posts.values()) - c += 1 - embed.title = values[c - 1]['author'] - embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) - embed.set_footer(text='{} / {}'.format(c, len(posts)), - icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - embed.set_image(url=values[c - 1]['url']) - await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + embed = d.Embed( + title=values[c - 1]['author'], url='https://e621.net/post/show/{}'.format(keys[c - 1]), color=dest.me.color if isinstance(dest.channel, d.TextChannel) else self.color) + embed.set_image(url=values[c - 1]['url']) + embed.set_author(name=pool['name'], + url='https://e621.net/pool/show?id={}'.format(pool['id']), icon_url=ctx.author.avatar_url) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') - except exc.Abort: - try: - await paginator.edit(content='**Exited paginator.**') + paginator = await dest.send(embed=embed) - except UnboundLocalError: - await dest.send('**Exited paginator.**') + for emoji in ('\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}', '\N{LEFTWARDS BLACK ARROW}', '\N{GROWING HEART}', '\N{BLACK RIGHTWARDS ARROW}'): + await paginator.add_reaction(emoji) + await ctx.message.add_reaction('\N{OCTAGONAL SIGN}') + await asyncio.sleep(1) - finally: + while not self.bot.is_closed(): + try: + done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=10 * 60), + self.bot.wait_for('reaction_remove', check=on_reaction, timeout=10 * 60)], return_when=asyncio.FIRST_COMPLETED) + for future in done: + future.result() + + except exc.GoTo: + await paginator.edit(content='**Enter image number...**') + number = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) + + c = int(number.content) + await number.delete() + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + + except exc.Left: + if c > 1: + c -= 1 + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + else: + await paginator.edit(content='**First image.**') + + except exc.Save: + if values[c - 1]['url'] not in starred: + starred.append(values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}') + else: + starred.remove(values[c - 1]['url']) + + await paginator.edit(content='\N{BROKEN HEART}') + + except exc.Right: + if c < len(keys): + c += 1 + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + + except exc.Abort: + try: + await paginator.edit(content='**Exited paginator.**') + + except UnboundLocalError: + await dest.send('**Exited paginator.**') + except asyncio.TimeoutError: + try: + await paginator.edit(content='**Paginator timed out.**') + + except UnboundLocalError: + await dest.send('**Paginator timed out.**') + except exc.NotFound: + await ctx.send('**Pool not found.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.Timeout: + await ctx.send('**Request timed out.**') + await ctx.message.add_reaction('\N{CROSS MARK}') + + finally: + if starred: + await ctx.message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + + for url in starred: + await ctx.author.send('`{} / {}`\n{}'.format(starred.index(url) + 1, len(starred), url)) + if len(starred) > 5: + await asyncio.sleep(self.RATE_LIMIT) + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + # Messy code that checks image limit and tags in blacklists + async def check_return_posts(self, ctx, *, booru='e621', tags=[], limit=1, previous={}): + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel + + blacklist = set() + # Creates temp blacklist based on context + for tag in self.blacklists['global_blacklist']: + blacklist.update(list(self.aliases[tag]) + [tag]) + for tag in self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set()): + blacklist.update(list(self.aliases[tag]) + [tag]) + for tag in self.blacklists['user_blacklist'].get(ctx.author.id, set()): + blacklist.update(list(self.aliases[tag]) + [tag]) + # Checks if tags are in local blacklists + if tags: + if (len(tags) > 5 and booru == 'e621') or (len(tags) > 4 and booru == 'e926'): + raise exc.TagBoundsError(formatter.tostring(tags[5:])) + for tag in tags: + if tag == 'swf' or tag == 'webm' or tag in blacklist: + raise exc.TagBlacklisted(tag) + + # Checks for blacklisted tags in endpoint blacklists - try/except is for continuing the parent loop + posts = {} + c = 0 + while len(posts) < limit: + if c == limit * 5 + self.LIMIT: + raise exc.Timeout + request = await u.fetch('https://{}.net/post/index.json'.format(booru), params={'tags': ','.join(['order:random'] + tags), 'limit': int(self.LIMIT * limit)}, json=True) + if len(request) == 0: + raise exc.NotFound(formatter.tostring(tags)) + if len(request) < limit: + limit = len(request) + + for post in request: + if 'swf' in post['file_ext'] or 'webm' in post['file_ext']: + continue + try: + for tag in blacklist: + if tag in post['tags']: + raise exc.Continue + except exc.Continue: + continue + if post['id'] not in posts.keys() and post['id'] not in previous.keys(): + posts[post['id']] = {'author': post['author'], 'url': post['file_url']} + if len(posts) == limit: + break + c += 1 + + return posts + + @commands.command(name='e621p', aliases=['e6p', '6p']) + @checks.del_ctx() + @checks.is_nsfw() + async def e621_paginator(self, ctx, *args): + def on_reaction(reaction, user): + if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Abort + elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.GoTo + elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Left + elif reaction.emoji == '\N{GROWING HEART}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Save + elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and (user is ctx.author or user.id == u.config['owner_id']): + raise exc.Right + return False + + def on_message(msg): + if msg.content.isdigit(): + if int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel: + return True + return False + + try: + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] + limit = self.LIMIT / 5 + starred = [] + c = 1 + + tags = self.get_favorites(ctx, tags) + + await ctx.trigger_typing() + + posts = await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit) + keys = list(posts.keys()) + values = list(posts.values()) + + embed = d.Embed( + title=values[c - 1]['author'], url='https://e621.net/post/show/{}'.format(keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color) + embed.set_image(url=values[c - 1]['url']) + embed.set_author(name=formatter.tostring(tags, random=True), + url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + + paginator = await dest.send(embed=embed) + + for emoji in ('\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}', '\N{LEFTWARDS BLACK ARROW}', '\N{GROWING HEART}', '\N{BLACK RIGHTWARDS ARROW}'): + await paginator.add_reaction(emoji) + await ctx.message.add_reaction('\N{OCTAGONAL SIGN}') + await asyncio.sleep(1) + + while not self.bot.is_closed(): + try: + done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=10 * 60), + self.bot.wait_for('reaction_remove', check=on_reaction, timeout=10 * 60)], return_when=asyncio.FIRST_COMPLETED) + for future in done: + future.result() + + except exc.GoTo: + await paginator.edit(content='**Enter image number...**') + number = await self.bot.wait_for('message', check=on_message, timeout=10 * 60) + + c = int(number.content) + await number.delete() + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + + except exc.Left: + if c > 1: + c -= 1 + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + else: + await paginator.edit(content='**First image.**') + + except exc.Save: + if values[c - 1]['url'] not in starred: + starred.append(values[c - 1]['url']) + + await paginator.edit(content='\N{HEAVY BLACK HEART}') + else: + starred.remove(values[c - 1]['url']) + + await paginator.edit(content='\N{BROKEN HEART}') + + except exc.Right: + if c % limit == 0: + await dest.trigger_typing() + try: + posts.update(await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit, previous=posts)) + + except exc.NotFound: + await paginator.edit(content='**No more images found.**') + + keys = list(posts.keys()) + values = list(posts.values()) + + c += 1 + embed.title = values[c - 1]['author'] + embed.url = 'https://e621.net/post/show/{}'.format(keys[c - 1]) + embed.set_footer(text='{} / {}'.format(c, len(posts)), + icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + embed.set_image(url=values[c - 1]['url']) + await paginator.edit(content='\N{HEAVY BLACK HEART}' if values[c - 1]['url'] in starred else None, embed=embed) + + except exc.Abort: + try: + await paginator.edit(content='**Exited paginator.**') + + except UnboundLocalError: + await dest.send('**Exited paginator.**') + except asyncio.TimeoutError: + try: + await paginator.edit(content='**Paginator timed out.**') + + except UnboundLocalError: + await dest.send('**Paginator timed out.**') + except exc.NotFound as e: + await ctx.send('`{}` **not found.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.TagBlacklisted as e: + await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{NO ENTRY SIGN}') + except exc.TagBoundsError as e: + await ctx.send('`{}` **out of bounds.** Tags limited to 5, currently.'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.FavoritesNotFound: + await ctx.send('**You have no favorite tags.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.Timeout: + await ctx.send('**Request timed out.**') + await ctx.message.add_reaction('\N{CROSS MARK}') + + finally: + if starred: + await ctx.message.add_reaction('\N{HOURGLASS WITH FLOWING SAND}') + + for url in starred: + await ctx.author.send('`{} / {}`\n{}'.format(starred.index(url) + 1, len(starred), url)) + if len(starred) > 5: + await asyncio.sleep(self.RATE_LIMIT) + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + @e621_paginator.error + async def e621_paginator_error(self, ctx, error): + if isinstance(error, errext.CheckFailure): + await ctx.send('\N{NO ENTRY} {} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10) + return await ctx.message.add_reaction('\N{NO ENTRY}') + + # Searches for and returns images from e621.net given tags when not blacklisted + @commands.group(aliases=['e6', '6'], brief='e621 | NSFW', description='e621 | NSFW\nTag-based search for e621.net\n\nYou can only search 5 tags and 6 images at once for now.\ne6 [tags...] ([# of images])') + @checks.del_ctx() + @checks.is_nsfw() + async def e621(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args, limit=3) + dest, args, limit = kwargs['destination'], kwargs['remaining'], kwargs['limit'] + + tags = self.get_favorites(ctx, args) + + await dest.trigger_typing() + + posts = await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit) + + for ident, post in posts.items(): + embed = d.Embed(title=post['author'], url='https://e621.net/post/show/{}'.format(ident), + color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color).set_image(url=post['url']) + embed.set_author(name=formatter.tostring(tags, random=True), + url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) + embed.set_footer( + text=str(ident), icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + + await dest.send(embed=embed) + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.TagBlacklisted as e: + await ctx.send('`{}` **blacklisted.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.BoundsError as e: + await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.TagBoundsError as e: + await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.NotFound as e: + await ctx.send('`{}` **not found.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.FavoritesNotFound: + await ctx.send('**You have no favorite tags.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.Timeout: + await ctx.send('**Request timed out.**') + await ctx.message.add_reaction('\N{CROSS MARK}') + + # tools.command_dict.setdefault(str(ctx.author.id), {}).update( + # {'command': ctx.command, 'args': ctx.args}) + + @e621.error + async def e621_error(self, ctx, error): + if isinstance(error, errext.CheckFailure): + await ctx.send('\N{NO ENTRY} {} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10) + return await ctx.message.add_reaction('\N{NO ENTRY}') + + # Searches for and returns images from e926.net given tags when not blacklisted + @commands.command(aliases=['e9', '9'], brief='e926 | SFW', description='e926 | SFW\nTag-based search for e926.net\n\nYou can only search 5 tags and 6 images at once for now.\ne9 [tags...] ([# of images])') + @checks.del_ctx() + async def e926(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args, limit=3) + dest, args, limit = kwargs['destination'], kwargs['remaining'], kwargs['limit'] + + tags = self.get_favorites(ctx, args) + + await dest.trigger_typing() + + posts = await self.check_return_posts(ctx, booru='e926', tags=tags, limit=limit) + + for ident, post in posts.items(): + embed = d.Embed(title=post['author'], url='https://e926.net/post/show/{}'.format(ident), + color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color).set_image(url=post['url']) + embed.set_author(name=formatter.tostring(tags, random=True), + url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) + embed.set_footer( + text=str(ident), icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + + await dest.send(embed=embed) + + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.TagBlacklisted as e: + await ctx.send('`{}` **blacklisted.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.BoundsError as e: + await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.TagBoundsError as e: + await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.NotFound as e: + await ctx.send('`{}` **not found.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.FavoritesNotFound: + await ctx.send('**You have no favorite tags.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.Timeout: + await ctx.send('**Request timed out.**') + await ctx.message.add_reaction('\N{CROSS MARK}') + + @commands.group(aliases=['fave', 'fav', 'f']) + @checks.del_ctx() + async def favorite(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Use a flag to manage favorites.**\n*Type* `{}help fav` *for more info.*'.format(ctx.prefix), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + @favorite.error + async def favorite_error(self, ctx, error): + pass + + @favorite.group(name='get', aliases=['g']) + async def _get_favorite(self, ctx): + pass + + @_get_favorite.command(name='tags', aliases=['t']) + async def __get_favorite_tags(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] + + await dest.send('\N{WHITE MEDIUM STAR} {}**\'s favorite tags:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(self.favorites.get(ctx.author.id, {}).get('tags', set()))), delete_after=10) await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except asyncio.TimeoutError: - try: - await paginator.edit(content='**Paginator timed out.**') - except UnboundLocalError: - await dest.send('**Paginator timed out.**') + @_get_favorite.command(name='posts', aliases=['p']) + async def __get_favorite_posts(self, ctx): + pass - finally: + @favorite.group(name='add', aliases=['a']) + async def _add_favorite(self, ctx): + pass + + @_add_favorite.command(name='tags', aliases=['t']) + async def __add_favorite_tags(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] + + for tag in tags: + if tag in self.blacklists['user_blacklist'].get(ctx.author.id, set()): + raise exc.TagBlacklisted(tag) + if len(self.favorites[ctx.author.id]['tags']) + len(tags) > 5: + raise exc.BoundsError + + self.favorites.setdefault(ctx.author.id, {}).setdefault('tags', set()).update(tags) + u.dump(self.favorites, 'cogs/favorites.pkl') + + await dest.send('{} **added to their favorites:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.BoundsError: + await ctx.send('**Favorites list currently limited to:** `5`', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + except exc.TagBlacklisted as e: + await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted.**', delete_after=10) + await ctx.message.add_reaction('\N{NO ENTRY SIGN}') + + @_add_favorite.command(name='posts', aliases=['p']) + async def __add_favorite_posts(self, ctx, *posts): + pass + + @favorite.group(name='remove', aliases=['r']) + async def _remove_favorite(self, ctx): + pass + + @_remove_favorite.command(name='tags', aliases=['t']) + async def __remove_favorite_tags(self, ctx, *args): + try: + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] + + for tag in tags: + try: + self.favorites[ctx.author.id].get('tags', set()).remove(tag) + + except KeyError: + raise exc.TagError(tag) + + u.dump(self.favorites, 'cogs/favorites.pkl') + + await dest.send('{} **removed from their favorites:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.TagError as e: + await ctx.send('`{}` **not in favorites.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + @_remove_favorite.command(name='posts', aliases=['p']) + async def __remove_favorite_posts(self, ctx): + pass + + @favorite.group(name='clear', aliases=['c']) + async def _clear_favorite(self, ctx): + pass + + @_clear_favorite.command(name='tags', aliases=['t']) + async def __clear_favorite_tags(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] + + with suppress(KeyError): + del self.favorites[ctx.author.id] + u.dump(self.favorites, 'cogs/favorites.pkl') + + await dest.send('{}**\'s favorites cleared.**'.format(ctx.author.mention), delete_after=5) await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except exc.NotFound as e: - await ctx.send('`{}` **not found.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.TagBlacklisted as e: - await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{NO ENTRY SIGN}') - except exc.TagBoundsError as e: - await ctx.send('`{}` **out of bounds.** Tags limited to 5, currently.'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.FavoritesNotFound: - await ctx.send('**You have no favorite tags.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.Timeout: - await ctx.send('**Request timed out.**') - await ctx.message.add_reaction('\N{CROSS MARK}') - finally: - for url in starred: - await ctx.author.send('`{} / {}`\n{}'.format(starred.index(url) + 1, len(starred), url)) - if len(starred) > 5: - await asyncio.sleep(self.RATE_LIMIT) + @_clear_favorite.command(name='posts', aliases=['p']) + async def __clear_favorite_posts(self, ctx): + pass - @e621_paginator.error - async def e621_paginator_error(self, ctx, error): - if isinstance(error, errext.CheckFailure): - await ctx.send('\N{NO ENTRY} {} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10) - return await ctx.message.add_reaction('\N{NO ENTRY}') + # Umbrella command structure to manage global, channel, and user blacklists + @commands.group(aliases=['bl', 'b'], brief='Manage blacklists', description='Blacklist base command for managing blacklists\n\n`bl get [blacklist]` to show a blacklist\n`bl set [blacklist] [tags]` to replace a blacklist\n`bl clear [blacklist]` to clear a blacklist\n`bl add [blacklist] [tags]` to add tags to a blacklist\n`bl remove [blacklist] [tags]` to remove tags from a blacklist', usage='[flag] [blacklist] ([tags])') + @checks.del_ctx() + async def blacklist(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Use a flag to manage blacklists.**\n*Type* `{}help bl` *for more info.*'.format(ctx.prefix), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - # Searches for and returns images from e621.net given tags when not blacklisted - @commands.group(aliases=['e6', '6'], brief='e621 | NSFW', description='e621 | NSFW\nTag-based search for e621.net\n\nYou can only search 5 tags and 6 images at once for now.\ne6 [tags...] ([# of images])') - @checks.del_ctx() - @checks.is_nsfw() - async def e621(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args, limit=3) - dest, args, limit = kwargs['destination'], kwargs['remaining'], kwargs['limit'] + # @blacklist.error + # async def blacklist_error(self, ctx, error): + # if isinstance(error, KeyError): + # return await ctx.send('**Blacklist does not exist.**', delete_after=10) - tags = self.get_favorites(ctx, args) + @blacklist.group(name='get', aliases=['g']) + async def _get_blacklist(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Invalid blacklist.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - await dest.trigger_typing() + @_get_blacklist.command(name='global', aliases=['gl', 'g']) + async def __get_global_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - posts = await self.check_return_posts(ctx, booru='e621', tags=tags, limit=limit) + await dest.send('\N{NO ENTRY SIGN} **Global blacklist:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']))) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - for ident, post in posts.items(): - embed = d.Embed(title=post['author'], url='https://e621.net/post/show/{}'.format(ident), - color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color).set_image(url=post['url']) - embed.set_author(name=formatter.tostring(tags, random=True), - url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) - embed.set_footer( - text=str(ident), icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + @_get_blacklist.command(name='channel', aliases=['ch', 'c']) + async def __get_channel_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - await dest.send(embed=embed) + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await dest.send('\N{NO ENTRY SIGN} {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set())))) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except exc.TagBlacklisted as e: - await ctx.send('`{}` **blacklisted.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.BoundsError as e: - await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.TagBoundsError as e: - await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.NotFound as e: - await ctx.send('`{}` **not found.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.FavoritesNotFound: - await ctx.send('**You have no favorite tags.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.Timeout: - await ctx.send('**Request timed out.**') - await ctx.message.add_reaction('\N{CROSS MARK}') + @_get_blacklist.command(name='me', aliases=['m']) + async def __get_user_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - # tools.command_dict.setdefault(str(ctx.author.id), {}).update( - # {'command': ctx.command, 'args': ctx.args}) + await dest.send('\N{NO ENTRY SIGN} {}**\'s blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(self.blacklists['user_blacklist'].get(ctx.author.id, set()))), delete_after=10) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @e621.error - async def e621_error(self, ctx, error): - if isinstance(error, errext.CheckFailure): - await ctx.send('\N{NO ENTRY} {} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10) - return await ctx.message.add_reaction('\N{NO ENTRY}') + @_get_blacklist.command(name='here', aliases=['h']) + async def __get_here_blacklists(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - # Searches for and returns images from e926.net given tags when not blacklisted - @commands.command(aliases=['e9', '9'], brief='e926 | SFW', description='e926 | SFW\nTag-based search for e926.net\n\nYou can only search 5 tags and 6 images at once for now.\ne9 [tags...] ([# of images])') - @checks.del_ctx() - async def e926(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args, limit=3) - dest, args, limit = kwargs['destination'], kwargs['remaining'], kwargs['limit'] + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - tags = self.get_favorites(ctx, args) + await dest.send('\N{NO ENTRY SIGN} **__Blacklisted:__**\n\n**Global:**\n```\n{}```\n**{}:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']), ctx.channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set())))) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - await dest.trigger_typing() + @_get_blacklist.group(name='all', aliases=['a']) + async def __get_all_blacklists(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Invalid blacklist.**') + await ctx.message.add_reaction('\N{CROSS MARK}') - posts = await self.check_return_posts(ctx, booru='e926', tags=tags, limit=limit) + @__get_all_blacklists.command(name='guild', aliases=['g']) + @commands.has_permissions(manage_channels=True) + async def ___get_all_guild_blacklists(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - for ident, post in posts.items(): - embed = d.Embed(title=post['author'], url='https://e926.net/post/show/{}'.format(ident), - color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else self.color).set_image(url=post['url']) - embed.set_author(name=formatter.tostring(tags, random=True), - url='https://e621.net/post?tags={}'.format(','.join(tags)), icon_url=ctx.author.avatar_url) - embed.set_footer( - text=str(ident), icon_url='http://lh6.ggpht.com/d3pNZNFCcJM8snBsRSdKUhR9AVBnJMcYYrR92RRDBOzCrxZMhuTeoGOQSmSEn7DAPQ=w300') + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - await dest.send(embed=embed) + await dest.send('\N{NO ENTRY SIGN} **__{} blacklists:__**\n\n{}'.format(guild.name, formatter.dict_tostring(self.blacklists['guild_blacklist'].get(guild.id, {})))) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @__get_all_blacklists.command(name='user', aliases=['u', 'member', 'm']) + @commands.is_owner() + async def ___get_all_user_blacklists(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - except exc.TagBlacklisted as e: - await ctx.send('`{}` **blacklisted.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.BoundsError as e: - await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.TagBoundsError as e: - await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.NotFound as e: - await ctx.send('`{}` **not found.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.FavoritesNotFound: - await ctx.send('**You have no favorite tags.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.Timeout: - await ctx.send('**Request timed out.**') - await ctx.message.add_reaction('\N{CROSS MARK}') + await dest.send('\N{NO ENTRY SIGN} **__User blacklists:__**\n\n{}'.format(formatter.dict_tostring(self.blacklists['user_blacklist']))) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @commands.group(aliases=['fave', 'fav', 'f']) - @checks.del_ctx() - async def favorite(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Use a flag to manage favorites.**\n*Type* `{}help fav` *for more info.*'.format(ctx.prefix), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + @blacklist.group(name='add', aliases=['a']) + async def _add_tags(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Invalid blacklist.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - @favorite.error - async def favorite_error(self, ctx, error): - pass + @_add_tags.command(name='global', aliases=['gl', 'g']) + @commands.is_owner() + async def __add_global_tags(self, ctx, *args): + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - @favorite.group(name='get', aliases=['g']) - async def _get_favorite(self, ctx): - pass + await dest.trigger_typing() - @_get_favorite.command(name='tags', aliases=['t']) - async def __get_favorite_tags(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] + self.blacklists['global_blacklist'].update(tags) + for tag in tags: + alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) + if alias_request: + for dic in alias_request: + self.aliases.setdefault(tag, set()).add(dic['name']) + else: + self.aliases.setdefault(tag, set()) + u.dump(self.blacklists, 'cogs/blacklists.pkl') + u.dump(self.aliases, 'cogs/aliases.pkl') - await dest.send('\N{WHITE MEDIUM STAR} {}**\'s favorite tags:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(self.favorites.get(ctx.author.id, {}).get('tags', set()))), delete_after=10) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await dest.send('**Added to global blacklist:**\n```\n{}```'.format(formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @_get_favorite.command(name='posts', aliases=['p']) - async def __get_favorite_posts(self, ctx): - pass + @_add_tags.command(name='channel', aliases=['ch', 'c']) + @commands.has_permissions(manage_channels=True) + async def __add_channel_tags(self, ctx, *args): + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - @favorite.group(name='add', aliases=['a']) - async def _add_favorite(self, ctx): - pass + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - @_add_favorite.command(name='tags', aliases=['t']) - async def __add_favorite_tags(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] + await dest.trigger_typing() - for tag in tags: - if tag in self.blacklists['user_blacklist'].get(ctx.author.id, set()): - raise exc.TagBlacklisted(tag) - if len(self.favorites[ctx.author.id]['tags']) + len(tags) > 5: - raise exc.BoundsError + self.blacklists['guild_blacklist'].setdefault( + guild.id, {}).setdefault(ctx.channel.id, set()).update(tags) + for tag in tags: + alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) + if alias_request: + for dic in alias_request: + self.aliases.setdefault(tag, set()).add(dic['name']) + else: + self.aliases.setdefault(tag, set()) + u.dump(self.blacklists, 'cogs/blacklists.pkl') + u.dump(self.aliases, 'cogs/aliases.pkl') - self.favorites.setdefault(ctx.author.id, {}).setdefault('tags', set()).update(tags) - u.dump(self.favorites, 'cogs/favorites.pkl') + await dest.send('**Added to** {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - await dest.send('{} **added to their favorites:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @_add_tags.command(name='me', aliases=['m']) + async def __add_user_tags(self, ctx, *args): + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - except exc.BoundsError: - await ctx.send('**Favorites list currently limited to:** `5`', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - except exc.TagBlacklisted as e: - await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted.**', delete_after=10) - await ctx.message.add_reaction('\N{NO ENTRY SIGN}') + await dest.trigger_typing() - @_add_favorite.command(name='posts', aliases=['p']) - async def __add_favorite_posts(self, ctx, *posts): - pass + self.blacklists['user_blacklist'].setdefault(ctx.author.id, set()).update(tags) + for tag in tags: + alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) + if alias_request: + for dic in alias_request: + self.aliases.setdefault(tag, set()).add(dic['name']) + else: + self.aliases.setdefault(tag, set()) + u.dump(self.blacklists, 'cogs/blacklists.pkl') + u.dump(self.aliases, 'cogs/aliases.pkl') - @favorite.group(name='remove', aliases=['r']) - async def _remove_favorite(self, ctx): - pass + await dest.send('{} **added to their blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @_remove_favorite.command(name='tags', aliases=['t']) - async def __remove_favorite_tags(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] + @blacklist.group(name='remove', aliases=['rm', 'r']) + async def _remove_tags(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Invalid blacklist.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - for tag in tags: + @_remove_tags.command(name='global', aliases=['gl', 'g']) + @commands.is_owner() + async def __remove_global_tags(self, ctx, *args): try: - self.favorites[ctx.author.id].get('tags', set()).remove(tag) + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - except KeyError: - raise exc.TagError(tag) + for tag in tags: + try: + self.blacklists['global_blacklist'].remove(tag) - u.dump(self.favorites, 'cogs/favorites.pkl') + except KeyError: + raise exc.TagError(tag) - await dest.send('{} **removed from their favorites:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + u.dump(self.blacklists, 'cogs/blacklists.pkl') - except exc.TagError as e: - await ctx.send('`{}` **not in favorites.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + await dest.send('**Removed from global blacklist:**\n```\n{}```'.format(formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @_remove_favorite.command(name='posts', aliases=['p']) - async def __remove_favorite_posts(self, ctx): - pass + except exc.TagError as e: + await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - @favorite.group(name='clear', aliases=['c']) - async def _clear_favorite(self, ctx): - pass - - @_clear_favorite.command(name='tags', aliases=['t']) - async def __clear_favorite_tags(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - with suppress(KeyError): - del self.favorites[ctx.author.id] - u.dump(self.favorites, 'cogs/favorites.pkl') - - await dest.send('{}**\'s favorites cleared.**'.format(ctx.author.mention), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_clear_favorite.command(name='posts', aliases=['p']) - async def __clear_favorite_posts(self, ctx): - pass - - # Umbrella command structure to manage global, channel, and user blacklists - @commands.group(aliases=['bl', 'b'], brief='Manage blacklists', description='Blacklist base command for managing blacklists\n\n`bl get [blacklist]` to show a blacklist\n`bl set [blacklist] [tags]` to replace a blacklist\n`bl clear [blacklist]` to clear a blacklist\n`bl add [blacklist] [tags]` to add tags to a blacklist\n`bl remove [blacklist] [tags]` to remove tags from a blacklist', usage='[flag] [blacklist] ([tags])') - @checks.del_ctx() - async def blacklist(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Use a flag to manage blacklists.**\n*Type* `{}help bl` *for more info.*'.format(ctx.prefix), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - # @blacklist.error - # async def blacklist_error(self, ctx, error): - # if isinstance(error, KeyError): - # return await ctx.send('**Blacklist does not exist.**', delete_after=10) - - @blacklist.group(name='get', aliases=['g']) - async def _get_blacklist(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Invalid blacklist.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - @_get_blacklist.command(name='global', aliases=['gl', 'g']) - async def __get_global_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - await dest.send('\N{NO ENTRY SIGN} **Global blacklist:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_get_blacklist.command(name='channel', aliases=['ch', 'c']) - async def __get_channel_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - await dest.send('\N{NO ENTRY SIGN} {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set())))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_get_blacklist.command(name='me', aliases=['m']) - async def __get_user_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - await dest.send('\N{NO ENTRY SIGN} {}**\'s blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(self.blacklists['user_blacklist'].get(ctx.author.id, set()))), delete_after=10) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_get_blacklist.command(name='here', aliases=['h']) - async def __get_here_blacklists(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - await dest.send('\N{NO ENTRY SIGN} **__Blacklisted:__**\n\n**Global:**\n```\n{}```\n**{}:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']), ctx.channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(ctx.channel.id, set())))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_get_blacklist.group(name='all', aliases=['a']) - async def __get_all_blacklists(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Invalid blacklist.**') - await ctx.message.add_reaction('\N{CROSS MARK}') - - @__get_all_blacklists.command(name='guild', aliases=['g']) - @commands.has_permissions(manage_channels=True) - async def ___get_all_guild_blacklists(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - await dest.send('\N{NO ENTRY SIGN} **__{} blacklists:__**\n\n{}'.format(guild.name, formatter.dict_tostring(self.blacklists['guild_blacklist'].get(guild.id, {})))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @__get_all_blacklists.command(name='user', aliases=['u', 'member', 'm']) - @commands.is_owner() - async def ___get_all_user_blacklists(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - await dest.send('\N{NO ENTRY SIGN} **__User blacklists:__**\n\n{}'.format(formatter.dict_tostring(self.blacklists['user_blacklist']))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @blacklist.group(name='add', aliases=['a']) - async def _add_tags(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Invalid blacklist.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - @_add_tags.command(name='global', aliases=['gl', 'g']) - @commands.is_owner() - async def __add_global_tags(self, ctx, *args): - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - - await dest.trigger_typing() - - self.blacklists['global_blacklist'].update(tags) - for tag in tags: - alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) - if alias_request: - for dic in alias_request: - self.aliases.setdefault(tag, set()).add(dic['name']) - else: - self.aliases.setdefault(tag, set()) - u.dump(self.blacklists, 'cogs/blacklists.pkl') - u.dump(self.aliases, 'cogs/aliases.pkl') - - await dest.send('**Added to global blacklist:**\n```\n{}```'.format(formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_add_tags.command(name='channel', aliases=['ch', 'c']) - @commands.has_permissions(manage_channels=True) - async def __add_channel_tags(self, ctx, *args): - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - await dest.trigger_typing() - - self.blacklists['guild_blacklist'].setdefault( - guild.id, {}).setdefault(ctx.channel.id, set()).update(tags) - for tag in tags: - alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) - if alias_request: - for dic in alias_request: - self.aliases.setdefault(tag, set()).add(dic['name']) - else: - self.aliases.setdefault(tag, set()) - u.dump(self.blacklists, 'cogs/blacklists.pkl') - u.dump(self.aliases, 'cogs/aliases.pkl') - - await dest.send('**Added to** {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_add_tags.command(name='me', aliases=['m']) - async def __add_user_tags(self, ctx, *args): - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - - await dest.trigger_typing() - - self.blacklists['user_blacklist'].setdefault(ctx.author.id, set()).update(tags) - for tag in tags: - alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) - if alias_request: - for dic in alias_request: - self.aliases.setdefault(tag, set()).add(dic['name']) - else: - self.aliases.setdefault(tag, set()) - u.dump(self.blacklists, 'cogs/blacklists.pkl') - u.dump(self.aliases, 'cogs/aliases.pkl') - - await dest.send('{} **added to their blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @blacklist.group(name='remove', aliases=['rm', 'r']) - async def _remove_tags(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Invalid blacklist.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - @_remove_tags.command(name='global', aliases=['gl', 'g']) - @commands.is_owner() - async def __remove_global_tags(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] - - for tag in tags: + @_remove_tags.command(name='channel', aliases=['ch', 'c']) + @commands.has_permissions(manage_channels=True) + async def __remove_channel_tags(self, ctx, *args): try: - self.blacklists['global_blacklist'].remove(tag) + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - except KeyError: - raise exc.TagError(tag) + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - u.dump(self.blacklists, 'cogs/blacklists.pkl') + for tag in tags: + try: + self.blacklists['guild_blacklist'][guild.id][ctx.channel.id].remove(tag) - await dest.send('**Removed from global blacklist:**\n```\n{}```'.format(formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + except KeyError: + raise exc.TagError(tag) - except exc.TagError as e: - await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + u.dump(self.blacklists, 'cogs/blacklists.pkl') - @_remove_tags.command(name='channel', aliases=['ch', 'c']) - @commands.has_permissions(manage_channels=True) - async def __remove_channel_tags(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] + await dest.send('**Removed from** {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(tags), delete_after=5)) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel + except exc.TagError as e: + await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - for tag in tags: + @_remove_tags.command(name='me', aliases=['m']) + async def __remove_user_tags(self, ctx, *args): try: - self.blacklists['guild_blacklist'][guild.id][ctx.channel.id].remove(tag) + kwargs = u.get_kwargs(ctx, args) + dest, tags = kwargs['destination'], kwargs['remaining'] - except KeyError: - raise exc.TagError(tag) + for tag in tags: + try: + self.blacklists['user_blacklist'][ctx.author.id].remove(tag) - u.dump(self.blacklists, 'cogs/blacklists.pkl') + except KeyError: + raise exc.TagError(tag) - await dest.send('**Removed from** {} **blacklist:**\n```\n{}```'.format(ctx.channel.mention, formatter.tostring(tags), delete_after=5)) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + u.dump(self.blacklists, 'cogs/blacklists.pkl') - except exc.TagError as e: - await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + await dest.send('{} **removed from their blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @_remove_tags.command(name='me', aliases=['m']) - async def __remove_user_tags(self, ctx, *args): - try: - kwargs = u.get_kwargs(ctx, args) - dest, tags = kwargs['destination'], kwargs['remaining'] + except exc.TagError as e: + await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - for tag in tags: - try: - self.blacklists['user_blacklist'][ctx.author.id].remove(tag) + @blacklist.group(name='clear', aliases=['cl', 'c']) + async def _clear_blacklist(self, ctx): + if ctx.invoked_subcommand is None: + await ctx.send('**Invalid blacklist.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') - except KeyError: - raise exc.TagError(tag) + @_clear_blacklist.command(name='global', aliases=['gl', 'g']) + @commands.is_owner() + async def __clear_global_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - u.dump(self.blacklists, 'cogs/blacklists.pkl') + self.blacklists['global_blacklist'].clear() + u.dump(self.blacklists, 'cogs/blacklists.pkl') - await dest.send('{} **removed from their blacklist:**\n```\n{}```'.format(ctx.author.mention, formatter.tostring(tags)), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await dest.send('**Global blacklist cleared.**', delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - except exc.TagError as e: - await ctx.send('`{}` **not in blacklist.**'.format(e), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + @_clear_blacklist.command(name='channel', aliases=['ch', 'c']) + @commands.has_permissions(manage_channels=True) + async def __clear_channel_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - @blacklist.group(name='clear', aliases=['cl', 'c']) - async def _clear_blacklist(self, ctx): - if ctx.invoked_subcommand is None: - await ctx.send('**Invalid blacklist.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + guild = ctx.guild if isinstance( + ctx.guild, d.Guild) else ctx.channel - @_clear_blacklist.command(name='global', aliases=['gl', 'g']) - @commands.is_owner() - async def __clear_global_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] + with suppress(KeyError): + del self.blacklists['guild_blacklist'][guild.id][ctx.channel.id] + u.dump(self.blacklists, 'cogs/blacklists.pkl') - self.blacklists['global_blacklist'].clear() - u.dump(self.blacklists, 'cogs/blacklists.pkl') + await dest.send('{} **blacklist cleared.**'.format(ctx.channel.mention), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - await dest.send('**Global blacklist cleared.**', delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @_clear_blacklist.command(name='me', aliases=['m']) + async def __clear_user_blacklist(self, ctx, *args): + dest = u.get_kwargs(ctx, args)['destination'] - @_clear_blacklist.command(name='channel', aliases=['ch', 'c']) - @commands.has_permissions(manage_channels=True) - async def __clear_channel_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] + with suppress(KeyError): + del self.blacklists['user_blacklist'][ctx.author.id] + u.dump(self.blacklists, 'cogs/blacklists.pkl') - guild = ctx.guild if isinstance( - ctx.guild, d.Guild) else ctx.channel - - with suppress(KeyError): - del self.blacklists['guild_blacklist'][guild.id][ctx.channel.id] - u.dump(self.blacklists, 'cogs/blacklists.pkl') - - await dest.send('{} **blacklist cleared.**'.format(ctx.channel.mention), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - @_clear_blacklist.command(name='me', aliases=['m']) - async def __clear_user_blacklist(self, ctx, *args): - dest = u.get_kwargs(ctx, args)['destination'] - - with suppress(KeyError): - del self.blacklists['user_blacklist'][ctx.author.id] - u.dump(self.blacklists, 'cogs/blacklists.pkl') - - await dest.send('{}**\'s blacklist cleared.**'.format(ctx.author.mention), delete_after=5) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await dest.send('{}**\'s blacklist cleared.**'.format(ctx.author.mention), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') From a74c08867af0fb0a7ea154931a6c5f83baf83674 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:15:18 -0400 Subject: [PATCH 03/18] 2 > 4 space --- src/main/cogs/info.py | 62 +++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/src/main/cogs/info.py b/src/main/cogs/info.py index 24f3351..d01c18d 100644 --- a/src/main/cogs/info.py +++ b/src/main/cogs/info.py @@ -10,40 +10,40 @@ from utils import utils as u class Info: - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - # @commands.command(name='helptest', aliases=['h'], hidden=True) - # async def list_commands(self, ctx): - # embed = d.Embed(title='All possible commands:', color=ctx.me.color) - # embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url) - # embed.add_field( - # name='Booru', value='\n{}bl umbrella command for managing blacklists'.format(u.config['prefix'])) - # - # await ctx.send(embed=embed) + # @commands.command(name='helptest', aliases=['h'], hidden=True) + # async def list_commands(self, ctx): + # embed = d.Embed(title='All possible commands:', color=ctx.me.color) + # embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url) + # embed.add_field( + # name='Booru', value='\n{}bl umbrella command for managing blacklists'.format(u.config['prefix'])) + # + # await ctx.send(embed=embed) - @commands.command(hidden=True) - async def hi(self, ctx, *args): - dest = u.get_kwargs(ctx, args) + @commands.command(hidden=True) + async def hi(self, ctx, *args): + dest = u.get_kwargs(ctx, args) - hello = 'Hewwo, {}.'.format(ctx.author.mention) - if ctx.author.id == checks.owner_id: - hello += '.. ***Master.*** uwu' - elif ctx.author.guild_permissions.administrator: - hello = '{} **Admin** {}'.format(hello[:7], hello[7:]) - elif ctx.author.guild_permissions.ban_members: - hello = '{} **Mod** {}'.format(hello[:7], hello[7:]) - await dest.send(hello) + hello = 'Hewwo, {}.'.format(ctx.author.mention) + if ctx.author.id == checks.owner_id: + hello += '.. ***Master.*** uwu' + elif ctx.author.guild_permissions.administrator: + hello = '{} **Admin** {}'.format(hello[:7], hello[7:]) + elif ctx.author.guild_permissions.ban_members: + hello = '{} **Mod** {}'.format(hello[:7], hello[7:]) + await dest.send(hello) - @commands.group(name='info', aliases=['i']) - async def info(self, ctx): - if invoked_subcommand is None: - await ctx.send('BOT INFO') + @commands.group(name='info', aliases=['i']) + async def info(self, ctx): + if invoked_subcommand is None: + await ctx.send('BOT INFO') - @info.command(aliases=['g', 'server', 's'], brief='Provides info about a guild', hidden=True) - async def guild(self, ctx): - pass + @info.command(aliases=['g', 'server', 's'], brief='Provides info about a guild', hidden=True) + async def guild(self, ctx): + pass - @info.command(aliases=['u', 'member', 'm'], brief='Provides info about a user', hidden=True) - async def user(self, ctx): - pass + @info.command(aliases=['u', 'member', 'm'], brief='Provides info about a user', hidden=True) + async def user(self, ctx): + pass From 1ecd790f839381ffaa3a5b3427041cf49eba3078 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:16:05 -0400 Subject: [PATCH 04/18] Prefix per guild command --- src/main/cogs/management.py | 332 +++++++++++++++++++----------------- src/main/run.py | 12 +- 2 files changed, 181 insertions(+), 163 deletions(-) diff --git a/src/main/cogs/management.py b/src/main/cogs/management.py index 25482cc..5c4733c 100644 --- a/src/main/cogs/management.py +++ b/src/main/cogs/management.py @@ -13,168 +13,180 @@ from utils import utils as u class Administration: - def __init__(self, bot): - self.bot = bot - self.RATE_LIMIT = u.RATE_LIMIT - self.queue = asyncio.Queue() - self.deleting = False - - if u.tasks['auto_del']: - for channel in u.tasks['auto_del']: - temp = self.bot.get_channel(channel) - self.bot.loop.create_task(self.queue_for_deletion(temp)) - print('AUTO-DELETING : #{}'.format(temp.id)) - self.bot.loop.create_task(self.delete()) - self.deleting = True - - @commands.command(name=',prunefromguild', aliases=[',pfg', ',prunefromserver', ',pfs'], brief='Prune a user\'s messages from the guild', description='about flag centers on message 50 of 101 messages\n\npfg \{user id\} [before|after|about] [\{message id\}]\n\nExample:\npfg \{user id\} before \{message id\}') - @commands.is_owner() - @checks.del_ctx() - async def prune_all_user(self, ctx, user, when=None, reference=None): - def yes(msg): - if msg.content.lower() == 'y' and msg.channel is ctx.channel and msg.author is ctx.author: - return True - elif msg.content.lower() == 'n' and msg.channel is ctx.channel and msg.author is ctx.author: - raise exc.CheckFail - else: - return False - - channels = ctx.guild.text_channels - if reference is not None: - for channel in channels: - try: - ref = await channel.get_message(reference) - - except err.NotFound: - continue - - history = [] - try: - pru_sent = await ctx.send('\N{HOURGLASS} **Pruning** <@{}>**\'s messages will take some time.**'.format(user)) - ch_sent = await ctx.send('\N{FILE CABINET} **Caching channels...**') - - if when is None: - for channel in channels: - async for message in channel.history(limit=None): - if message.author.id == int(user): - history.append(message) - await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) - await asyncio.sleep(self.RATE_LIMIT) - elif when == 'before': - for channel in channels: - async for message in channel.history(limit=None, before=ref.created_at): - if message.author.id == int(user): - history.append(message) - await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) - await asyncio.sleep(self.RATE_LIMIT) - elif when == 'after': - for channel in channels: - async for message in channel.history(limit=None, after=ref.created_at): - if message.author.id == int(user): - history.append(message) - await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) - await asyncio.sleep(self.RATE_LIMIT) - elif when == 'about': - for channel in channels: - async for message in channel.history(limit=None, about=ref.created_at): - if message.author.id == int(user): - history.append(message) - await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) - await asyncio.sleep(self.RATE_LIMIT) - - est_sent = await ctx.send('\N{STOPWATCH} **Estimated time to delete history:** `{}m {}s`'.format(int(self.RATE_LIMIT * len(history) / 60), int(self.RATE_LIMIT * len(history) % 60))) - cont_sent = await ctx.send('{} **Continue?** `Y` or `N`'.format(ctx.author.mention)) - await self.bot.wait_for('message', check=yes, timeout=10 * 60) - await cont_sent.delete() - del_sent = await ctx.send('\N{WASTEBASKET} **Deleting messages...**') - await del_sent.pin() - c = 0 - for message in history: - with suppress(err.NotFound): - await message.delete() - c += 1 - await del_sent.edit(content='\N{WASTEBASKET} **Deleted** `{}/{}` **messages.**'.format(history.index(message) + 1, len(history))) - await asyncio.sleep(self.RATE_LIMIT) - await del_sent.unpin() - - await ctx.send('\N{WASTEBASKET} `{}` **of** <@{}>**\'s messages left in** {}**.**'.format(len(history) - c, user, ctx.guild.name)) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - - except exc.CheckFail: - await ctx.send('**Deletion aborted.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - except TimeoutError: - await ctx.send('**Deletion timed out.**', delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') - - async def delete(self): - while self.deleting: - message = await self.queue.get() - await asyncio.sleep(self.RATE_LIMIT) - with suppress(err.NotFound): - if not message.pinned: - await message.delete() - - print('STOPPED : deleting') - - async def queue_for_deletion(self, channel): - def check(msg): - if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator: - raise exc.Abort - elif msg.channel is channel and not msg.pinned: - return True - return False - - try: - async for message in channel.history(limit=None): - if message.content.lower() == 'stop' and message.author.guild_permissions.administrator: - raise exc.Abort - if not message.pinned: - await self.queue.put(message) - - while not self.bot.is_closed(): - message = await self.bot.wait_for('message', check=check) - await self.queue.put(message) - - except exc.Abort: - u.tasks['auto_del'].remove(channel.id) - u.dump(u.tasks, 'cogs/tasks.pkl') - if not u.tasks['auto_del']: + def __init__(self, bot): + self.bot = bot + self.RATE_LIMIT = u.RATE_LIMIT + self.queue = asyncio.Queue() self.deleting = False - print('STOPPED : deleting #{}'.format(channel.id)) - await channel.send('**Stopped queueing messages for deletion in** {}**.**'.format(channel.mention), delete_after=5) - @commands.command(name='autodelete', aliases=['autodel', 'ad']) - @commands.has_permissions(administrator=True) - @checks.del_ctx() - async def auto_delete(self, ctx): - try: - if ctx.channel.id not in u.tasks['auto_del']: - u.tasks['auto_del'].append(ctx.channel.id) - u.dump(u.tasks, 'cogs/tasks.pkl') - self.bot.loop.create_task(self.queue_for_deletion(ctx.channel)) - if not self.deleting: - self.bot.loop.create_task(self.delete()) - self.deleting = True - print('AUTO-DELETING : #{}'.format(ctx.channel.id)) - await ctx.send('**Auto-deleting all messages in {}.**'.format(ctx.channel.mention), delete_after=5) + if u.tasks['auto_del']: + for channel in u.tasks['auto_del']: + temp = self.bot.get_channel(channel) + self.bot.loop.create_task(self.queue_for_deletion(temp)) + print('AUTO-DELETING : #{}'.format(temp.id)) + self.bot.loop.create_task(self.delete()) + self.deleting = True + + @commands.command(name=',prunefromguild', aliases=[',pfg', ',prunefromserver', ',pfs'], brief='Prune a user\'s messages from the guild', description='about flag centers on message 50 of 101 messages\n\npfg \{user id\} [before|after|about] [\{message id\}]\n\nExample:\npfg \{user id\} before \{message id\}') + @commands.is_owner() + @checks.del_ctx() + async def prune_all_user(self, ctx, user, when=None, reference=None): + def yes(msg): + if msg.content.lower() == 'y' and msg.channel is ctx.channel and msg.author is ctx.author: + return True + elif msg.content.lower() == 'n' and msg.channel is ctx.channel and msg.author is ctx.author: + raise exc.CheckFail + else: + return False + + channels = ctx.guild.text_channels + if reference is not None: + for channel in channels: + try: + ref = await channel.get_message(reference) + + except err.NotFound: + continue + + history = [] + try: + pru_sent = await ctx.send('\N{HOURGLASS} **Pruning** <@{}>**\'s messages will take some time.**'.format(user)) + ch_sent = await ctx.send('\N{FILE CABINET} **Caching channels...**') + + if when is None: + for channel in channels: + async for message in channel.history(limit=None): + if message.author.id == int(user): + history.append(message) + await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) + await asyncio.sleep(self.RATE_LIMIT) + elif when == 'before': + for channel in channels: + async for message in channel.history(limit=None, before=ref.created_at): + if message.author.id == int(user): + history.append(message) + await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) + await asyncio.sleep(self.RATE_LIMIT) + elif when == 'after': + for channel in channels: + async for message in channel.history(limit=None, after=ref.created_at): + if message.author.id == int(user): + history.append(message) + await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) + await asyncio.sleep(self.RATE_LIMIT) + elif when == 'about': + for channel in channels: + async for message in channel.history(limit=None, about=ref.created_at): + if message.author.id == int(user): + history.append(message) + await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels))) + await asyncio.sleep(self.RATE_LIMIT) + + est_sent = await ctx.send('\N{STOPWATCH} **Estimated time to delete history:** `{}m {}s`'.format(int(self.RATE_LIMIT * len(history) / 60), int(self.RATE_LIMIT * len(history) % 60))) + cont_sent = await ctx.send('{} **Continue?** `Y` or `N`'.format(ctx.author.mention)) + await self.bot.wait_for('message', check=yes, timeout=10 * 60) + await cont_sent.delete() + del_sent = await ctx.send('\N{WASTEBASKET} **Deleting messages...**') + await del_sent.pin() + c = 0 + for message in history: + with suppress(err.NotFound): + await message.delete() + c += 1 + await del_sent.edit(content='\N{WASTEBASKET} **Deleted** `{}/{}` **messages.**'.format(history.index(message) + 1, len(history))) + await asyncio.sleep(self.RATE_LIMIT) + await del_sent.unpin() + + await ctx.send('\N{WASTEBASKET} `{}` **of** <@{}>**\'s messages left in** {}**.**'.format(len(history) - c, user, ctx.guild.name)) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + + except exc.CheckFail: + await ctx.send('**Deletion aborted.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + except TimeoutError: + await ctx.send('**Deletion timed out.**', delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + async def delete(self): + while self.deleting: + message = await self.queue.get() + await asyncio.sleep(self.RATE_LIMIT) + with suppress(err.NotFound): + if not message.pinned: + await message.delete() + + print('STOPPED : deleting') + + async def queue_for_deletion(self, channel): + def check(msg): + if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator: + raise exc.Abort + elif msg.channel is channel and not msg.pinned: + return True + return False + + try: + async for message in channel.history(limit=None): + if message.content.lower() == 'stop' and message.author.guild_permissions.administrator: + raise exc.Abort + if not message.pinned: + await self.queue.put(message) + + while not self.bot.is_closed(): + message = await self.bot.wait_for('message', check=check) + await self.queue.put(message) + + except exc.Abort: + u.tasks['auto_del'].remove(channel.id) + u.dump(u.tasks, 'cogs/tasks.pkl') + if not u.tasks['auto_del']: + self.deleting = False + print('STOPPED : deleting #{}'.format(channel.id)) + await channel.send('**Stopped queueing messages for deletion in** {}**.**'.format(channel.mention), delete_after=5) + + @commands.command(name='autodelete', aliases=['autodel', 'ad']) + @commands.has_permissions(administrator=True) + @checks.del_ctx() + async def auto_delete(self, ctx): + try: + if ctx.channel.id not in u.tasks['auto_del']: + u.tasks['auto_del'].append(ctx.channel.id) + u.dump(u.tasks, 'cogs/tasks.pkl') + self.bot.loop.create_task(self.queue_for_deletion(ctx.channel)) + if not self.deleting: + self.bot.loop.create_task(self.delete()) + self.deleting = True + print('AUTO-DELETING : #{}'.format(ctx.channel.id)) + await ctx.send('**Auto-deleting all messages in {}.**'.format(ctx.channel.mention), delete_after=5) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + else: + raise exc.Exists + + except exc.Exists: + await ctx.send('**Already auto-deleting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) + await ctx.message.add_reaction('\N{CROSS MARK}') + + @commands.command(name='deletecommands', aliases=['delcmds']) + @commands.has_permissions(administrator=True) + async def delete_commands(self, ctx): + if ctx.guild.id not in u.settings['del_ctx']: + u.settings['del_ctx'].append(ctx.guild.id) + else: + u.settings['del_ctx'].remove(ctx.guild.id) + u.dump(u.settings, 'settings.pkl') + + await ctx.send('**Delete command invocations:** `{}`'.format(ctx.guild.id in u.settings['del_ctx'])) await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - else: - raise exc.Exists - except exc.Exists: - await ctx.send('**Already auto-deleting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10) - await ctx.message.add_reaction('\N{CROSS MARK}') + @commands.command(name='setprefix', aliases=['setpre', 'spre']) + @commands.has_permissions(administrator=True) + async def set_prefix(self, ctx, prefix=None): + if prefix is not None: + u.settings['prefixes'][ctx.guild.id] = prefix + else: + with suppress(KeyError): + del u.settings['prefixes'][ctx.guild.id] - @commands.command(name='deletecommands', aliases=['delcmds']) - @commands.has_permissions(administrator=True) - async def delete_commands(self, ctx): - if ctx.guild.id not in u.settings['del_ctx']: - u.settings['del_ctx'].append(ctx.guild.id) - else: - u.settings['del_ctx'].remove(ctx.guild.id) - u.dump(u.settings, 'settings.pkl') - - await ctx.send('**Delete command invocations:** `{}`'.format(ctx.guild.id in u.settings['del_ctx'])) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await ctx.send(f'**Prefix set to:** `{"` or `".join(prefix if ctx.guild.id in u.settings["prefixes"] else u.config["prefix"])}`') + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') diff --git a/src/main/run.py b/src/main/run.py index 34c2263..3bc600f 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -18,13 +18,19 @@ from utils import utils as u # log.basicConfig(level=log.INFO) -bot = commands.Bot(command_prefix=u.config['prefix'], description='Experimental miscellaneous bot') +def get_prefix(bot, message): + if isinstance(message.guild, d.Guild) and message.guild.id in u.settings['prefixes']: + return u.settings['prefixes'][message.guild.id] + return u.config['prefix'] + + +bot = commands.Bot(command_prefix=get_prefix, description='Experimental miscellaneous bot') # Send and print ready message to #testing and console after logon @bot.event async def on_ready(): - from cogs import booru, info, management, owner, tools + from cogs import booru, info, management, owner, tools bot.add_cog(tools.Utils(bot)) bot.add_cog(owner.Bot(bot)) @@ -33,7 +39,7 @@ async def on_ready(): bot.add_cog(info.Info(bot)) bot.add_cog(booru.MsG(bot)) - # bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) + # bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) if u.config['playing'] is not 'None': await bot.change_presence(game=d.Game(name=u.config['playing'])) From d576e4d6a307ef28a85b8fd69df396071510b6d9 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:17:16 -0400 Subject: [PATCH 05/18] Compressed add_cog to for loop --- src/main/run.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index 3bc600f..0ce49f3 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -28,16 +28,15 @@ def get_prefix(bot, message): bot = commands.Bot(command_prefix=get_prefix, description='Experimental miscellaneous bot') # Send and print ready message to #testing and console after logon + + @bot.event async def on_ready(): from cogs import booru, info, management, owner, tools - bot.add_cog(tools.Utils(bot)) - bot.add_cog(owner.Bot(bot)) - bot.add_cog(owner.Tools(bot)) - bot.add_cog(management.Administration(bot)) - bot.add_cog(info.Info(bot)) - bot.add_cog(booru.MsG(bot)) + for cog in (tools.Utils(bot), owner.Bot(bot), owner.Tools(bot), management.Administration(bot), info.Info(bot), booru.MsG(bot)): + bot.add_cog(cog) + print(f'COG : {type(cog).__name__}') # bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) From 1443dce3566baf2733d8b7dfc2c182e31220a270 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:17:55 -0400 Subject: [PATCH 06/18] on_message override to check if invoker is bot --- src/main/run.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index 0ce49f3..6d46849 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -55,15 +55,23 @@ async def on_ready(): u.temp.clear() +@bot.event +async def on_message(message): + if message.author.bot or message.author is bot.user: + return + + await bot.process_commands(message) + + @bot.event async def on_error(error, *args, **kwargs): - print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr) - tb.print_exc() + print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr) + tb.print_exc() await bot.get_user(u.config['owner_id']).send('**ERROR** ⚠ `{}`'.format(error)) await bot.get_channel(u.config['info_channel']).send('**ERROR** ⚠ `{}`'.format(error)) - # u.notify('E R R O R') - await bot.logout() - u.close(bot.loop) + # u.notify('E R R O R') + await bot.logout() + u.close(bot.loop) @bot.event From 4d92778c8a7ebbb90d88fd895b98fa4d58cf293c Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:19:15 -0400 Subject: [PATCH 07/18] Misc testing --- src/main/run.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index 6d46849..b1b0817 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -130,16 +130,8 @@ def after(voice, error): @commands.is_owner() @checks.del_ctx() async def test(ctx): - def check(react, user): - return reaction.emoji == '\N{THUMBS UP SIGN}' - # channel = bot.get_channel(int(cid)) - # voice = await channel.connect() - # voice.play(d.AudioSource, after=lambda: after(voice)) - test = await ctx.send('thumbs up!') - while True: - done, pending = await asyncio.wait([bot.wait_for('reaction_add', check=check), bot.wait_for('reaction_remove', check=check)], return_when=asyncio.FIRST_COMPLETED) - await ctx.send('well doneeee') - # bot.add_listener(on_reaction_add) - # bot.add_listener(on_reaction_remove) + channel = bot.get_channel(int(cid)) + voice = await channel.connect() + voice.play(d.AudioSource, after=lambda: after(voice)) bot.run(u.config['token']) From 22afd87d8b2d7236298362027fc19e7d595abb44 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:19:58 -0400 Subject: [PATCH 08/18] =?UTF-8?q?=E2=9A=A0=EF=B8=8F=20>=20\N{WARNING=20SIG?= =?UTF-8?q?N}?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/run.py | 89 ++++++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 42 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index b1b0817..f908b46 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -40,19 +40,19 @@ async def on_ready(): # bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) - if u.config['playing'] is not 'None': - await bot.change_presence(game=d.Game(name=u.config['playing'])) - else: - await bot.change_presence(game=None) + if u.config['playing'] is not 'None': + await bot.change_presence(game=d.Game(name=u.config['playing'])) + else: + await bot.change_presence(game=None) - print('\n\\ \\ \\ \\ \\ \\ \\ \\ \\\nC O N N E C T E D : {}\n/ / / / / / / / /\n'.format(bot.user.name)) - await bot.get_channel(u.config['info_channel']).send('**Started** \N{BLACK SUN WITH RAYS} .') - # u.notify('C O N N E C T E D') - if u.temp: - channel = bot.get_channel(u.temp['restart_ch']) - message = await channel.get_message(u.temp['restart_msg']) - await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - u.temp.clear() + print('\n\\ \\ \\ \\ \\ \\ \\ \\ \\\nC O N N E C T E D : {}\n/ / / / / / / / /\n'.format(bot.user.name)) + await bot.get_channel(u.config['info_channel']).send('**Started** \N{BLACK SUN WITH RAYS} .') + # u.notify('C O N N E C T E D') + if u.temp: + channel = bot.get_channel(u.temp['restart_ch']) + message = await channel.get_message(u.temp['restart_msg']) + await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + u.temp.clear() @bot.event @@ -67,8 +67,13 @@ async def on_message(message): async def on_error(error, *args, **kwargs): print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr) tb.print_exc() - await bot.get_user(u.config['owner_id']).send('**ERROR** ⚠ `{}`'.format(error)) - await bot.get_channel(u.config['info_channel']).send('**ERROR** ⚠ `{}`'.format(error)) + await bot.get_user(u.config['owner_id']).send('**ERROR** \N{WARNING SIGN} `{}`'.format(error)) + await bot.get_channel(u.config['info_channel']).send('**ERROR** \N{WARNING SIGN} `{}`'.format(error)) + if u.temp: + channel = bot.get_channel(u.temp['restart_ch']) + message = await channel.get_message(u.temp['restart_msg']) + await message.add_reaction('\N{WARNING SIGN}') + u.temp.clear() # u.notify('E R R O R') await bot.logout() u.close(bot.loop) @@ -76,54 +81,54 @@ async def on_error(error, *args, **kwargs): @bot.event async def on_command_error(ctx, error): - if isinstance(error, errext.CheckFailure): - await ctx.send('\N{NO ENTRY} **Insufficient permissions.**', delete_after=10) - await ctx.message.add_reaction('\N{NO ENTRY}') - elif isinstance(error, errext.CommandNotFound): - print('INVALID COMMAND : {}'.format(error), file=sys.stderr) - await ctx.message.add_reaction('\N{CROSS MARK}') - else: - print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format( - error), file=sys.stderr) - tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr) - await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** ⚠ `{}`'.format(error)) - await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** ⚠ `{}`'.format(error)) - await exc.send_error(ctx, error) - await ctx.message.add_reaction('⚠') - # u.notify('C O M M A N D E R R O R') + if isinstance(error, errext.CheckFailure): + await ctx.send('\N{NO ENTRY} **Insufficient permissions.**', delete_after=10) + await ctx.message.add_reaction('\N{NO ENTRY}') + elif isinstance(error, errext.CommandNotFound): + print('INVALID COMMAND : {}'.format(error), file=sys.stderr) + await ctx.message.add_reaction('\N{CROSS MARK}') + else: + print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format( + error), file=sys.stderr) + tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr) + await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}`'.format(error)) + await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}`'.format(error)) + await exc.send_error(ctx, error) + await ctx.message.add_reaction('\N{WARNING SIGN}') + # u.notify('C O M M A N D E R R O R') async def on_reaction_add(r, u): - pass + pass async def on_reaction_remove(r, u): - pass + pass async def reaction_add(r, u): - bot.add_listener(on_reaction_add) - print('Reacted') - bot.remove_listener(on_reaction_remove) + bot.add_listener(on_reaction_add) + print('Reacted') + bot.remove_listener(on_reaction_remove) async def reaction_remove(r, u): - bot.add_listener(on_reaction_remove) - print('Removed') - bot.remove_listener(on_reaction_remove) + bot.add_listener(on_reaction_remove) + print('Removed') + bot.remove_listener(on_reaction_remove) # d.opus.load_opus('opus') async def wait(voice): - asyncio.sleep(5) - await voice.disconnect() + asyncio.sleep(5) + await voice.disconnect() def after(voice, error): - coro = voice.disconnect() - future = asyncio.run_coroutine_threadsafe(coro, voice.loop) - future.result() + coro = voice.disconnect() + future = asyncio.run_coroutine_threadsafe(coro, voice.loop) + future.result() @bot.command(name=',test', hidden=True) From e927ccca9d0e640d9c574d6ee5c182c71de60aaa Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:20:33 -0400 Subject: [PATCH 09/18] Added "LOADED :" --- src/main/utils/utils.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/utils/utils.py b/src/main/utils/utils.py index 38aa546..29fef8d 100644 --- a/src/main/utils/utils.py +++ b/src/main/utils/utils.py @@ -22,23 +22,23 @@ print('\nPID : {}\n'.format(os.getpid())) try: with open('config.json') as infile: config = jsn.load(infile) - print('config.json loaded.') + print('LOADED : config.json') except FileNotFoundError: with open('config.json', 'w') as outfile: jsn.dump({'client_id': 0, 'info_channel': 0, 'owner_id': 0, 'permissions': 126016, 'playing': 'a game', 'prefix': [',', 'm,'], 'token': 'str'}, outfile, indent=4, sort_keys=True) raise FileNotFoundError( - 'Config file not found: config.json created with abstract values. Restart run.py with correct values.') + 'FILE NOT FOUND : config.json created with abstract values. Restart run.py with correct values') def setdefault(filename, default=None): try: with open(filename, 'rb') as infile: - print('{} loaded.'.format(filename)) + print('LOADED : {}'.format(filename)) return pkl.load(infile) except FileNotFoundError: with open(filename, 'wb+') as iofile: - print('File not found: {} created and loaded with default values.'.format(filename)) + print('FILE NOT FOUND : {} created and loaded with default values'.format(filename)) pkl.dump(default, iofile) iofile.seek(0) return pkl.load(iofile) From dc63ec794e54f5245a38388b98bd913f0c32a815 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:20:47 -0400 Subject: [PATCH 10/18] isdigit() --- src/main/utils/utils.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/utils/utils.py b/src/main/utils/utils.py index 29fef8d..d75ca93 100644 --- a/src/main/utils/utils.py +++ b/src/main/utils/utils.py @@ -137,8 +137,7 @@ def get_kwargs(ctx, args, *, limit=False): if limit: for arg in remaining: - if 1 <= len(arg) <= 2: - with suppress(ValueError): + if arg.isdigit(): if 1 <= int(arg) <= limit: lim = int(arg) remaining.remove(arg) From c1a0f5850d780ad66e228526b2ee779ee5e4d8f6 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:22:14 -0400 Subject: [PATCH 11/18] User-Agent tweak --- src/main/utils/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/utils/utils.py b/src/main/utils/utils.py index d75ca93..e32a1aa 100644 --- a/src/main/utils/utils.py +++ b/src/main/utils/utils.py @@ -106,7 +106,7 @@ def close(loop): async def fetch(url, *, params={}, json=False): global session - async with session.get(url, params=params, headers={'user-agent': 'Modumind/0.0.1 (Myned)'}) as r: + async with session.get(url, params=params, headers={'User-Agent': 'Myned/Modumind/0.0.1'}) as r: if json: return await r.json() return await r.read() From 8a0ba12f2074b3dae6130dc3eff93887ab9adee7 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:23:01 -0400 Subject: [PATCH 12/18] Added prefixes dict to settings file --- src/main/utils/utils.py | 130 ++++++++++++++++++++-------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/src/main/utils/utils.py b/src/main/utils/utils.py index e32a1aa..c3989ef 100644 --- a/src/main/utils/utils.py +++ b/src/main/utils/utils.py @@ -20,49 +20,49 @@ print('\nPID : {}\n'.format(os.getpid())) try: - with open('config.json') as infile: - config = jsn.load(infile) + with open('config.json') as infile: + config = jsn.load(infile) print('LOADED : config.json') except FileNotFoundError: - with open('config.json', 'w') as outfile: - jsn.dump({'client_id': 0, 'info_channel': 0, 'owner_id': 0, 'permissions': 126016, - 'playing': 'a game', 'prefix': [',', 'm,'], 'token': 'str'}, outfile, indent=4, sort_keys=True) - raise FileNotFoundError( + with open('config.json', 'w') as outfile: + jsn.dump({'client_id': 0, 'info_channel': 0, 'owner_id': 0, 'permissions': 126016, + 'playing': 'a game', 'prefix': [',', 'm,'], 'token': 'str'}, outfile, indent=4, sort_keys=True) + raise FileNotFoundError( 'FILE NOT FOUND : config.json created with abstract values. Restart run.py with correct values') def setdefault(filename, default=None): - try: - with open(filename, 'rb') as infile: + try: + with open(filename, 'rb') as infile: print('LOADED : {}'.format(filename)) - return pkl.load(infile) - except FileNotFoundError: - with open(filename, 'wb+') as iofile: + return pkl.load(infile) + except FileNotFoundError: + with open(filename, 'wb+') as iofile: print('FILE NOT FOUND : {} created and loaded with default values'.format(filename)) - pkl.dump(default, iofile) - iofile.seek(0) - return pkl.load(iofile) + pkl.dump(default, iofile) + iofile.seek(0) + return pkl.load(iofile) def load(filename, *, json=False): - if not json: - with open(filename, 'rb') as infile: - return pkl.load(infile) - else: - with open(filename) as infile: - return jsn.load(infile) + if not json: + with open(filename, 'rb') as infile: + return pkl.load(infile) + else: + with open(filename) as infile: + return jsn.load(infile) def dump(obj, filename, *, json=False): - if not json: - with open(filename, 'wb') as outfile: - pkl.dump(obj, outfile) - else: - with open(filename, 'w') as outfile: - jsn.dump(obj, outfile, indent=4, sort_keys=True) + if not json: + with open(filename, 'wb') as outfile: + pkl.dump(obj, outfile) + else: + with open(filename, 'w') as outfile: + jsn.dump(obj, outfile, indent=4, sort_keys=True) -settings = setdefault('settings.pkl', {'del_ctx': []}) +settings = setdefault('settings.pkl', {'del_ctx': [], 'prefixes': {}}) tasks = setdefault('cogs/tasks.pkl', {'auto_del': [], 'auto_qual': [], 'auto_rev': []}) temp = setdefault('temp.pkl', {}) @@ -87,62 +87,62 @@ session = aiohttp.ClientSession() def close(loop): - global session + global session - if session: - session.close() + if session: + session.close() - loop.stop() - pending = asyncio.Task.all_tasks() - for task in pending: - task.cancel() - # with suppress(asyncio.CancelledError): - # loop.run_until_complete(task) - # loop.close() + loop.stop() + pending = asyncio.Task.all_tasks() + for task in pending: + task.cancel() + # with suppress(asyncio.CancelledError): + # loop.run_until_complete(task) + # loop.close() - print('Finished cancelling tasks.') + print('Finished cancelling tasks.') async def fetch(url, *, params={}, json=False): - global session + global session async with session.get(url, params=params, headers={'User-Agent': 'Myned/Modumind/0.0.1'}) as r: - if json: - return await r.json() - return await r.read() + if json: + return await r.json() + return await r.read() # def geneate_embed(**kwargs): # embed = d.Embed(title=kwargs['title'], ) def get_kwargs(ctx, args, *, limit=False): - destination = ctx - remaining = list(args[:]) - rm = False - lim = 1 + destination = ctx + remaining = list(args[:]) + rm = False + lim = 1 - if '-d' in remaining or '-dm' in remaining: - destination = ctx.author + if '-d' in remaining or '-dm' in remaining: + destination = ctx.author - for flag in ('-d', '-dm'): - with suppress(ValueError): - remaining.remove(flag) + for flag in ('-d', '-dm'): + with suppress(ValueError): + remaining.remove(flag) - if ('-r' in remaining or '-rm' in remaining or '-remove' in remaining) and ctx.author.permissions_in(ctx.channel).manage_messages: - rm = True + if ('-r' in remaining or '-rm' in remaining or '-remove' in remaining) and ctx.author.permissions_in(ctx.channel).manage_messages: + rm = True - for flag in ('-r', '-rm', '-remove'): - with suppress(ValueError): - remaining.remove(flag) + for flag in ('-r', '-rm', '-remove'): + with suppress(ValueError): + remaining.remove(flag) - if limit: - for arg in remaining: + if limit: + for arg in remaining: if arg.isdigit(): - if 1 <= int(arg) <= limit: - lim = int(arg) - remaining.remove(arg) - break - else: - raise exc.BoundsError(arg) + if 1 <= int(arg) <= limit: + lim = int(arg) + remaining.remove(arg) + break + else: + raise exc.BoundsError(arg) - return {'destination': destination, 'remaining': remaining, 'remove': rm, 'limit': lim} + return {'destination': destination, 'remaining': remaining, 'remove': rm, 'limit': lim} From 51a002bb3fd75f16c560c2b7616c8bf5b510e3e3 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:23:27 -0400 Subject: [PATCH 13/18] 2 > 4 space --- src/main/misc/checks.py | 48 +++++++++++++++++++-------------------- src/main/utils/scraper.py | 30 ++++++++++++------------ 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/main/misc/checks.py b/src/main/misc/checks.py index 261911f..1c080e8 100644 --- a/src/main/misc/checks.py +++ b/src/main/misc/checks.py @@ -14,48 +14,48 @@ owner_id = u.config['owner_id'] def is_owner(): - async def predicate(ctx): - return ctx.message.author.id == owner_id - return commands.check(predicate) + async def predicate(ctx): + return ctx.message.author.id == owner_id + return commands.check(predicate) def is_admin(): - def predicate(ctx): - return ctx.message.author.guild_permissions.administrator - return commands.check(predicate) + def predicate(ctx): + return ctx.message.author.guild_permissions.administrator + return commands.check(predicate) def is_mod(): - def predicate(ctx): - return ctx.message.author.guild_permissions.ban_members - return commands.check(predicate) + def predicate(ctx): + return ctx.message.author.guild_permissions.ban_members + return commands.check(predicate) def owner(ctx): - return ctx.message.author.id == owner_id + return ctx.message.author.id == owner_id def admin(ctx): - return ctx.message.author.guild_permissions.administrator + return ctx.message.author.guild_permissions.administrator def mod(ctx): - return ctx.message.author.guild_permissions.ban_members + return ctx.message.author.guild_permissions.ban_members def is_nsfw(): - def predicate(ctx): - if isinstance(ctx.message.channel, d.TextChannel): - return ctx.message.channel.is_nsfw() - return True - return commands.check(predicate) + def predicate(ctx): + if isinstance(ctx.message.channel, d.TextChannel): + return ctx.message.channel.is_nsfw() + return True + return commands.check(predicate) def del_ctx(): - async def predicate(ctx): - with suppress(AttributeError): - if ctx.guild.id in u.settings['del_ctx'] and ctx.me.permissions_in(ctx.channel).manage_messages and isinstance(ctx.message.channel, d.TextChannel): - with suppress(err.NotFound): - await ctx.message.delete() - return True - return commands.check(predicate) + async def predicate(ctx): + with suppress(AttributeError): + if ctx.guild.id in u.settings['del_ctx'] and ctx.me.permissions_in(ctx.channel).manage_messages and isinstance(ctx.message.channel, d.TextChannel): + with suppress(err.NotFound): + await ctx.message.delete() + return True + return commands.check(predicate) diff --git a/src/main/utils/scraper.py b/src/main/utils/scraper.py index afdac07..1c4fabc 100644 --- a/src/main/utils/scraper.py +++ b/src/main/utils/scraper.py @@ -8,26 +8,26 @@ from utils import utils as u async def get_post(url): - content = await u.fetch('http://iqdb.harry.lu', params={'url': url}) + content = await u.fetch('http://iqdb.harry.lu', params={'url': url}) - try: - value = BeautifulSoup(content, 'html.parser').find_all('a')[1].get('href') - if value != '#': - return value - else: - raise IndexError - except IndexError: try: - raise exc.MatchError(re.search('\/([^\/]+)$', url).group(1)) + value = BeautifulSoup(content, 'html.parser').find_all('a')[1].get('href') + if value != '#': + return value + else: + raise IndexError + except IndexError: + try: + raise exc.MatchError(re.search('\/([^\/]+)$', url).group(1)) - except AttributeError: - raise exc.MissingArgument + except AttributeError: + raise exc.MissingArgument async def get_image(url): - content = await u.fetch(url) + content = await u.fetch(url) - value = html.fromstring(content).xpath( - 'string(/html/body/div[@id="content"]/div[@id="post-view"]/div[@class="content"]/div[2]/img/@src)') + value = html.fromstring(content).xpath( + 'string(/html/body/div[@id="content"]/div[@id="post-view"]/div[@class="content"]/div[2]/img/@src)') - return value + return value From 9edaac780361f11fb206e10e15e1c6f632ca6060 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:24:19 -0400 Subject: [PATCH 14/18] Removed global nl --- src/main/cogs/owner.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/cogs/owner.py b/src/main/cogs/owner.py index 1434041..7463996 100644 --- a/src/main/cogs/owner.py +++ b/src/main/cogs/owner.py @@ -14,8 +14,6 @@ from misc import exceptions as exc from misc import checks from utils import utils as u -nl = re.compile('\n') - class Bot: @@ -99,9 +97,8 @@ class Tools: return await d.send('```python\n{}```'.format(self.format(i, o))) async def refresh(self, m, i='', o=''): - global nl - output = m.content[10:-2] - if len(nl.findall(output)) <= 20: + output = m.content[9:-3] + if len(re.findall('\n', output)) <= 20: await m.edit(content='```python\n{}\n{}\n>>>```'.format(output, self.format(i, o))) else: await m.edit(content='```python\n{}```'.format(self.format(i, o))) From 12c577d9b163ba41c3e07648d82360630d88de37 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:24:43 -0400 Subject: [PATCH 15/18] 2 > 4, WIP console tweaking --- src/main/cogs/owner.py | 293 +++++++++++++++++++++++------------------ 1 file changed, 163 insertions(+), 130 deletions(-) diff --git a/src/main/cogs/owner.py b/src/main/cogs/owner.py index 7463996..19a9718 100644 --- a/src/main/cogs/owner.py +++ b/src/main/cogs/owner.py @@ -5,6 +5,7 @@ import os import re import sys import traceback as tb +from contextlib import suppress import discord as d import pyrasite as pyr @@ -17,165 +18,197 @@ from utils import utils as u class Bot: - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - # Close connection to Discord - immediate offline - @commands.command(name=',die', aliases=[',d'], brief='Kills the bot', description='BOT OWNER ONLY\nCloses the connection to Discord', hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def die(self, ctx): - await ctx.message.add_reaction('\N{NEW MOON SYMBOL}') + # Close connection to Discord - immediate offline + @commands.command(name=',die', aliases=[',d'], brief='Kills the bot', description='BOT OWNER ONLY\nCloses the connection to Discord', hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def die(self, ctx): + await ctx.message.add_reaction('\N{NEW MOON SYMBOL}') - await self.bot.get_channel(u.config['info_channel']).send('**Shutting down** \N{NEW MOON SYMBOL} . . .') - # loop = self.bot.loop.all_tasks() - # for task in loop: - # task.cancel() - await self.bot.logout() - u.close(self.bot.loop) - print('\n/ / / / / / / / / / / /\nD I S C O N N E C T E D\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n') - # u.notify('D I S C O N N E C T E D') + await self.bot.get_channel(u.config['info_channel']).send('**Shutting down** \N{NEW MOON SYMBOL} . . .') + # loop = self.bot.loop.all_tasks() + # for task in loop: + # task.cancel() + await self.bot.logout() + u.close(self.bot.loop) + print('\n/ / / / / / / / / / / /\nD I S C O N N E C T E D\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n') + # u.notify('D I S C O N N E C T E D') - @commands.command(name=',restart', aliases=[',res', ',r'], hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def restart(self, ctx): - await ctx.message.add_reaction('\N{SLEEPING SYMBOL}') + @commands.command(name=',restart', aliases=[',res', ',r'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def restart(self, ctx): + await ctx.message.add_reaction('\N{SLEEPING SYMBOL}') - print('\n| | | | | | | | | |\nR E S T A R T I N G\n| | | | | | | | | |\n') - await self.bot.get_channel(u.config['info_channel']).send('**Restarting** \N{SLEEPING SYMBOL} . . .') - # u.notify('R E S T A R T I N G') + print('\n| | | | | | | | | |\nR E S T A R T I N G\n| | | | | | | | | |\n') + await self.bot.get_channel(u.config['info_channel']).send('**Restarting** \N{SLEEPING SYMBOL} . . .') + # u.notify('R E S T A R T I N G') - u.temp['restart_ch'] = ctx.channel.id - u.temp['restart_msg'] = ctx.message.id - u.dump(u.temp, 'temp.pkl') + u.temp['restart_ch'] = ctx.channel.id + u.temp['restart_msg'] = ctx.message.id + u.dump(u.temp, 'temp.pkl') - # loop = self.bot.loop.all_tasks() - # for task in loop: - # task.cancel() - await self.bot.logout() - u.close(self.bot.loop) - os.execl(sys.executable, 'python3', 'run.py') + # loop = self.bot.loop.all_tasks() + # for task in loop: + # task.cancel() + await self.bot.logout() + u.close(self.bot.loop) + os.execl(sys.executable, 'python3', 'run.py') - # Invite bot to bot owner's server - @commands.command(name=',invite', aliases=[',inv', ',link'], brief='Invite the bot', description='BOT OWNER ONLY\nInvite the bot to a server (Requires admin)', hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def invite(self, ctx): - await ctx.message.add_reaction('\N{ENVELOPE}') + # Invite bot to bot owner's server + @commands.command(name=',invite', aliases=[',inv', ',link'], brief='Invite the bot', description='BOT OWNER ONLY\nInvite the bot to a server (Requires admin)', hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def invite(self, ctx): + await ctx.message.add_reaction('\N{ENVELOPE}') - await ctx.send('https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(u.config['client_id'], u.config['permissions']), delete_after=10) + await ctx.send('https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(u.config['client_id'], u.config['permissions']), delete_after=10) - @commands.command(name=',status', aliases=[',presence', ',game'], hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def status(self, ctx, *, game=None): - if game is not None: - await self.bot.change_presence(game=d.Game(name=game)) - u.config['playing'] = game - u.dump(u.config, 'config.json', json=True) - else: - await self.bot.change_presence(game=None) - u.config['playing'] = 'None' - u.dump(u.config, 'config.json', json=True) + @commands.command(name=',status', aliases=[',presence', ',game'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def status(self, ctx, *, game=None): + if game is not None: + await self.bot.change_presence(game=d.Game(name=game)) + u.config['playing'] = game + u.dump(u.config, 'config.json', json=True) + else: + await self.bot.change_presence(game=None) + u.config['playing'] = 'None' + u.dump(u.config, 'config.json', json=True) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') class Tools: - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - def format(self, i='', o=''): - if len(o) > 1: - return '>>> {}\n{}'.format(i, o) - else: - return '>>> {}'.format(i) + def format(self, i='', o=''): + if len(o) > 1: + return '>>> {}\n{}'.format(i, o) + else: + return '>>> {}'.format(i) - async def generate(self, d, i='', o=''): - return await d.send('```python\n{}```'.format(self.format(i, o))) + async def generate(self, d, i='', o=''): + return await d.send('```python\n{}```'.format(self.format(i, o))) - async def refresh(self, m, i='', o=''): + async def refresh(self, m, i='', o=''): output = m.content[9:-3] if len(re.findall('\n', output)) <= 20: - await m.edit(content='```python\n{}\n{}\n>>>```'.format(output, self.format(i, o))) - else: - await m.edit(content='```python\n{}```'.format(self.format(i, o))) + await m.edit(content='```python\n{}\n{}\n>>>```'.format(output, self.format(i, o))) + else: + await m.edit(content='```python\n{}```'.format(self.format(i, o))) - async def generate_err(self, d, o=''): - return await d.send('```\n{}```'.format(o)) + async def generate_err(self, d, o=''): + return await d.send('```\n{}```'.format(o)) - async def refresh_err(self, m, o=''): - await m.edit(content='```\n{}```'.format(o)) + async def refresh_err(self, m, o=''): + await m.edit(content='```\n{}```'.format(o)) - @commands.command(name=',console', aliases=[',con', ',c'], hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def console(self, ctx): - def execute(msg): - if msg.content == 'exit' and msg.author is ctx.author: - raise exc.Abort - elif msg.author is ctx.author and msg.channel is ctx.channel: - return True - else: - return False + @commands.command(name=',console', aliases=[',con', ',c'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def console(self, ctx): + def execute(msg): + if msg.content.startswith('exe') and msg.author is ctx.author and msg.channel is ctx.channel: + results.cancel() + return True + return False - try: - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + def evaluate(msg): + if msg.content.startswith('eval') and msg.author is ctx.author and msg.channel is ctx.channel: + results.cancel() + return True + return False + + def exit(reaction, user): + if reaction.emoji == '\N{LEFTWARDS ARROW WITH HOOK}' and user is ctx.author and reaction.message.id == ctx.message.id: + results.cancel() + raise exc.Abort + return False - console = await self.generate(ctx) - exception = await self.generate_err(ctx) - while not self.bot.is_closed(): try: - exe = await self.bot.wait_for('message', check=execute) + console = await self.generate(ctx) + exception = await self.generate_err(ctx) + + await ctx.message.add_reaction('\N{LEFTWARDS ARROW WITH HOOK}') + + while not self.bot.is_closed(): + try: + results = await asyncio.gather([self.bot.wait_for('message', check=execute), self.bot.wait_for('message', check=evaluate), self.bot.wait_for('reaction_add', check=exit)], return_exceptions=True) + print(results) + except exc.Execute: + try: + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + exec(exe.content) + + except Exception: + await self.refresh_err(exception, tb.format_exc(limit=1)) + + finally: + await self.refresh(console, exe.content, sys.stdout.getvalue() if sys.stdout.getvalue() != console.content else None) + sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ + + except exc.Evaluate: + try: + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + eval(exe.content) + + except Exception: + await self.refresh_err(exception, tb.format_exc(limit=1)) + + finally: + await self.refresh(console, exe.content, sys.stdout.getvalue() if sys.stdout.getvalue() != console.content else None) + sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ + + finally: + with suppress(d.NotFound): + await exe.delete() + except exc.Abort: - raise exc.Abort - await exe.delete() - try: - sys.stdout = io.StringIO() - sys.stderr = io.StringIO() - exec(exe.content) - except Exception: - await self.refresh_err(exception, tb.format_exc(limit=1)) + pass + finally: - await self.refresh(console, exe.content, sys.stdout.getvalue()) - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ - except exc.Abort: - await ctx.send('\N{LEFTWARDS ARROW WITH HOOK} **Exited console.**') - finally: - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ - print('Reset sys output.') + sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ + print('Reset sys output.') - @commands.command(name='arbitrary', aliases=[',arbit', ',ar']) - @commands.is_owner() - @checks.del_ctx() - async def arbitrary(self, ctx, *, exe): - try: - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - sys.stdout = io.StringIO() - exec(exe) - await self.generate(ctx, exe, sys.stdout.getvalue()) - except Exception: - await ctx.send('```\n{}```'.format(tb.format_exc(limit=1))) - tb.print_exc(limit=1) - finally: - sys.stdout = sys.__stdout__ - print('Reset stdout.') + @commands.command(name='arbitrary', aliases=[',arbit', ',ar']) + @commands.is_owner() + @checks.del_ctx() + async def arbitrary(self, ctx, *, exe): + try: + sys.stdout = io.StringIO() + exec(exe) + await self.generate(ctx, exe, sys.stdout.getvalue()) + except Exception: + await ctx.send('```\n{}```'.format(tb.format_exc(limit=1))) + finally: + sys.stdout = sys.__stdout__ + print('Reset stdout.') + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @commands.group(aliases=[',db'], hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def debug(self, ctx): - console = await self.generate(ctx) + @commands.group(aliases=[',db'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def debug(self, ctx): + console = await self.generate(ctx) - @debug.command(name='inject', aliases=['inj']) - async def _inject(self, ctx, *, input_): - pass + @debug.command(name='inject', aliases=['inj']) + async def _inject(self, ctx, *, input_): + pass - @debug.command(name='inspect', aliases=['ins']) - async def _inspect(self, ctx, *, input_): - pass + @debug.command(name='inspect', aliases=['ins']) + async def _inspect(self, ctx, *, input_): + pass From 8b0d3d5bb38289a7ef9fa215f4b3db6c83d94014 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:25:12 -0400 Subject: [PATCH 16/18] Added Execute and Evaluate exceptions to be caught in the command --- src/main/misc/exceptions.py | 60 +++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/src/main/misc/exceptions.py b/src/main/misc/exceptions.py index a782fc4..3cf4c9d 100644 --- a/src/main/misc/exceptions.py +++ b/src/main/misc/exceptions.py @@ -2,104 +2,112 @@ base = '⚠️ **An internal error has occurred.** This has been reported to my async def send_error(ctx, error): - await ctx.send('{}\n```\n{}```'.format(base, error)) + await ctx.send('{}\n```\n{}```'.format(base, error)) + + +class Execute(Exception): + pass + + +class Evaluate(Exception): + pass class Left(Exception): - pass + pass class Right(Exception): - pass + pass class Save(Exception): - pass + pass class GoTo(Exception): - pass + pass class Exists(Exception): - pass + pass class MissingArgument(Exception): - pass + pass class FavoritesNotFound(Exception): - pass + pass class PostError(Exception): - pass + pass class ImageError(Exception): - pass + pass class MatchError(Exception): - pass + pass class TagBlacklisted(Exception): - pass + pass class BoundsError(Exception): - pass + pass class TagBoundsError(Exception): - pass + pass class TagExists(Exception): - pass + pass class TagError(Exception): - pass + pass class FlagError(Exception): - pass + pass class BlacklistError(Exception): - pass + pass class NotFound(Exception): - pass + pass class Timeout(Exception): - pass + pass class InvalidVideoFile(Exception): - pass + pass class MissingAttachment(Exception): - pass + pass class TooManyAttachments(Exception): - pass + pass class CheckFail(Exception): - pass + pass class Abort(Exception): - pass + pass class Continue(Exception): - pass + pass From 3fa251114a01fe2871ddfb8444346d9f1ffcf991 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:25:40 -0400 Subject: [PATCH 17/18] Prefix command change to accommodate guild prefixes --- src/main/cogs/tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/cogs/tools.py b/src/main/cogs/tools.py index e383f1b..1657788 100644 --- a/src/main/cogs/tools.py +++ b/src/main/cogs/tools.py @@ -56,7 +56,7 @@ class Utils: @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') @checks.del_ctx() async def prefix(self, ctx): - await ctx.send('**Prefix:** `{}`'.format(u.config['prefix'])) + await ctx.send('**Prefix:** `{}`'.format('` or `'.join(u.settings['prefixes'][ctx.guild.id] if ctx.guild.id in u.settings['prefixes'] else u.config['prefix']))) await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') @commands.group(name=',send', aliases=[',s'], hidden=True) From 392679a26dba409d0afd531e8a510c5bb6e44a66 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 20 Oct 2017 16:26:13 -0400 Subject: [PATCH 18/18] Send command __ fix --- src/main/cogs/tools.py | 142 ++++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/src/main/cogs/tools.py b/src/main/cogs/tools.py index 1657788..64d3852 100644 --- a/src/main/cogs/tools.py +++ b/src/main/cogs/tools.py @@ -30,88 +30,88 @@ command_dict = {} class Utils: - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - @commands.command(name='last', aliases=['l', ','], brief='Reinvokes last command', description='Reinvokes previous command executed', hidden=True) - async def last_command(self, ctx): - global command_dict + @commands.command(name='last', aliases=['l', ','], brief='Reinvokes last command', description='Reinvokes previous command executed', hidden=True) + async def last_command(self, ctx): + global command_dict - if command_dict.get(str(ctx.author.id), {}).get('args', None) is not None: - args = command_dict.get(str(ctx.author.id), {})['args'] - print(command_dict) - await ctx.invoke(command_dict.get(str(ctx.author.id), {}).get('command', None), args) + if command_dict.get(str(ctx.author.id), {}).get('args', None) is not None: + args = command_dict.get(str(ctx.author.id), {})['args'] + print(command_dict) + await ctx.invoke(command_dict.get(str(ctx.author.id), {}).get('command', None), args) - # Displays latency - @commands.command(aliases=['p'], brief='Pong!', description='Returns latency from bot to Discord servers, not to user') - @checks.del_ctx() - async def ping(self, ctx): - global command_dict + # Displays latency + @commands.command(aliases=['p'], brief='Pong!', description='Returns latency from bot to Discord servers, not to user') + @checks.del_ctx() + async def ping(self, ctx): + global command_dict - await ctx.message.add_reaction('\N{TABLE TENNIS PADDLE AND BALL}') + await ctx.message.add_reaction('\N{TABLE TENNIS PADDLE AND BALL}') - await ctx.send(ctx.author.mention + ' \N{TABLE TENNIS PADDLE AND BALL} `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5) - command_dict.setdefault(str(ctx.author.id), {}).update({'command': ctx.command}) + await ctx.send(ctx.author.mention + ' \N{TABLE TENNIS PADDLE AND BALL} `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5) + command_dict.setdefault(str(ctx.author.id), {}).update({'command': ctx.command}) - @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') - @checks.del_ctx() - async def prefix(self, ctx): + @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') + @checks.del_ctx() + async def prefix(self, ctx): await ctx.send('**Prefix:** `{}`'.format('` or `'.join(u.settings['prefixes'][ctx.guild.id] if ctx.guild.id in u.settings['prefixes'] else u.config['prefix']))) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @commands.group(name=',send', aliases=[',s'], hidden=True) - @commands.is_owner() - @checks.del_ctx() - async def send(self, ctx): - pass + @commands.group(name=',send', aliases=[',s'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def send(self, ctx): + pass - @send.command(name='guild', aliases=['g', 'server', 's']) - async def send_guild(self, ctx, guild, channel, *, message): - await discord.utils.get(self.bot.get_all_channels(), guild__name=guild, name=channel).send(message) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @send.command(name='guild', aliases=['g', 'server', 's']) + async def send_guild(self, ctx, guild, channel, *, message): + await discord.utils.get(self.bot.get_all_channels(), guild_name=guild, name=channel).send(message) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @send.command(name='user', aliases=['u', 'member', 'm']) - async def send_user(self, ctx, user, *, message): - await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(message) - await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') + @send.command(name='user', aliases=['u', 'member', 'm']) + async def send_user(self, ctx, user, *, message): + await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(message) + await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') - @commands.command(aliases=['authenticateupload', 'authupload', 'authup', 'auth']) - async def authenticate_upload(self, ctx): - global youtube - flow = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtube.upload', - login_hint='botmyned@gmail.com', redirect_uri='urn:ietf:wg:oauth:2.0:oob') - flow.params['access_type'] = 'offline' - webbrowser.open_new_tab(flow.step1_get_authorize_url()) - credentials = flow.step2_exchange(input('Authorization code: ')) - youtube = build('youtube', 'v3', http=credentials.authorize(http.build_http())) - print('Service built.') + @commands.command(aliases=['authenticateupload', 'authupload', 'authup', 'auth']) + async def authenticate_upload(self, ctx): + global youtube + flow = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtube.upload', + login_hint='botmyned@gmail.com', redirect_uri='urn:ietf:wg:oauth:2.0:oob') + flow.params['access_type'] = 'offline' + webbrowser.open_new_tab(flow.step1_get_authorize_url()) + credentials = flow.step2_exchange(input('Authorization code: ')) + youtube = build('youtube', 'v3', http=credentials.authorize(http.build_http())) + print('Service built.') - @commands.command(aliases=['up', 'u', 'vid', 'v']) - @commands.has_permissions(administrator=True) - async def upload(self, ctx): - global youtube - attachments = ctx.message.attachments - try: - if not attachments: - raise exc.MissingAttachment - if len(attachments) > 1: - raise exc.TooManyAttachments(len(attachments)) - mime = mimetypes.guess_type(attachments[0].filename)[0] - if 'video/' in mime: - with tempfile.NamedTemporaryFile() as temp: - await attachments[0].save(temp) - else: - raise exc.InvalidVideoFile(mime) - print('https://www.youtube.com/watch?v=' + youtube.videos().insert(part='snippet', - body={'categoryId': '24', 'title': 'Test'}, media_body=http.MediaFileUpload(temp.name, chunksize=-1))) - except exc.InvalidVideoFile as e: - await ctx.send('`' + str(e) + '` **not valid video type.**', delete_after=10) - except exc.TooManyAttachments as e: - await ctx.send('`' + str(e) + '` **too many attachments.** Only one attachment is permitted to upload.', delete_after=10) - except exc.MissingAttachment: - await ctx.send('**Missing attachment.**', delete_after=10) + @commands.command(aliases=['up', 'u', 'vid', 'v']) + @commands.has_permissions(administrator=True) + async def upload(self, ctx): + global youtube + attachments = ctx.message.attachments + try: + if not attachments: + raise exc.MissingAttachment + if len(attachments) > 1: + raise exc.TooManyAttachments(len(attachments)) + mime = mimetypes.guess_type(attachments[0].filename)[0] + if 'video/' in mime: + with tempfile.NamedTemporaryFile() as temp: + await attachments[0].save(temp) + else: + raise exc.InvalidVideoFile(mime) + print('https://www.youtube.com/watch?v=' + youtube.videos().insert(part='snippet', + body={'categoryId': '24', 'title': 'Test'}, media_body=http.MediaFileUpload(temp.name, chunksize=-1))) + except exc.InvalidVideoFile as e: + await ctx.send('`' + str(e) + '` **not valid video type.**', delete_after=10) + except exc.TooManyAttachments as e: + await ctx.send('`' + str(e) + '` **too many attachments.** Only one attachment is permitted to upload.', delete_after=10) + except exc.MissingAttachment: + await ctx.send('**Missing attachment.**', delete_after=10) - @upload.error - async def upload_error(self, ctx, error): - pass + @upload.error + async def upload_error(self, ctx, error): + pass # http.