From 5e65dcbb8f0c6735fdf2ecc8a54e5d6a52736860 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 21:51:38 -0400 Subject: [PATCH 01/10] Passed CommandNotFound error, WIP dual reaction events --- src/main/run.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index 73f8620..0e4fbc3 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -60,16 +60,29 @@ async def on_ready(): @bot.event async def on_command_error(ctx, error): - print(error) - await ctx.send('{}\n```\n{}```'.format(exc.base, error)) + if not isinstance(error, commands.errors.CommandNotFound): + print(error) + await ctx.send('{}\n```\n{}```'.format(exc.base, error)) async def on_reaction_add(r, u): - print('Reacted') + pass async def on_reaction_remove(r, u): + pass + + +async def reaction_add(r, u): + 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.command(name=',test', hidden=True) From 48b17e3ab2bb0ffca04021be0d4e4f4151fd1e3c Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 21:52:03 -0400 Subject: [PATCH 02/10] Changed int() to round() to be slightly more accurate --- 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 ace1ba5..2f7f7a2 100644 --- a/src/main/cogs/tools.py +++ b/src/main/cogs/tools.py @@ -48,7 +48,7 @@ class Utils: async def ping(self, ctx): global command_dict - await ctx.send(ctx.message.author.mention + ' 🏓 `' + str(int(self.bot.latency * 1000)) + 'ms`', delete_after=5) + await ctx.send(ctx.message.author.mention + ' 🏓 `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5) command_dict.setdefault(str(ctx.message.author.id), {}).update({'command': ctx.command}) @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') From 80050b95412533730fa4b8d1764b659a00801dc3 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 21:53:44 -0400 Subject: [PATCH 03/10] Added changing game status, removed prefix for exit, cleaned try/except --- src/main/cogs/owner.py | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/src/main/cogs/owner.py b/src/main/cogs/owner.py index fddeb8b..05d186d 100644 --- a/src/main/cogs/owner.py +++ b/src/main/cogs/owner.py @@ -62,6 +62,18 @@ class Bot: async def invite(self, ctx): await ctx.send('🔗 https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(self.config['client_id'], self.config['permissions']), delete_after=10) + @commands.command(aliases=['presence', 'game'], hidden=True) + @commands.is_owner() + @checks.del_ctx() + async def status(self, ctx, game): + try: + if game is not None: + await self.bot.change_presence(game=d.Game(name=game)) + else: + raise exc.NotFound + except exc.NotFound: + await ctx.send('❌ **No game given.**', delete_after=10) + class Tools: @@ -96,8 +108,8 @@ class Tools: @checks.del_ctx() async def console(self, ctx): def execute(msg): - if msg.content == ',exit' and msg.author is ctx.message.author: - raise exc.CheckFail + if msg.content == 'exit' and msg.author is ctx.message.author: + raise exc.Abort elif msg.author is ctx.message.author and msg.channel is ctx.message.channel: return True else: @@ -107,20 +119,23 @@ class Tools: console = await self.generate(ctx) exception = await self.generate_err(ctx) while not self.bot.is_closed(): - exe = await self.bot.wait_for('message', check=execute) - await exe.delete() - sys.stdout = io.StringIO() - sys.stderr = io.StringIO() try: + exe = await self.bot.wait_for('message', check=execute) + except exc.Abort: + raise exc.Abort + finally: + await exe.delete() + try: + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() exec(exe.content) except Exception: - tb.print_exc(limit=1) - await self.refresh(console, exe.content, sys.stdout.getvalue()) - await self.refresh_err(exception, sys.stderr.getvalue()) - await ctx.send(console.content[10:-3]) - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ - except exc.CheckFail: + await self.refresh_err(exception, tb.format_exc(limit=1)) + finally: + await self.refresh(console, exe.content, sys.stdout.getvalue()) + sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ + except exc.Abort: await ctx.send('↩ī¸ **Exited console.**') finally: sys.stdout = sys.__stdout__ From 2ff61c47945dcf637de0d0ffb133a0075fcc2294 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 21:57:57 -0400 Subject: [PATCH 04/10] Fixed alias name conflict, check for no command arg, pass ValueError --- src/main/cogs/booru.py | 53 ++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/src/main/cogs/booru.py b/src/main/cogs/booru.py index 21bf6dd..59a7710 100644 --- a/src/main/cogs/booru.py +++ b/src/main/cogs/booru.py @@ -31,18 +31,29 @@ class MsG: @commands.command(aliases=['tag', 't'], brief='e621 Tag search', description='e621 | NSFW\nReturn a link search for given tags') @checks.del_ctx() async def tags(self, ctx, *tags): - await ctx.send('✅ `{}`\nhttps://e621.net/post?tags={}'.format(formatter.tostring(tags), ','.join(tags))) + try: + if tags: + await ctx.send('✅ `{}`\nhttps://e621.net/post?tags={}'.format(formatter.tostring(tags), ','.join(tags))) + else: + raise exc.TagError + except exc.TagError: + await ctx.send('❌ **No tags given.**', delete_after=10) # Tag aliases - @commands.command(aliases=['alias', 'a'], brief='e621 Tag aliases', description='e621 | NSFW\nSearch aliases for given tag') + @commands.command(name='aliases', aliases=['alias', 'a'], brief='e621 Tag aliases', description='e621 | NSFW\nSearch aliases for given tag') @checks.del_ctx() - async def aliases(self, ctx, tag): + async def tag_aliases(self, ctx, tag=None): aliases = [] - - 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 ctx.send('✅ `' + tag + '` **aliases:**\n```' + formatter.tostring(aliases) + '```') + try: + if tag is not None: + 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 ctx.send('✅ `' + tag + '` **aliases:**\n```' + formatter.tostring(aliases) + '```') + else: + raise exc.TagError + except exc.TagError: + await ctx.send('❌ **No tags given.**', delete_after=10) # 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') @@ -420,11 +431,14 @@ class MsG: # Checks for, defines, and removes limit from args for arg in args: if len(arg) == 1: - if int(arg) <= 6 and int(arg) >= 1: - limit = int(arg) - args.remove(arg) - else: - raise exc.BoundsError(arg) + try + if int(arg) <= 6 and int(arg) >= 1: + limit = int(arg) + args.remove(arg) + else: + raise exc.BoundsError(arg) + except ValueError: + pass # , previous=temp_urls.get(ctx.message.author.id, [])) posts = await self.check_return_posts(ctx=ctx, booru='e621', tags=args, limit=limit) for ident, post in posts.items(): @@ -468,11 +482,14 @@ class MsG: # Checks for, defines, and removes limit from args for arg in args: if len(arg) == 1: - if int(arg) <= 6 and int(arg) >= 1: - limit = int(arg) - args.remove(arg) - else: - raise exc.BoundsError(arg) + try: + if int(arg) <= 6 and int(arg) >= 1: + limit = int(arg) + args.remove(arg) + else: + raise exc.BoundsError(arg) + except ValueError: + pass # , previous=temp_urls.get(ctx.message.author.id, [])) posts = await self.check_return_posts(ctx=ctx, booru='e926', tags=args, limit=limit) for ident, post in posts.items(): From efd035fce512be26b4012423afe82007e321cad1 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:38:27 -0400 Subject: [PATCH 05/10] Moved config file creation and loading into utils --- src/main/utils/utils.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/utils/utils.py b/src/main/utils/utils.py index debc16a..550d7d9 100644 --- a/src/main/utils/utils.py +++ b/src/main/utils/utils.py @@ -30,8 +30,16 @@ def dump(obj, filename): tasks = setdefault('./cogs/tasks.pkl', {}) -with open('config.json') as infile: - config = json.load(infile) +try: + with open('config.json') as infile: + config = json.load(infile) + print('\"config.json\" loaded.') +except FileNotFoundError: + with open('config.json', 'w') as outfile: + json.dump({'client_id': 0, 'listed_ids': [0], 'owner_id': 0, 'permissions': 126016, 'prefix': ',', + 'shutdown_channel': 0, 'startup_channel': 0, '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.') async def clear(obj, interval=10 * 60, replace=None): From 70c863062bdf145a97b9bb411fe3f59e72bd76f7 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:38:58 -0400 Subject: [PATCH 06/10] utils.config, formatting fix --- src/main/run.py | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/src/main/run.py b/src/main/run.py index 0e4fbc3..eeaa004 100644 --- a/src/main/run.py +++ b/src/main/run.py @@ -17,31 +17,18 @@ from misc import exceptions as exc from misc import checks from utils import utils as u -try: - with open('config.json') as infile: - config = json.load(infile) - print('\"config.json\" loaded.') -except FileNotFoundError: - with open('config.json', 'w') as outfile: - json.dump({'client_id': 0, 'listed_ids': [0], 'owner_id': 0, 'permissions': 126016, 'prefix': ',', - 'shutdown_channel': 0, 'startup_channel': 0, '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.') - - logging.basicConfig(level=logging.INFO) print('PID {}'.format(os.getpid())) -bot = commands.Bot(command_prefix=config['prefix'], description='Experimental booru bot') +bot = commands.Bot(command_prefix=u.config['prefix'], description='Experimental booru bot') + # Send and print ready message to #testing and console after logon - - @bot.event async def on_ready(): bot.add_cog(tools.Utils(bot)) - bot.add_cog(owner.Bot(bot, config)) + bot.add_cog(owner.Bot(bot)) bot.add_cog(owner.Tools(bot)) bot.add_cog(management.Administration(bot)) bot.add_cog(info.Info(bot)) @@ -51,8 +38,8 @@ async def on_ready(): # bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) - if isinstance(bot.get_channel(config['startup_channel']), d.TextChannel): - await bot.get_channel(config['startup_channel']).send('**Started.** ☀ī¸') + if isinstance(bot.get_channel(u.config['startup_channel']), d.TextChannel): + await bot.get_channel(u.config['startup_channel']).send('**Started.** ☀ī¸') print('CONNECTED') print(bot.user.name) print('-------') @@ -94,4 +81,4 @@ async def test(ctx): bot.add_listener(on_reaction_add) bot.add_listener(on_reaction_remove) -bot.run(config['token']) +bot.run(u.config['token']) From ada3aac86a798ca7af5c60132028aed281f60cbe Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:39:12 -0400 Subject: [PATCH 07/10] utils.config --- src/main/misc/checks.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/misc/checks.py b/src/main/misc/checks.py index 09daf75..c782109 100644 --- a/src/main/misc/checks.py +++ b/src/main/misc/checks.py @@ -6,11 +6,10 @@ import discord from discord.ext import commands from discord.ext.commands import errors -with open('config.json') as infile: - config = json.load(infile) +from utils import utils as u -owner_id = config['owner_id'] -listed_ids = config['listed_ids'] +owner_id = u.config['owner_id'] +listed_ids = u.config['listed_ids'] def is_owner(): From e72e0ae24f76c0a50b2c266d41eef6cdc3b9b04c Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:39:48 -0400 Subject: [PATCH 08/10] Converting string concatenation to .format --- src/main/cogs/owner.py | 13 ++++++------- src/main/cogs/tools.py | 18 ++++++++---------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/main/cogs/owner.py b/src/main/cogs/owner.py index 05d186d..fa9de64 100644 --- a/src/main/cogs/owner.py +++ b/src/main/cogs/owner.py @@ -19,17 +19,16 @@ nl = re.compile('\n') class Bot: - def __init__(self, bot, config): + def __init__(self, bot): self.bot = bot - self.config = config # 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): - if isinstance(self.bot.get_channel(self.config['startup_channel']), d.TextChannel): - await self.bot.get_channel(self.config['shutdown_channel']).send('**Shutting down...** 🌙') + if isinstance(self.bot.get_channel(u.config['startup_channel']), d.TextChannel): + await self.bot.get_channel(u.config['shutdown_channel']).send('**Shutting down...** 🌙') # loop = self.bot.loop.all_tasks() # for task in loop: # task.cancel() @@ -45,8 +44,8 @@ class Bot: async def restart(self, ctx): print('RESTARTING') print('-------') - if isinstance(self.bot.get_channel(self.config['startup_channel']), d.TextChannel): - await self.bot.get_channel(self.config['shutdown_channel']).send('**Restarting...** 💤') + if isinstance(self.bot.get_channel(u.config['startup_channel']), d.TextChannel): + await self.bot.get_channel(u.config['shutdown_channel']).send('**Restarting...** 💤') # loop = self.bot.loop.all_tasks() # for task in loop: # task.cancel() @@ -60,7 +59,7 @@ class Bot: @commands.is_owner() @checks.del_ctx() async def invite(self, ctx): - await ctx.send('🔗 https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(self.config['client_id'], self.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(aliases=['presence', 'game'], hidden=True) @commands.is_owner() diff --git a/src/main/cogs/tools.py b/src/main/cogs/tools.py index 2f7f7a2..19c8c74 100644 --- a/src/main/cogs/tools.py +++ b/src/main/cogs/tools.py @@ -35,21 +35,19 @@ class Utils: @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.message.author.id), {}).get('args', None) is not None: args = command_dict.get(str(ctx.message.author.id), {})['args'] print(command_dict) + await ctx.invoke(command_dict.get(str(ctx.message.author.id), {}).get('command', None), args) # [prefix]ping -> Pong! @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 + user = ctx.message.author - await ctx.send(ctx.message.author.mention + ' 🏓 `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5) - command_dict.setdefault(str(ctx.message.author.id), {}).update({'command': ctx.command}) + await ctx.send('{} 🏓 `{}ms`'.format(round(self.bot.latency * 1000)), delete_after=5) @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') @checks.del_ctx() @@ -70,7 +68,7 @@ class Utils: async def send_user(self, ctx, user, *message): await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(formatter.tostring(message)) - @commands.command(aliases=['authenticateupload', 'authupload', 'authup', 'auth']) + @commands.command(aliases=['authupload', 'auth']) async def authenticate_upload(self, ctx): global youtube flow = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtube.upload', @@ -97,12 +95,12 @@ class Utils: 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))) + print('https://www.youtube.com/watch?v={}'.format(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) + await ctx.send('❌ `{}` **not valid video type.**'.format(e), 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) + await ctx.send('❌ `{}` **too many attachments.** Only one attachment is permitted to upload.'.format(e), delete_after=10) except exc.MissingAttachment: await ctx.send('❌ **Missing attachment.**', delete_after=10) From f0f0850c0e4ad5f6ab768d42f707bc68ead0c4f0 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:40:38 -0400 Subject: [PATCH 09/10] Changed tag command to search related tags, .format(), formatting, ctx --- src/main/cogs/booru.py | 301 +++++++++++++++++++++++++---------------- 1 file changed, 181 insertions(+), 120 deletions(-) diff --git a/src/main/cogs/booru.py b/src/main/cogs/booru.py index 59a7710..5a7d506 100644 --- a/src/main/cogs/booru.py +++ b/src/main/cogs/booru.py @@ -14,8 +14,6 @@ from misc import checks from utils import utils as u from utils import formatter, scraper -# temp_urls = {} - class MsG: @@ -30,30 +28,38 @@ class MsG: # Tag search @commands.command(aliases=['tag', 't'], brief='e621 Tag search', description='e621 | NSFW\nReturn a link search for given tags') @checks.del_ctx() - async def tags(self, ctx, *tags): - try: - if tags: - await ctx.send('✅ `{}`\nhttps://e621.net/post?tags={}'.format(formatter.tostring(tags), ','.join(tags))) - else: - raise exc.TagError - except exc.TagError: - await ctx.send('❌ **No tags given.**', delete_after=10) + async def tags(self, ctx, tag): + tags = [] + + await ctx.trigger_typing() + tag_request = await u.fetch('https://e621.net/tag/related.json', params={'tags': tag, 'type': 'general'}, json=True) + for tag in tag_request.get('wolf', []): + tags.append(tag[0]) + + await ctx.send('✅ ``{}` **tags:**\n```\n{}```'.format(tag, formatter.tostring(tags))) + + @tags.error + async def tags_error(self, ctx, error): + if isinstance(error, errext.MissingRequiredArgument): + return await ctx.send('❌ **No tags given.**', delete_after=10) # Tag aliases @commands.command(name='aliases', aliases=['alias', 'a'], brief='e621 Tag aliases', description='e621 | NSFW\nSearch aliases for given tag') @checks.del_ctx() - async def tag_aliases(self, ctx, tag=None): + async def tag_aliases(self, ctx, tag): aliases = [] - try: - if tag is not None: - 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 ctx.send('✅ `' + tag + '` **aliases:**\n```' + formatter.tostring(aliases) + '```') - else: - raise exc.TagError - except exc.TagError: - await ctx.send('❌ **No tags given.**', delete_after=10) + + await ctx.trigger_typing() + 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 ctx.send('✅ `{}` **aliases:**\n```\n{}```'.format(tag, formatter.tostring(aliases))) + + @tag_aliases.error + async def tag_aliases_error(self, ctx, error): + if isinstance(error, errext.MissingRequiredArgument): + return await ctx.send('❌ **No tags given.**', delete_after=10) # 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') @@ -61,16 +67,25 @@ class MsG: async def reverse_image_search(self, ctx, url): try: await ctx.trigger_typing() - await ctx.send('✅ ' + ctx.message.author.mention + ' **Probable match:**\n' + await scraper.check_match(url)) + await ctx.send('✅ **Probable match:**\n{}'.format(await scraper.check_match(url))) + except exc.MatchError: - await ctx.send('❌ ' + ctx.message.author.mention + ' **No probable match.**', delete_after=10) + await ctx.send('❌ **No probable match.**', delete_after=10) + + @reverse_image_search.error + async def reverse_image_search_error(self, ctx, error): + if isinstance(error, errext.MissingRequiredArgument): + return await ctx.send('❌ **Invalid url.**', delete_after=10) async def return_pool(self, *, ctx, booru='e621', query=[]): + channel = ctx.message.channel + user = ctx.message.author + def on_message(msg): - if msg.content.lower() == 'cancel' and msg.author is ctx.message.author and msg.channel is ctx.message.channel: + if msg.content.lower() == 'cancel' and msg.author is user and msg.channel is channel: raise exc.Abort try: - if int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is ctx.message.author and msg.channel is ctx.message.channel: + if int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is user and msg.channel is channel: return True except ValueError: pass @@ -115,36 +130,39 @@ class MsG: @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, *kwords): + channel = ctx.message.channel + user = ctx.message.author + def on_react(reaction, user): - if reaction.emoji == 'đŸšĢ' and reaction.message.content == paginator.content and user is ctx.message.author: + if reaction.emoji == 'đŸšĢ' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Abort - elif reaction.emoji == '📁' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == '📁' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Save - elif reaction.emoji == 'âŦ…' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == 'âŦ…' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Left - elif reaction.emoji == 'đŸ”ĸ' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == 'đŸ”ĸ' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.GoTo - elif reaction.emoji == '➡' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == '➡' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Right else: return False def on_message(msg): try: - if int(msg.content) <= len(posts) and msg.author is ctx.message.author and msg.channel is ctx.message.channel: + if int(msg.content) <= len(posts) and msg.author is user and msg.channel is channel: return True + except ValueError: pass + else: return False - user = ctx.message.author starred = [] c = 1 try: await ctx.trigger_typing() - pool, posts = await self.return_pool(ctx=ctx, booru='e621', query=kwords) keys = list(posts.keys()) values = list(posts.values()) @@ -218,15 +236,19 @@ class MsG: await paginator.edit(content='đŸšĢ **Exited paginator.**') except UnboundLocalError: await ctx.send('đŸšĢ **Exited paginator.**') + except asyncio.TimeoutError: try: await ctx.send(content='❌ **Paginator timed out.**') except UnboundLocalError: await ctx.send('❌ **Paginator timed out.**') + except exc.NotFound: await ctx.send('❌ **Pool not found.**', delete_after=10) + except exc.Timeout: await ctx.send('❌ **Request timed out.**') + finally: for url in starred: await user.send(url) @@ -287,30 +309,34 @@ class MsG: @checks.del_ctx() @checks.is_nsfw() async def e621_paginator(self, ctx, *args): + channel = ctx.message.channel + user = ctx.message.author + def on_react(reaction, user): - if reaction.emoji == 'đŸšĢ' and reaction.message.content == paginator.content and user is ctx.message.author: + if reaction.emoji == 'đŸšĢ' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Abort - elif reaction.emoji == '📁' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == '📁' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Save - elif reaction.emoji == 'âŦ…' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == 'âŦ…' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Left - elif reaction.emoji == 'đŸ”ĸ' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == 'đŸ”ĸ' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.GoTo - elif reaction.emoji == '➡' and reaction.message.content == paginator.content and user is ctx.message.author: + elif reaction.emoji == '➡' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']): raise exc.Right else: return False def on_message(msg): try: - if int(msg.content) <= len(posts) and msg.author is ctx.message.author and msg.channel is ctx.message.channel: + if int(msg.content) <= len(posts) and msg.author is user and msg.channel is channel: return True + except ValueError: pass + else: return False - user = ctx.message.author args = list(args) limit = self.LIMIT / 5 starred = [] @@ -318,7 +344,6 @@ class MsG: try: await ctx.trigger_typing() - posts = await self.check_return_posts(ctx=ctx, booru='e621', tags=args, limit=limit) keys = list(posts.keys()) values = list(posts.values()) @@ -380,8 +405,10 @@ class MsG: await ctx.trigger_typing() try: posts.update(await self.check_return_posts(ctx=ctx, booru='e621', tags=args, limit=limit, previous=posts)) + except exc.NotFound: await paginator.edit(content='❌ **No more images found.**') + keys = list(posts.keys()) values = list(posts.values()) @@ -395,16 +422,22 @@ class MsG: except exc.Abort: await paginator.edit(content='đŸšĢ **Exited paginator.**') + except asyncio.TimeoutError: await paginator.edit(content='❌ **Paginator timed out.**') + except exc.NotFound as e: await ctx.send('❌ `{}` **not found.**'.format(e), delete_after=10) + except exc.TagBlacklisted as e: await ctx.send('❌ `{}` **blacklisted.**'.format(e), delete_after=10) + except exc.TagBoundsError as e: await ctx.send('❌ `{}` **out of bounds.** Tags limited to 5, currently.'.format(e), delete_after=10) + except exc.Timeout: await ctx.send('❌ **Request timed out.**') + finally: for url in starred: await user.send(url) @@ -414,66 +447,13 @@ class MsG: @e621_paginator.error async def e621_paginator_error(self, ctx, error): if isinstance(error, errext.CheckFailure): - return await ctx.send('❌ <#' + str(ctx.message.channel.mention) + '> **is not an NSFW channel.**', delete_after=10) + return await ctx.send('❌ {} **is not an NSFW channel.**'.format(ctx.message.channel.mention), delete_after=10) # Searches for and returns images from e621.net given tags when not blacklisted @commands.command(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): - # global temp_urls - - args = list(args) - limit = 1 - - try: - await ctx.trigger_typing() - # Checks for, defines, and removes limit from args - for arg in args: - if len(arg) == 1: - try - if int(arg) <= 6 and int(arg) >= 1: - limit = int(arg) - args.remove(arg) - else: - raise exc.BoundsError(arg) - except ValueError: - pass - # , previous=temp_urls.get(ctx.message.author.id, [])) - posts = await self.check_return_posts(ctx=ctx, booru='e621', tags=args, 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).set_image(url=post['url']) - embed.set_author(name=formatter.tostring(args, random=True), - url='https://e621.net/post?tags={}'.format(','.join(args)), icon_url=ctx.message.author.avatar_url) - embed.set_footer( - text=str(ident), icon_url='http://ndl.mgccw.com/mu3/app/20141013/18/1413204353554/icon/icon_xl.png') - await ctx.send(embed=embed) - # temp_urls.setdefault(ctx.message.author.id, []).extend(posts.keys()) - except exc.TagBlacklisted as e: - await ctx.send('❌ `' + str(e) + '` **blacklisted.**', delete_after=10) - except exc.BoundsError as e: - await ctx.send('❌ `' + str(e) + '` **out of bounds.**', delete_after=10) - except exc.TagBoundsError as e: - await ctx.send('❌ `' + str(e) + '` **out of bounds.** Tags limited to 5, currently.', delete_after=10) - except exc.NotFound as e: - await ctx.send('❌ `' + str(e) + '` **not found.**', delete_after=10) - except exc.Timeout: - await ctx.send('❌ **Request timed out.**') - tools.command_dict.setdefault(str(ctx.message.author.id), {}).update( - {'command': ctx.command, 'args': ctx.args}) - - @e621.error - async def e621_error(self, ctx, error): - if isinstance(error, errext.CheckFailure): - return await ctx.send('❌ <#' + str(ctx.message.channel.mention) + '> **is not an NSFW channel.**', delete_after=10) - - # 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): - # global temp_urls - args = list(args) limit = 1 @@ -488,27 +468,85 @@ class MsG: args.remove(arg) else: raise exc.BoundsError(arg) + + except ValueError: + pass + posts = await self.check_return_posts(ctx=ctx, booru='e621', tags=args, 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).set_image(url=post['url']) + embed.set_author(name=formatter.tostring(args, random=True), + url='https://e621.net/post?tags={}'.format(','.join(args)), icon_url=user.avatar_url) + embed.set_footer( + text=str(ident), icon_url='http://ndl.mgccw.com/mu3/app/20141013/18/1413204353554/icon/icon_xl.png') + await ctx.send(embed=embed) + + except exc.TagBlacklisted as e: + await ctx.send('❌ `{}` **blacklisted.**'.format(e), delete_after=10) + + except exc.BoundsError as e: + await ctx.send('❌ `{}` **out of bounds.**'.format(e), delete_after=10) + + except exc.TagBoundsError as e: + await ctx.send('❌ `{}` **out of bounds.** Tags limited to 5, currently.'.format(e), delete_after=10) + + except exc.NotFound as e: + await ctx.send('❌ `{}` **not found.**'.format(e), delete_after=10) + + except exc.Timeout: + await ctx.send('❌ **Request timed out.**') + + tools.command_dict.setdefault(str(user.id), {}).update( + {'command': ctx.command, 'args': ctx.args}) + + @e621.error + async def e621_error(self, ctx, error): + if isinstance(error, errext.CheckFailure): + return await ctx.send('❌ {} **is not an NSFW channel.**'.format(ctx.message.channel.mention), delete_after=10) + + # 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): + args = list(args) + limit = 1 + + try: + await ctx.trigger_typing() + # Checks for, defines, and removes limit from args + for arg in args: + if len(arg) == 1: + try: + if int(arg) <= 6 and int(arg) >= 1: + limit = int(arg) + args.remove(arg) + else: + raise exc.BoundsError(arg) + except ValueError: pass - # , previous=temp_urls.get(ctx.message.author.id, [])) posts = await self.check_return_posts(ctx=ctx, booru='e926', tags=args, 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).set_image(url=post['url']) embed.set_author(name=formatter.tostring(args, random=True), - url='https://e621.net/post?tags={}'.format(','.join(args)), icon_url=ctx.message.author.avatar_url) + url='https://e621.net/post?tags={}'.format(','.join(args)), icon_url=user.avatar_url) embed.set_footer( text=str(ident), icon_url='http://ndl.mgccw.com/mu3/app/20141013/18/1413204353554/icon/icon_xl.png') await ctx.send(embed=embed) - # temp_urls.setdefault(ctx.message.author.id, []).extend(posts.values()) + except exc.TagBlacklisted as e: - await ctx.send('❌ `' + str(e) + '` **blacklisted.**', delete_after=10) + await ctx.send('❌ `{}` **blacklisted.**'.format(e), delete_after=10) + except exc.BoundsError as e: - await ctx.send('❌ `' + str(e) + '` **out of bounds.**', delete_after=10) + await ctx.send('❌ `{}` **out of bounds.**'.format(e), delete_after=10) + except exc.TagBoundsError as e: - await ctx.send('❌ `' + str(e) + '` **out of bounds.** Tags limited to 5, currently.', delete_after=10) + await ctx.send('❌ `{}` **out of bounds.** Tags limited to 5, currently.'.format(e), delete_after=10) + except exc.NotFound as e: - await ctx.send('❌ `' + str(e) + '` **not found.**', delete_after=10) + await ctx.send('❌ `{}` **not found.**'.format(e), delete_after=10) + except exc.Timeout: await ctx.send('❌ **Request timed out.**') @@ -517,14 +555,14 @@ class MsG: @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* `' + ctx.prefix + 'help bl` *for more info.*', delete_after=10) + await ctx.send('❌ **Use a flag to manage blacklists.**\n*Type* `{}help bl` *for more info.*'.format(ctx.prefix), delete_after=10) @blacklist.error async def blacklist_error(self, ctx, error): if isinstance(error, commands.CheckFailure): return await ctx.send('❌ **Insufficient permissions.**') - if isinstance(error, KeyError): - return await ctx.send('❌ **Blacklist does not exist.**', delete_after=10) + # 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): @@ -533,26 +571,29 @@ class MsG: @_get_blacklist.command(name='global', aliases=['gl', 'g']) async def __get_global_blacklist(self, ctx): - await ctx.send('đŸšĢ **Global blacklist:**\n```\n' + formatter.tostring(self.blacklists['global_blacklist']) + '```') + await ctx.send('đŸšĢ **Global blacklist:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']))) @_get_blacklist.command(name='channel', aliases=['ch', 'c']) async def __get_channel_blacklist(self, ctx): guild = ctx.message.guild if isinstance( ctx.message.guild, d.Guild) else ctx.message.channel channel = ctx.message.channel - await ctx.send('đŸšĢ ' + channel.mention + ' **blacklist:**\n```\n' + formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set())) + '```') + + await ctx.send('đŸšĢ {} **blacklist:**\n```\n{}```'.format(channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set())))) @_get_blacklist.command(name='me', aliases=['m']) async def __get_user_blacklist(self, ctx): user = ctx.message.author - await ctx.send('đŸšĢ ' + user.mention + '**\'s blacklist:**\n```\n' + formatter.tostring(self.blacklists['user_blacklist'].get(user.id, set())) + '```', delete_after=10) + + await ctx.send('đŸšĢ {}**\'s blacklist:**\n```\n{}```'.format(user.mention, formatter.tostring(self.blacklists['user_blacklist'].get(user.id, set()))), delete_after=10) @_get_blacklist.command(name='here', aliases=['h']) async def __get_here_blacklists(self, ctx): guild = ctx.message.guild if isinstance( ctx.message.guild, d.Guild) else ctx.message.channel channel = ctx.message.channel - await ctx.send('đŸšĢ **__Blacklisted:__**\n\n**Global:**\n```\n' + formatter.tostring(self.blacklists['global_blacklist']) + '```\n**' + channel.mention + ':**\n```\n' + formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set())) + '```') + + await ctx.send('đŸšĢ **__Blacklisted:__**\n\n**Global:**\n```\n{}```\n**{}:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']), channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set())))) @_get_blacklist.group(name='all', aliases=['a']) async def __get_all_blacklists(self, ctx): @@ -564,12 +605,13 @@ class MsG: async def ___get_all_guild_blacklists(self, ctx): guild = ctx.message.guild if isinstance( ctx.message.guild, d.Guild) else ctx.message.channel - await ctx.send('đŸšĢ **__' + guild.name + ' blacklists:__**\n\n' + formatter.dict_tostring(self.blacklists['guild_blacklist'].get(guild.id, {}))) + + await ctx.send('đŸšĢ **__{} blacklists:__**\n\n{}'.format(guild.name, formatter.dict_tostring(self.blacklists['guild_blacklist'].get(guild.id, {})))) @__get_all_blacklists.command(name='user', aliases=['u', 'member', 'm']) @commands.is_owner() async def ___get_all_user_blacklists(self, ctx): - await ctx.send('đŸšĢ **__User blacklists:__**\n\n' + formatter.dict_tostring(self.blacklists['user_blacklist'])) + await ctx.send('đŸšĢ **__User blacklists:__**\n\n{}'.format(formatter.dict_tostring(self.blacklists['user_blacklist']))) @blacklist.group(name='add', aliases=['a']) async def _add_tags(self, ctx): @@ -587,7 +629,8 @@ class MsG: self.aliases.setdefault(tag, set()).add(dic['name']) u.dump(self.blacklists, './cogs/blacklists.pkl') u.dump(self.aliases, './cogs/aliases.pkl') - await ctx.send('✅ **Added to global blacklist:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + + await ctx.send('✅ **Added to global blacklist:**\n```\n{}```'.format(formatter.tostring(tags)), delete_after=5) @_add_tags.command(name='channel', aliases=['ch', 'c']) @commands.has_permissions(manage_channels=True) @@ -605,7 +648,8 @@ class MsG: self.aliases.setdefault(tag, set()).add(dic['name']) u.dump(self.blacklists, './cogs/blacklists.pkl') u.dump(self.aliases, './cogs/aliases.pkl') - await ctx.send('✅ **Added to** ' + channel.mention + ' **blacklist:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + + await ctx.send('✅ **Added to** {} **blacklist:**\n```\n{}```'.format(channel.mention, formatter.tostring(tags)), delete_after=5) @_add_tags.command(name='me', aliases=['m']) async def __add_user_tags(self, ctx, *tags): @@ -619,7 +663,8 @@ class MsG: self.aliases.setdefault(tag, set()).add(dic['name']) u.dump(self.blacklists, './cogs/blacklists.pkl') u.dump(self.aliases, './cogs/aliases.pkl') - await ctx.send('✅ ' + user.mention + ' **added:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + + await ctx.send('✅ {} **added:**\n```\n{}```'.format(user.mention, formatter.tostring(tags)), delete_after=5) @blacklist.group(name='remove', aliases=['rm', 'r']) async def _remove_tags(self, ctx): @@ -633,12 +678,15 @@ class MsG: for tag in tags: try: self.blacklists['global_blacklist'].remove(tag) + except KeyError: raise exc.TagError(tag) u.dump(self.blacklists, './cogs/blacklists.pkl') + await ctx.send('✅ **Removed from global blacklist:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + except exc.TagError as e: - await ctx.send('❌ `' + str(e) + '` **not in blacklist.**', delete_after=10) + await ctx.send('❌ `{}` **not in blacklist.**'.format(e), delete_after=10) @_remove_tags.command(name='channel', aliases=['ch', 'c']) @commands.has_permissions(manage_channels=True) @@ -646,30 +694,38 @@ class MsG: guild = ctx.message.guild if isinstance( ctx.message.guild, d.Guild) else ctx.message.channel channel = ctx.message.channel + try: for tag in tags: try: self.blacklists['guild_blacklist'][guild.id][channel.id].remove(tag) + except KeyError: raise exc.TagError(tag) u.dump(self.blacklists, './cogs/blacklists.pkl') + await ctx.send('✅ **Removed from** ' + channel.mention + ' **blacklist:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + except exc.TagError as e: - await ctx.send('❌ `' + str(e) + '` **not in blacklist.**', delete_after=10) + await ctx.send('❌ `{}` **not in blacklist.**'.format(e), delete_after=10) @_remove_tags.command(name='me', aliases=['m']) async def __remove_user_tags(self, ctx, *tags): user = ctx.message.author + try: for tag in tags: try: self.blacklists['user_blacklist'][user.id].remove(tag) + except KeyError: raise exc.TagError(tag) u.dump(self.blacklists, './cogs/blacklists.pkl') - await ctx.send('✅ ' + user.mention + ' **removed:**\n```\n' + formatter.tostring(tags) + '```', delete_after=5) + + await ctx.send('✅ {} **removed:**\n```\n{}```'.format(user.mention, formatter.tostring(tags)), delete_after=5) + except exc.TagError as e: - await ctx.send('❌ `' + str(e) + '` **not in blacklist.**', delete_after=10) + await ctx.send('❌ `{}` **not in blacklist.**'.format(e), delete_after=10) @blacklist.group(name='clear', aliases=['cl', 'c']) async def _clear_blacklist(self, ctx): @@ -681,6 +737,7 @@ class MsG: async def __clear_global_blacklist(self, ctx): del self.blacklists['global_blacklist'] u.dump(self.blacklists, './cogs/blacklists.pkl') + await ctx.send('✅ **Global blacklist cleared.**', delete_after=5) @_clear_blacklist.command(name='channel', aliases=['ch', 'c']) @@ -689,13 +746,17 @@ class MsG: guild = ctx.message.guild if isinstance( ctx.message.guild, d.Guild) else ctx.message.channel channel = ctx.message.channel + del self.blacklists['guild_blacklist'][str(guild.id)][channel.id] u.dump(self.blacklists, './cogs/blacklists.pkl') - await ctx.send('✅ <#' + channel.mention + '> **blacklist cleared.**', delete_after=5) + + await ctx.send('✅ {} **blacklist cleared.**'.format(channel.mention), delete_after=5) @_clear_blacklist.command(name='me', aliases=['m']) async def __clear_user_blacklist(self, ctx): user = ctx.message.author + del self.blacklists['user_blacklist'][user.id] u.dump(self.blacklists, './cogs/blacklists.pkl') - await ctx.send('✅ ' + user.mention + '**\'s blacklist cleared.**', delete_after=5) + + await ctx.send('✅ {}**\'s blacklist cleared.**'.format(user.mention), delete_after=5) From 81d8a31ea65c9145b79ca708781b0eec1dd36578 Mon Sep 17 00:00:00 2001 From: Myned Date: Fri, 13 Oct 2017 23:41:32 -0400 Subject: [PATCH 10/10] Converted to .format() --- src/main/cogs/owner.py | 13 +++++++------ src/main/cogs/tools.py | 18 ++++++++++-------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/main/cogs/owner.py b/src/main/cogs/owner.py index fa9de64..05d186d 100644 --- a/src/main/cogs/owner.py +++ b/src/main/cogs/owner.py @@ -19,16 +19,17 @@ nl = re.compile('\n') class Bot: - def __init__(self, bot): + def __init__(self, bot, config): self.bot = bot + self.config = config # 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): - if isinstance(self.bot.get_channel(u.config['startup_channel']), d.TextChannel): - await self.bot.get_channel(u.config['shutdown_channel']).send('**Shutting down...** 🌙') + if isinstance(self.bot.get_channel(self.config['startup_channel']), d.TextChannel): + await self.bot.get_channel(self.config['shutdown_channel']).send('**Shutting down...** 🌙') # loop = self.bot.loop.all_tasks() # for task in loop: # task.cancel() @@ -44,8 +45,8 @@ class Bot: async def restart(self, ctx): print('RESTARTING') print('-------') - if isinstance(self.bot.get_channel(u.config['startup_channel']), d.TextChannel): - await self.bot.get_channel(u.config['shutdown_channel']).send('**Restarting...** 💤') + if isinstance(self.bot.get_channel(self.config['startup_channel']), d.TextChannel): + await self.bot.get_channel(self.config['shutdown_channel']).send('**Restarting...** 💤') # loop = self.bot.loop.all_tasks() # for task in loop: # task.cancel() @@ -59,7 +60,7 @@ class Bot: @commands.is_owner() @checks.del_ctx() async def invite(self, ctx): - 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(self.config['client_id'], self.config['permissions']), delete_after=10) @commands.command(aliases=['presence', 'game'], hidden=True) @commands.is_owner() diff --git a/src/main/cogs/tools.py b/src/main/cogs/tools.py index 19c8c74..2f7f7a2 100644 --- a/src/main/cogs/tools.py +++ b/src/main/cogs/tools.py @@ -35,19 +35,21 @@ class Utils: @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.message.author.id), {}).get('args', None) is not None: args = command_dict.get(str(ctx.message.author.id), {})['args'] print(command_dict) - await ctx.invoke(command_dict.get(str(ctx.message.author.id), {}).get('command', None), args) # [prefix]ping -> Pong! @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): - user = ctx.message.author + global command_dict - await ctx.send('{} 🏓 `{}ms`'.format(round(self.bot.latency * 1000)), delete_after=5) + await ctx.send(ctx.message.author.mention + ' 🏓 `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5) + command_dict.setdefault(str(ctx.message.author.id), {}).update({'command': ctx.command}) @commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes') @checks.del_ctx() @@ -68,7 +70,7 @@ class Utils: async def send_user(self, ctx, user, *message): await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(formatter.tostring(message)) - @commands.command(aliases=['authupload', 'auth']) + @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', @@ -95,12 +97,12 @@ class Utils: await attachments[0].save(temp) else: raise exc.InvalidVideoFile(mime) - print('https://www.youtube.com/watch?v={}'.format(youtube.videos().insert(part='snippet', - body={'categoryId': '24', 'title': 'Test'}, media_body=http.MediaFileUpload(temp.name, chunksize=-1)))) + 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('❌ `{}` **not valid video type.**'.format(e), delete_after=10) + await ctx.send('❌ `' + str(e) + '` **not valid video type.**', delete_after=10) except exc.TooManyAttachments as e: - await ctx.send('❌ `{}` **too many attachments.** Only one attachment is permitted to upload.'.format(e), delete_after=10) + 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)