From 8e050c016ecc28b8d66472474b741891144cbc82 Mon Sep 17 00:00:00 2001 From: phxntxm Date: Sat, 30 Jul 2016 19:20:55 -0500 Subject: [PATCH] Updates to comply with PEP 8 --- bot.py | 3 +- cogs/core.py | 1 - cogs/mod.py | 65 ++++++++++++++++++++++++-------------------- cogs/overwatch.py | 9 +++--- cogs/playlist.py | 20 ++++++++------ cogs/stats.py | 56 +++++++++++++++++++------------------- cogs/tags.py | 12 +++++--- cogs/twitch.py | 16 +++++------ cogs/utils/checks.py | 27 +++--------------- 9 files changed, 100 insertions(+), 109 deletions(-) diff --git a/bot.py b/bot.py index e845748..06bd450 100644 --- a/bot.py +++ b/bot.py @@ -27,6 +27,7 @@ log.setLevel(logging.INFO) handler = logging.FileHandler(filename='bonfire.log', encoding='utf-8', mode='a') log.addHandler(handler) + # Bot event overrides @bot.event async def on_ready(): @@ -80,7 +81,7 @@ async def on_command_error(error, ctx): print('In {0.command.qualified_name}:'.format(ctx), file=f) traceback.print_tb(error.original.__traceback__, file=f) print('{0.__class__.__name__}: {0}'.format(error.original), file=f) - + if __name__ == '__main__': for e in extensions: diff --git a/cogs/core.py b/cogs/core.py index 4ab0cbc..ebf8fc8 100644 --- a/cogs/core.py +++ b/cogs/core.py @@ -102,7 +102,6 @@ class Core: fortune = subprocess.check_output(fortuneCommand.split()).decode("utf-8") await self.bot.say(fortune) - @commands.command(pass_context=True) @checks.customPermsOrRole(send_messages=True) async def roll(self, ctx, notation: str="d6"): diff --git a/cogs/mod.py b/cogs/mod.py index d1d9533..c790f63 100644 --- a/cogs/mod.py +++ b/cogs/mod.py @@ -71,13 +71,13 @@ class Mod: if server_perms is None: await self.bot.say("There are no custom permissions setup on this server yet!") return - + perms_value = server_perms.get(command) if perms_value is None: await self.bot.say("That command has no custom permissions setup on it!") else: permissions = discord.Permissions(perms_value) - needed_perm = [perm[0] for perm in permissions._perm_iterator() if perm[1]][0] + needed_perm = [perm[0] for perm in permissions if perm[1]][0] await self.bot.say("You need to have the permission `{}` " "to use the command `{}` in this server".format(needed_perm, command)) @@ -89,16 +89,16 @@ class Mod: If you want to open the command to everyone, provide 'none' as the permission""" command = " ".join(msg[0:len(msg) - 1]) permissions = msg[len(msg) - 1] - - #If a user can run the command, they have to have send_messages permissions; so use this as the base + + # If a user can run the command, they have to have send_messages permissions; so use this as the base if permissions.lower() == "none": permissions = "send_messages" - - #Convert the string to an int value of the permissions obj, based on the required permission + + # Convert the string to an int value of the permissions obj, based on the required permission perm_obj = discord.Permissions.none() - setattr(perm_obj,permissions,True) + setattr(perm_obj, permissions, True) perm_value = perm_obj.value - + cmd = None for part in msg[0:len(msg) - 1]: try: @@ -108,9 +108,10 @@ class Mod: cmd = cmd.commands.get(part) except AttributeError: break - + if cmd is None: - await self.bot.say("That command does not exist! You can't have custom permissions on a non-existant command....") + await self.bot.say( + "That command does not exist! You can't have custom permissions on a non-existant command....") return for check in cmd.checks: @@ -127,7 +128,7 @@ class Mod: server_perms = custom_perms.get(ctx.message.server.id) or {} server_perms[command] = perm_value custom_perms[ctx.message.server.id] = server_perms - + config.saveContent('custom_permissions', custom_perms) await self.bot.say("I have just added your custom permissions; " "you now need to have `{}` permissions to use the command `{}`".format(permissions, command)) @@ -149,7 +150,7 @@ class Mod: del custom_perms[ctx.message.server.id][cmd] config.saveContent('custom_permissions', custom_perms) await self.bot.say("I have just removed the custom permissions for {}!".format(cmd)) - + @commands.group(aliases=['rule'], pass_context=True, no_pm=True, invoke_without_command=True) @checks.customPermsOrRole(send_messages=True) async def rules(self, ctx): @@ -159,9 +160,9 @@ class Mod: if server_rules is None or len(server_rules) == 0: await self.bot.say("This server currently has no rules on it! I see you like to live dangerously...") return - fmt = "\n".join("{}) {}".format(num+1,rule) for num,rule in enumerate(server_rules)) + fmt = "\n".join("{}) {}".format(num + 1, rule) for num, rule in enumerate(server_rules)) await self.bot.say('```{}```'.format(fmt)) - + @rules.command(name='add', aliases=['create'], pass_context=True, no_pm=True) @checks.customPermsOrRole(manage_server=True) async def rules_add(self, ctx, *, rule: str): @@ -170,9 +171,9 @@ class Mod: server_rules = rules.get(ctx.message.server.id) or [] server_rules.append(rule) rules[ctx.message.server.id] = server_rules - config.saveContent('rules',rules) + config.saveContent('rules', rules) await self.bot.say("I have just saved your new rule, use the rules command to view this server's current rules") - + @rules.command(name='remove', aliases=['delete'], pass_context=True, no_pm=True) @checks.customPermsOrRole(manage_server=True) async def rules_delete(self, ctx, rule: int=None): @@ -182,29 +183,33 @@ class Mod: rules = config.getContent('rules') or {} server_rules = rules.get(ctx.message.server.id) if server_rules is None or len(server_rules) == 0: - await self.bot.say("This server currently has no rules on it! Can't remove something that doesn't exist bro") + await self.bot.say( + "This server currently has no rules on it! Can't remove something that doesn't exist bro") return - list_rules = "\n".join("{}) {}".format(num+1,rule) for num,rule in enumerate(server_rules)) - + list_rules = "\n".join("{}) {}".format(num + 1, rule) for num, rule in enumerate(server_rules)) + if rule is None: - await self.bot.say("Your rules are:\n```{}```Please provide the rule number you would like to remove (just the number)".format(list_rules)) - - msg = await self.bot.wait_for_message(timeout=60.0, author=ctx.message.author, channel = ctx.message.channel, check = lambda m: m.content.isdigit()) + await self.bot.say("Your rules are:\n```{}```Please provide the rule number" + "you would like to remove (just the number)".format(list_rules)) + + msg = await self.bot.wait_for_message(timeout=60.0, author=ctx.message.author, channel=ctx.message.channel, + check=lambda m: m.content.isdigit()) if msg is None: await self.bot.say("You took too long...it's just a number, seriously? Try typing a bit quicker") return - del server_rules[int(msg.content)-1] + del server_rules[int(msg.content) - 1] rules[ctx.message.server.id] = server_rules - config.saveContent('rules',rules) - + config.saveContent('rules', rules) + try: - del server_rules[rule-1] + del server_rules[rule - 1] rules[ctx.message.server.id] = server_rules - config.saveContent('rules',rules) + config.saveContent('rules', rules) await self.bot.say("I have just removed that rule from your list of rules!") except IndexError: - await self.bot.say("That is not a valid rule number, try running the command again. Your current rules are:\n```{}```".format(list_rules)) - - + await self.bot.say("That is not a valid rule number, try running the command again. " + "Your current rules are:\n```{}```".format(list_rules)) + + def setup(bot): bot.add_cog(Mod(bot)) diff --git a/cogs/overwatch.py b/cogs/overwatch.py index 80aec4c..2d48818 100644 --- a/cogs/overwatch.py +++ b/cogs/overwatch.py @@ -5,7 +5,6 @@ import discord import aiohttp import json -import re base_url = "https://owapi.net/api/v2/u/" check_g_stats = ["eliminations", "deaths", 'kpd', 'wins', 'losses', 'time_played', @@ -29,7 +28,7 @@ class Overwatch: @ow.command(name="stats", pass_context=True, no_pm=True) @checks.customPermsOrRole(send_messages=True) - async def ow_stats(self, ctx, user: discord.Member = None, hero: str = ""): + async def ow_stats(self, ctx, user: discord.Member=None, hero: str=""): """Prints out a basic overview of a member's stats Provide a hero after the member to get stats for that specific hero""" if user is None: @@ -42,7 +41,7 @@ class Overwatch: await self.bot.say("Searching profile information....") if hero == "": - with aiohttp.ClientSession(headers={"User-Agent":"Bonfire/1.0.0"}) as s: + with aiohttp.ClientSession(headers={"User-Agent": "Bonfire/1.0.0"}) as s: async with s.get(base_url + "{}/stats/general".format(bt)) as r: result = await r.text() @@ -54,7 +53,7 @@ class Overwatch: "Overwatch stats for {}: ```py\n{}```".format(user.name, fmt.title().replace("_", " "))) else: url = base_url + "{}/heroes/{}".format(bt, hero.lower().replace('-', '')) - with aiohttp.ClientSession(headers={"User-Agent":"Bonfire/1.0.0"}) as s: + with aiohttp.ClientSession(headers={"User-Agent": "Bonfire/1.0.0"}) as s: async with s.get(url) as r: if r.status == 500: fmt = "{} has not used the hero {} before!".format(user.name, hero.title()) @@ -81,7 +80,7 @@ class Overwatch: await self.bot.say("Looking up your profile information....") url = base_url + "{}/stats/general".format(bt) - with aiohttp.ClientSession(headers={"User-Agent":"Bonfire/1.0.0"}) as s: + with aiohttp.ClientSession(headers={"User-Agent": "Bonfire/1.0.0"}) as s: async with s.get(url) as r: if not r.status == 200: await self.bot.say("Profile does not exist! Battletags are picky, " diff --git a/cogs/playlist.py b/cogs/playlist.py index 564dc75..19561d8 100644 --- a/cogs/playlist.py +++ b/cogs/playlist.py @@ -5,7 +5,7 @@ from .utils import checks if not discord.opus.is_loaded(): discord.opus.load_opus('/usr/lib64/libopus.so.0') - + class VoiceEntry: def __init__(self, message, player): @@ -56,11 +56,12 @@ class VoiceState: async def audio_player_task(self): while True: - self.play_next_song.clear() + self.play_next_song.clear() self.current = await self.songs.get() await self.bot.send_message(self.current.channel, 'Now playing ' + str(self.current)) - - self.current.player = await self.voice.create_ytdl_player(self.current.player.url, ytdl_options=self.opts, after=self.toggle_next) + + self.current.player = await self.voice.create_ytdl_player(self.current.player.url, ytdl_options=self.opts, + after=self.toggle_next) self.current.player.start() await self.play_next_song.wait() @@ -69,6 +70,7 @@ class Music: """Voice related commands. Works in multiple servers at once. """ + def __init__(self, bot): self.bot = bot self.voice_states = {} @@ -143,11 +145,11 @@ class Music: success = await ctx.invoke(self.summon) if not success: return - + if state.songs.full(): await self.bot.say("The queue is currently full! You'll need to wait to add a new song") return - + player = await state.voice.create_ytdl_player(song, ytdl_options=state.opts, after=state.toggle_next) player.volume = 0.6 entry = VoiceEntry(ctx.message, player) @@ -209,7 +211,7 @@ class Music: """Prints the length of the queue""" await self.bot.say("There are a total of {} songs in the queue" .format(str(self.get_voice_state(ctx.message.server).songs.qsize()))) - + @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole(send_messages=True) async def skip(self, ctx): @@ -236,7 +238,7 @@ class Music: await self.bot.say('Skip vote added, currently at [{}/3]'.format(total_votes)) else: await self.bot.say('You have already voted to skip this song.') - + @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole(kick_members=True) async def modskip(self, ctx): @@ -245,7 +247,7 @@ class Music: if not state.is_playing(): await self.bot.say('Not playing any music right now...') return - + state.skip() await self.bot.say('Song has just been skipped.') diff --git a/cogs/stats.py b/cogs/stats.py index 1e057f0..4a44f21 100644 --- a/cogs/stats.py +++ b/cogs/stats.py @@ -2,8 +2,6 @@ from discord.ext import commands from .utils import config from .utils import checks import discord -import re -import operator class Stats: @@ -17,7 +15,6 @@ class Stats: async def mostboops(self, ctx): """Shows the person you have 'booped' the most, as well as how many times""" boops = config.getContent('boops') - members = ctx.message.server.members if not boops.get(ctx.message.author.id): await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) return @@ -36,17 +33,18 @@ class Stats: @checks.customPermsOrRole(send_messages=True) async def listboops(self, ctx): """Lists all the users you have booped and the amount of times""" - members = ctx.message.server.members boops = config.getContent('boops') or {} booped_members = boops.get(ctx.message.author.id) if booped_members is None: await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) return - + server_member_ids = [member.id for member in ctx.message.server.members] - booped_members = {m_id:amt for m_id,amt in booped_members.items() if m_id in server_member_ids} - - output = "\n".join("{0.display_name}: {1} times".format(discord.utils.get(self.bot.get_all_members(),id=m_id),amt) for m_id,amt in booped_members) + booped_members = {m_id: amt for m_id, amt in booped_members.items() if m_id in server_member_ids} + + output = "\n".join( + "{0.display_name}: {1} times".format(discord.utils.get(self.bot.get_all_members(), id=m_id), amt) for + m_id, amt in booped_members) await self.bot.say("You have booped:```{}```".format(output)) @commands.command(pass_context=True, no_pm=True) @@ -54,45 +52,47 @@ class Stats: async def leaderboard(self, ctx): """Prints a leaderboard of everyone in the server's battling record""" battles = config.getContent('battle_records') - + server_member_ids = [member.id for member in ctx.message.server.members] - server_members = {member_id:stats for member_id,stats in battles.items() if member_id in server_member_ids} - sorted_members = sorted(server_members.items(), key = lambda x: x[1]['rating'],reverse=True) - + server_members = {member_id: stats for member_id, stats in battles.items() if member_id in server_member_ids} + sorted_members = sorted(server_members.items(), key=lambda k: k[1]['rating'], reverse=True) + fmt = "" count = 1 for x in sorted_members: member_id = x[0] stats = x[1] - member = discord.utils.get(ctx.message.server.members,id=member_id) - fmt += "#{}) {} (Rating: {})\n".format(count,member.display_name,stats.get('rating')) + member = discord.utils.get(ctx.message.server.members, id=member_id) + fmt += "#{}) {} (Rating: {})\n".format(count, member.display_name, stats.get('rating')) count += 1 - await self.bot.say("You have booped:```{}```".format(fmt)) - - + await self.bot.say("Battling leaderboard for this server:```{}```".format(fmt)) + @commands.command(pass_context=True) @checks.customPermsOrRole(send_messages=True) async def stats(self, ctx, member: discord.Member=None): """Prints the battling stats for you, or the user provided""" member = member or ctx.message.author - + all_members = config.getContent('battle_records') - if not member.id in all_members: + if member.id not in all_members: await self.bot.say("That user has not battled yet!") return - + server_member_ids = [member.id for member in ctx.message.server.members] - server_members = {member_id:stats for member_id,stats in all_members.items() if member_id in server_member_ids} - sorted_server_members = sorted(server_members.items(), key = lambda x: x[1]['rating'],reverse=True) - sorted_all_members = sorted(all_members.items(), key = lambda x: x[1]['rating'],reverse=True) - - server_rank = [i for i,x in enumerate(sorted_server_members) if x[0] == member.id][0] + 1 - total_rank = [i for i,x in enumerate(sorted_all_members) if x[0] == member.id][0] + 1 + server_members = {member_id: stats for member_id, stats in all_members.items() if + member_id in server_member_ids} + sorted_server_members = sorted(server_members.items(), key=lambda x: x[1]['rating'], reverse=True) + sorted_all_members = sorted(all_members.items(), key=lambda x: x[1]['rating'], reverse=True) + + server_rank = [i for i, x in enumerate(sorted_server_members) if x[0] == member.id][0] + 1 + total_rank = [i for i, x in enumerate(sorted_all_members) if x[0] == member.id][0] + 1 rating = server_members[member.id]['rating'] - record = "{}-{}".format(server_members[member.id]['wins'],server_members[member.id]['losses']) + record = "{}-{}".format(server_members[member.id]['wins'], server_members[member.id]['losses']) fmt = 'Stats for {}:\n\tRecord: {}\n\tServer Rank: {}/{}\n\tOverall Rank: {}/{}\n\tRating: {}' - fmt = fmt.format(member.display_name,record,server_rank,len(server_members),total_rank,len(all_members),rating) + fmt = fmt.format(member.display_name, record, server_rank, len(server_members), total_rank, len(all_members), + rating) await self.bot.say('```{}```'.format(fmt)) + def setup(bot): bot.add_cog(Stats(bot)) diff --git a/cogs/tags.py b/cogs/tags.py index 7100e06..efbf5eb 100644 --- a/cogs/tags.py +++ b/cogs/tags.py @@ -2,18 +2,19 @@ from discord.ext import commands from .utils import config from .utils import checks + class Tags: """This class contains all the commands for custom tags""" def __init__(self, bot): self.bot = bot - + @commands.command(pass_context=True) @checks.customPermsOrRole(send_messages=True) async def tags(self, ctx): """Prints all the custom tags that this server currently has""" tags = config.getContent('tags') - fmt = "\n".join("{}".format(tag['tag']) for tag in tags if tag['server_id']==ctx.message.server.id) + fmt = "\n".join("{}".format(tag['tag']) for tag in tags if tag['server_id'] == ctx.message.server.id) await self.bot.say('```{}```'.format(fmt)) @commands.group(pass_context=True, invoke_without_command=True, no_pm=True) @@ -43,13 +44,15 @@ class Tags: if t['tag'] == tag and t['server_id'] == ctx.message.server.id: t['result'] = tag_result if config.saveContent('tags', tags): - await self.bot.say("I have just updated the tag `{0}`! You can call this tag by entering !tag {0}".format(tag)) + await self.bot.say( + "I have just updated the tag `{0}`! You can call this tag by entering !tag {0}".format(tag)) else: await self.bot.say("I was unable to save this data") return tags.append({'server_id': ctx.message.server.id, 'tag': tag, 'result': tag_result}) if config.saveContent('tags', tags): - await self.bot.say("I have just added the tag `{0}`! You can call this tag by entering !tag {0}".format(tag)) + await self.bot.say( + "I have just added the tag `{0}`! You can call this tag by entering !tag {0}".format(tag)) else: await self.bot.say("I was unable to save this data") @@ -72,5 +75,6 @@ class Tags: else: await self.bot.say("I was unable to save this data") + def setup(bot): bot.add_cog(Tags(bot)) diff --git a/cogs/twitch.py b/cogs/twitch.py index 648329c..0236db6 100644 --- a/cogs/twitch.py +++ b/cogs/twitch.py @@ -41,14 +41,14 @@ class Twitch: twitch[m_id]['live'] = 1 fmt = "{} has just gone live! View their stream at {}".format(member.name, url) await self.bot.send_message(server, fmt) - config.saveContent('twitch',twitch) + config.saveContent('twitch', twitch) elif live and not online: server = discord.utils.find(lambda s: s.id == r['server_id'], self.bot.servers) member = discord.utils.find(lambda m: m.id == m_id, server.members) twitch[m_id]['live'] = 0 fmt = "{} has just gone offline! Catch them next time they stream at {}".format(member.name, url) - await self.bot.send_message(server,fmt) - config.saveContent('twitch',twitch) + await self.bot.send_message(server, fmt) + config.saveContent('twitch', twitch) await asyncio.sleep(30) @commands.group(no_pm=True, invoke_without_command=True, pass_context=True) @@ -57,20 +57,20 @@ class Twitch: """Use this command to check the twitch info of a user""" if member is None: member = ctx.message.author - + twitch_channels = config.getContent('twitch') or {} result = twitch_channels.get(ctx.message.author.id) if result is None: await self.bot.say("{} has not saved their twitch URL yet!".format(member.name)) return - + url = result['twitch_url'] user = re.search("(?<=twitch.tv/)(.*)", url).group(1) with aiohttp.ClientSession() as s: async with s.get("https://api.twitch.tv/kraken/channels/{}".format(user)) as r: response = await r.text() data = json.loads(response) - + fmt = "Username: {}".format(data['display_name']) fmt += "\nStatus: {}".format(data['status']) fmt += "\nFollowers: {}".format(data['followers']) @@ -90,7 +90,7 @@ class Twitch: with aiohttp.ClientSession() as s: async with s.get(url) as r: - if not r.status == 200: + if not r.status == 200: await self.bot.say("That twitch user does not exist! " "What would be the point of adding a nonexistant twitch user? Silly") return @@ -143,7 +143,7 @@ class Twitch: twitch[ctx.message.author.id]['notifications_on'] = 1 config.saveContent('twitch', twitch) await self.bot.say("I will notify if you go live {}, you'll get a bajillion followers I promise c:".format( - ctx.message.author.mention)) + ctx.message.author.mention)) @notify.command(name='off', aliases=['stop,no'], pass_context=True, no_pm=True) @checks.customPermsOrRole(send_messages=True) diff --git a/cogs/utils/checks.py b/cogs/utils/checks.py index 445d5b1..0fc3ae2 100644 --- a/cogs/utils/checks.py +++ b/cogs/utils/checks.py @@ -7,40 +7,21 @@ def isOwner(ctx): return ctx.message.author.id == config.ownerID -def customPermsOrRole(perm): - def predicate(ctx): - if ctx.message.channel.is_private: - return False - custom_permissions = config.getContent('custom_permissions') - _perm = None - try: - _perm = custom_permissions[ctx.message.server.id][str(ctx.command)] - except KeyError: - pass - - if _perm is None: - return getattr(ctx.message.author.permissions_in(ctx.message.channel), perm) - else: - return getattr(ctx.message.author.permissions_in(ctx.message.channel), _perm) - - return commands.check(predicate) - def customPermsOrRole(**perms): def predicate(ctx): if ctx.message.channel.is_private: return False - + member_perms = ctx.message.author.permissions_in(ctx.message.channel) default_perms = discord.Permissions.none() - for perm,setting in perms.items(): - setattr(default_perms,perm,setting) - + for perm, setting in perms.items(): + setattr(default_perms, perm, setting) + try: required_perm = config.getContent('custom_permissions')[ctx.message.server.id][ctx.command.qualified_name] except KeyError: required_perm = default_perms return member_perms >= required_perm - return commands.check(predicate)