From a9267f106e220a719f50e6692e13ffe71116450a Mon Sep 17 00:00:00 2001 From: phxntxm Date: Sun, 17 Jul 2016 16:10:12 -0500 Subject: [PATCH] Git rid of useless references, and updated for pep8 --- bot.py | 18 +++++++++--------- cogs/core.py | 25 +++++++++++++------------ cogs/interaction.py | 15 ++++++++------- cogs/mod.py | 41 ++++++++++++++++++++--------------------- cogs/overwatch.py | 24 ++++++++++++++---------- cogs/owner.py | 15 ++++++++------- cogs/stats.py | 12 ++++++------ cogs/twitch.py | 19 ++++++++++--------- cogs/utils/config.py | 13 ------------- 9 files changed, 88 insertions(+), 94 deletions(-) diff --git a/bot.py b/bot.py index 200780e..b9aa8ab 100644 --- a/bot.py +++ b/bot.py @@ -1,8 +1,6 @@ #!/usr/local/bin/python3.5 import discord -import traceback -import sys from discord.ext import commands from cogs.utils import config @@ -27,7 +25,7 @@ async def on_ready(): if channel_id != 0: destination = discord.utils.find(lambda m: m.id == channel_id, bot.get_all_channels()) await bot.send_message(destination, "I have just finished restarting!") - config.saveContent('restart_server',0) + config.saveContent('restart_server', 0) @bot.event @@ -44,7 +42,8 @@ async def on_member_join(member): @bot.event async def on_member_remove(member): - await bot.send_message(member.server, "{0} has left the server, I hope it wasn't because of something I said :c".format(member)) + await bot.send_message(member.server, + "{0} has left the server, I hope it wasn't because of something I said :c".format(member)) @bot.event @@ -58,15 +57,16 @@ async def on_command_error(error, ctx): elif isinstance(error, commands.CheckFailure): fmt = "You can't tell me what to do!" await bot.send_message(ctx.message.channel, fmt) - #elif isinstance(error, commands.CommandInvokeError): - #f = open("/home/phxntx5/public_html/Bonfire/error_log", 'w') - #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) + # elif isinstance(error, commands.CommandInvokeError): + # f = open("/home/phxntx5/public_html/Bonfire/error_log", 'w') + # 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) else: fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' await bot.send_message(ctx.message.channel, fmt.format(type(error).__name__, error)) + if __name__ == '__main__': for e in extensions: bot.load_extension(e) diff --git a/cogs/core.py b/cogs/core.py index b6e9943..e2cc337 100644 --- a/cogs/core.py +++ b/cogs/core.py @@ -34,16 +34,16 @@ class Core: perms.attach_files = True await self.bot.say("Use this URL to add me to a server that you'd like!\n{}" .format(discord.utils.oauth_url('183748889814237186', perms))) - + @commands.command(pass_context=True) @checks.customPermsOrRole("none") async def doggo(self, ctx): """Use this to print a random doggo image. Doggo is love, doggo is life.""" os.chdir('/home/phxntx5/public_html/Bonfire/images') - f = glob.glob('doggo*')[random.randint(0,len(glob.glob('doggo*'))-1)] + f = glob.glob('doggo*')[random.randint(0, len(glob.glob('doggo*')) - 1)] f = open(f, 'rb') - await self.bot.send_file(ctx.message.channel,f) + await self.bot.send_file(ctx.message.channel, f) f.close() @commands.command() @@ -79,16 +79,16 @@ class Core: url = 'https://derpibooru.org/search.json?q=' query = '+'.join(search) url += query - + nsfw_channels = config.getContent("nsfw_channels") if ctx.message.channel.id in nsfw_channels: url += ",+explicit&filter_id=95938" - + # Get the response from derpibooru and parse the 'searc' result from it response = urllib.request.urlopen(url) data = json.loads(response.read().decode('utf-8')) results = data['search'] - + # Get the link if it exists, if not return saying no results found if len(results) > 0: index = random.randint(0, len(results) - 1) @@ -100,7 +100,7 @@ class Core: # If no search term was provided, search for a random image with urllib.request.urlopen('https://derpibooru.org/images/random') as response: imageLink = response.geturl() - + # Post link to my link shortening site # discord still shows image previews through redirects so this is not an issue. url = 'https://shpro.link/redirect.php/' @@ -169,10 +169,10 @@ class Core: for t in tags: if t['tag'] == tag and t['server_id'] == ctx.message.server.id: t['result'] = tag_result - config.saveContent('tags',tags) + config.saveContent('tags', tags) return - tags.append({'server_id':ctx.message.server.id,'tag':tag,'result':tag_result}) - config.saveContent('tags',tags) + tags.append({'server_id': ctx.message.server.id, 'tag': tag, 'result': tag_result}) + 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)) @tag.command(name='delete', aliases=['remove', 'stop'], pass_context=True, no_pm=True) @@ -184,12 +184,13 @@ class Core: tags = config.getContent('tags') result = [t for t in tags if t['tag'] == tag and t['server_id'] == ctx.message.server.id] if len(result) == 0: - await self.bot.say("The tag {} does not exist! You can't remove something if it doesn't exist...".format(tag)) + await self.bot.say( + "The tag {} does not exist! You can't remove something if it doesn't exist...".format(tag)) return for t in tags: if t['tag'] == tag and t['server_id'] == ctx.message.server.id: tags.remove(t) - config.saveContent('tags',tags) + config.saveContent('tags', tags) await self.bot.say('I have just removed the tag `{}`'.format(tag)) diff --git a/cogs/interaction.py b/cogs/interaction.py index 77a9018..21c688f 100644 --- a/cogs/interaction.py +++ b/cogs/interaction.py @@ -33,12 +33,13 @@ def updateBattleRecords(winner, loser): result[1] = str(int(result[1]) + 1) battles[loser.id] = "-".join(result) else: - battles = {winner.id:"1-0",loser.id:"0-1"} - config.saveContent('battle_records',battles) + battles = {winner.id: "1-0", loser.id: "0-1"} + config.saveContent('battle_records', battles) class Interaction: """Commands that interact with another user""" + def __init__(self, bot): self.bot = bot @@ -87,7 +88,7 @@ class Interaction: await self.bot.say(fmt.format(battleP2.mention, battleP1.mention)) updateBattleRecords(battleP2, battleP1) battlingOff() - + @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def decline(self, ctx): @@ -97,7 +98,7 @@ class Interaction: await self.bot.say("{0} has chickened out! {1} wins by default!".format(battleP2.mention, battleP1.mention)) updateBattleRecords(battleP1, battleP2) battlingOff() - + @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def boop(self, ctx, boopee: discord.Member): @@ -122,7 +123,7 @@ class Interaction: amount = 1 booper_boops = boops.get(ctx.message.author.id) if booper_boops is None: - boops[ctx.message.author.id] = {boopee.id:1} + boops[ctx.message.author.id] = {boopee.id: 1} elif booper_boops.get(boopee.id) is None: booper_boops[boopee.id] = 1 boops[ctx.message.author.id] = booper_boops @@ -130,8 +131,8 @@ class Interaction: amount = booper_boops.get(boopee.id) + 1 booper_boops[boopee.id] = amount boops[ctx.message.author.id] = booper_boops - - config.saveContent('boops',boops) + + config.saveContent('boops', boops) fmt = "{0.mention} has just booped you {1.mention}! That's {2} times now!" await self.bot.say(fmt.format(booper, boopee, amount)) diff --git a/cogs/mod.py b/cogs/mod.py index dc63180..dfb57ed 100644 --- a/cogs/mod.py +++ b/cogs/mod.py @@ -1,7 +1,6 @@ from discord.ext import commands from .utils import checks from .utils import config -import pymysql import discord import re @@ -29,19 +28,19 @@ class Mod: await self.bot.say("This channel is already registered as 'nsfw'!") else: nsfw_channels.append(ctx.message.channel.id) - config.saveContent('nsfw_channels',nsfw_channels) + config.saveContent('nsfw_channels', nsfw_channels) await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)") - @nsfw.command(name="remove", aliases=["delete"], pass_context=True) + @nsfw.command(name="remove", aliases=["delete"], pass_context=True, no_pm=True) @checks.customPermsOrRole("kick_members") - async def nsfw_remove(self, ctx, no_pm=True): + async def nsfw_remove(self, ctx): """Removes this channel as a 'nsfw' channel""" nsfw_channels = config.getContent('nsfw_channels') - if not ctx.message.channel.id in nsfw_channels: + if ctx.message.channel.id not in nsfw_channels: await self.bot.say("This channel is not registered as a ''nsfw' channel!") else: nsfw_channels.remove(ctx.message.channel.id) - config.saveContent('nsfw_channels',nsfw_channels) + config.saveContent('nsfw_channels', nsfw_channels) await self.bot.say("This channel has just been unregistered as a nsfw channel") @commands.command(pass_context=True, no_pm=True) @@ -68,7 +67,7 @@ class Mod: await self.bot.say("Valid permissions are: ```{}```".format("\n".join("{}".format(i) for i in valid_perms))) return command = " ".join(command) - + custom_perms = config.getContent('custom_permissions') if custom_perms is None: await self.bot.say("There are no custom permissions setup on this server yet!") @@ -81,8 +80,8 @@ class Mod: if command_perms is None: await self.bot.say("That command has no custom permissions setup on it!") else: - await self.bot.say("You need to have the permission `{}` " \ - "to use the command `{}` in this server".format(command_perms,command)) + await self.bot.say("You need to have the permission `{}` " + "to use the command `{}` in this server".format(command_perms, command)) @perms.command(name="add", aliases=["setup,create"], pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) @@ -90,11 +89,11 @@ class Mod: """Sets up custom permissions on the provided command Format must be 'perms add ' 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] + command = " ".join(msg[0:len(msg) - 1]) + permissions = msg[len(msg) - 1] if permissions.lower() == "none": permissions = "send_messages" - msg = msg[0:len(msg)-1] + msg = msg[0:len(msg) - 1] count = 0 cmd = self.bot.commands.get(msg[count]) while isinstance(cmd, commands.Group): @@ -103,36 +102,35 @@ class Mod: cmd = cmd.commands.get(msg[count]) except: break - + for check in cmd.checks: - if "isOwner" == check.__name__ or re.search("has_permissions",str(check)) is not None: + if "isOwner" == check.__name__ or re.search("has_permissions", str(check)) is not None: await self.bot.say("This command cannot have custom permissions setup!") return if getattr(discord.Permissions, permissions, None) is None and not permissions.lower() == "none": await self.bot.say("{} does not appear to be a valid permission! Valid permissions are: ```{}```" .format(permissions, "\n".join(valid_perms))) - return - + return + custom_perms = config.getContent('custom_permissions') if custom_perms is None: custom_perms = {} server_perms = custom_perms.get(ctx.message.server.id) if server_perms is None: - custom_perms[ctx.message.server.id] = {command:permissions} + custom_perms[ctx.message.server.id] = {command: permissions} else: server_perms[command] = permissions custom_perms[ctx.message.server.id] = server_perms - config.saveContent('custom_permissions',custom_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)) - + @perms.command(name="remove", aliases=["delete"], pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) async def remove_perms(self, ctx, *command: str): """Removes the custom permissions setup on the command specified""" cmd = " ".join(command) - sid = ctx.message.server.id custom_perms = config.getContent('custom_permissions') if custom_perms is None: await self.bot.say("You do not have custom permissions setup on this server yet!") @@ -146,8 +144,9 @@ class Mod: await self.bot.say("You do not have custom permissions setup on this command yet!") return del custom_perms[ctx.message.server.id][cmd] - config.saveContent('custom_permissions',custom_perms) + config.saveContent('custom_permissions', custom_perms) await self.bot.say("I have just removed the custom permissions for {}!".format(cmd)) + def setup(bot): bot.add_cog(Mod(bot)) diff --git a/cogs/overwatch.py b/cogs/overwatch.py index 478819d..b5394f9 100644 --- a/cogs/overwatch.py +++ b/cogs/overwatch.py @@ -7,14 +7,17 @@ import urllib.parse import urllib.request import urllib.error import json +import re base_url = "https://owapi.net/api/v2/u/" -check_g_stats = ["eliminations","deaths",'kpd','wins','losses','time_played', - 'cards','damage_done','healing_done','multikills'] -check_o_stats = ['wins','losses'] +check_g_stats = ["eliminations", "deaths", 'kpd', 'wins', 'losses', 'time_played', + 'cards', 'damage_done', 'healing_done', 'multikills'] +check_o_stats = ['wins', 'losses'] + class Overwatch: """Class for viewing Overwatch stats""" + def __init__(self, bot): self.bot = bot @@ -32,12 +35,12 @@ class Overwatch: if user is None: user = ctx.message.author bt = config.getContent('overwatch').get(ctx.message.author.id) - + if bt is None: await self.bot.say("I do not have this user's battletag saved!") return await self.bot.say("Searching profile information....") - + try: if hero == "": result = urllib.request.urlopen(base_url + "{}/stats/general".format(bt)) @@ -45,7 +48,8 @@ class Overwatch: fmt = "\n".join("{}: {}".format(i, r) for i, r in data['game_stats'].items() if i in check_g_stats) fmt += "\n" fmt += "\n".join("{}: {}".format(i, r) for i, r in data['overall_stats'].items() if i in check_o_stats) - await self.bot.say("Overwatch stats for {}: ```py\n{}```".format(user.name, fmt.title().replace("_", " "))) + await self.bot.say( + "Overwatch stats for {}: ```py\n{}```".format(user.name, fmt.title().replace("_", " "))) else: result = urllib.request.urlopen(base_url + "{}/heroes/{}".format(bt, hero.lower().replace('-', ''))) data = json.loads(result.read().decode('utf-8')) @@ -55,7 +59,7 @@ class Overwatch: await self.bot.say("Overwatch stats for {} using the hero {}: ```py\n{}``` " .format(user.name, hero.title(), fmt.title().replace("_", " "))) except urllib.error.HTTPError as error: - error_no = int(re.search("\d+",str(error)).group(0)) + error_no = int(re.search("\d+", str(error)).group(0)) if error_no == 500: await self.bot.say("{} has not used the hero {} before!".format(user.name, hero.title())) elif error_no == 404: @@ -76,8 +80,8 @@ class Overwatch: return ow = config.getContent('overwatch') ow[ctx.message.author.id] = bt - config.saveContent('overwatch',ow) - + config.saveContent('overwatch', ow) + await self.bot.say("I have just saved your battletag {}".format(ctx.message.author.mention)) @ow.command(pass_context=True, name="delete", aliases=['remove'], no_pm=True) @@ -87,7 +91,7 @@ class Overwatch: result = config.getContent('overwatch') if result.get(ctx.message.author.id): del result[ctx.message.author.id] - config.saveContent('overwatch',result) + config.saveContent('overwatch', result) await self.bot.say("I no longer have your battletag saved {}".format(ctx.message.author.mention)) else: await self.bot.say("I don't even have your battletag saved {}".format(ctx.message.author.mention)) diff --git a/cogs/owner.py b/cogs/owner.py index 2e4a4c8..3d39046 100644 --- a/cogs/owner.py +++ b/cogs/owner.py @@ -15,6 +15,7 @@ multi = re.compile(r'```(.*?)```', re.DOTALL) class Owner: """Commands that can only be used by Phantom, bot management commands""" + def __init__(self, bot): self.bot = bot @@ -22,21 +23,21 @@ class Owner: @commands.check(checks.isOwner) async def restart(self, ctx): """Forces the bot to restart""" - config.saveContent('restart_server',ctx.message.channel.id) + config.saveContent('restart_server', ctx.message.channel.id) await self.bot.say("Restarting; see you in the next life {0}!".format(ctx.message.author.mention)) python = sys.executable os.execl(python, python, *sys.argv) - - @commands.command(pass_context=True) + @commands.command() @commands.check(checks.isOwner) - async def adddoggo(self, ctx, url: str): + async def adddoggo(self, url: str): """Saves a URL as an image to add for the doggo command""" os.chdir('/home/phxntx5/public_html/Bonfire/images') local_path = 'doggo{}.jpg'.format(len(glob.glob('doggo*'))) - urllib.request.urlretrieve(url,local_path) - await self.bot.say("Just saved a new doggo image! You now have {} doggo images!".format(len(glob.glob('doggo*')))) - + urllib.request.urlretrieve(url, local_path) + await self.bot.say( + "Just saved a new doggo image! You now have {} doggo images!".format(len(glob.glob('doggo*')))) + @commands.command(pass_context=True) @commands.check(checks.isOwner) async def py(self, ctx): diff --git a/cogs/stats.py b/cogs/stats.py index 027cf38..cb5efbb 100644 --- a/cogs/stats.py +++ b/cogs/stats.py @@ -3,11 +3,11 @@ from discord.utils import find from .utils import config from .utils import checks import re -import pymysql class Stats: """Leaderboard/stats related commands""" + def __init__(self, bot): self.bot = bot @@ -20,14 +20,14 @@ class Stats: 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 - + most_boops = 0 - for b_id,amt in boops.get(ctx.message.author.id).items(): + for b_id, amt in boops.get(ctx.message.author.id).items(): member = find(lambda m: m.id == b_id, self.bot.get_all_members()) if member in members and amt > most_boops: most_boops = amt most_id = b_id - + member = find(lambda m: m.id == most_id, self.bot.get_all_members()) await self.bot.say("{0} you have booped {1} the most amount of times, coming in at {2} times".format( ctx.message.author.mention, member.mention, most_boops)) @@ -42,7 +42,7 @@ class Stats: await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) return output = "You have booped:" - for b_id,amt in boops.get(ctx.message.author.id).items(): + for b_id, amt in boops.get(ctx.message.author.id).items(): member = find(lambda m: m.id == b_id, self.bot.get_all_members()) if member in members: output += "\n{0.name}: {1} times".format(member, amt) @@ -57,7 +57,7 @@ class Stats: count = 0 fmt = [] if battles is not None: - for m_id,record in battles.items(): + for m_id, record in battles.items(): member = find(lambda m: m.id == m_id, self.bot.get_all_members()) if member in members: winAmt = int(record.split('-')[0]) diff --git a/cogs/twitch.py b/cogs/twitch.py index 944dc36..5f836cc 100644 --- a/cogs/twitch.py +++ b/cogs/twitch.py @@ -47,14 +47,14 @@ class Twitch: config.closeConnection() await asyncio.sleep(30) - @commands.group(no_pm=True, invoke_without_command=True,pass_context=True) + @commands.group(no_pm=True, invoke_without_command=True, pass_context=True) @checks.customPermsOrRole("none") async def twitch(self, ctx, *, member: discord.Member=None): """Use this command to check the twitch info of a user""" if member is not None: twitch = config.getContent('twitch') result = twitch.get(ctx.message.author.id) - + if result is not None: url = result['twitch_url'] user = re.search("(?<=twitch.tv/)(.*)", url).group(1) @@ -88,12 +88,13 @@ class Twitch: twitch = config.getContent('twitch') result = twitch.get(ctx.message.author.id) - + if result is not None: twitch[ctx.message.author.id]['twitch_url'] = url else: - twitch[ctx.message.author.id] = {'twitch_url':url,'server_id':ctx.message.server.id,'notifications_on': 1,'live':0} - config.saveContent('twitch',twitch) + twitch[ctx.message.author.id] = {'twitch_url': url, 'server_id': ctx.message.server.id, + 'notifications_on': 1, 'live': 0} + config.saveContent('twitch', twitch) await self.bot.say("I have just saved your twitch url {}".format(ctx.message.author.mention)) @twitch.command(name='remove', aliases=['delete'], pass_context=True, no_pm=True) @@ -103,7 +104,7 @@ class Twitch: twitch = config.getContent('twitch') if twitch.get(ctx.message.author.id) is not None: del twitch[ctx.message.author.id] - config.saveContent('twitch',twitch) + config.saveContent('twitch', twitch) await self.bot.say("I am no longer saving your twitch URL {}".format(ctx.message.author.mention)) else: await self.bot.say( @@ -131,7 +132,7 @@ class Twitch: ctx.message.author.mention)) else: twitch[ctx.message.author.id]['notifications_on'] = 1 - config.saveContent('twitch',twitch) + 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)) @@ -144,12 +145,12 @@ class Twitch: await self.bot.say( "I do not have your twitch URL added {}. You can save your twitch url with !twitch add".format( ctx.message.author.mention)) - elif not result['notifications_on']: + elif not twitch.get(ctx.message.author.id)['notifications_on']: await self.bot.say("I am already set to not notify if you go live! Pay attention brah {}".format( ctx.message.author.mention)) else: twitch[ctx.message.author.id]['notifications_on'] = 0 - config.saveContent('twitch',twitch) + config.saveContent('twitch', twitch) await self.bot.say( "I will not notify if you go live anymore {}, " "are you going to stream some lewd stuff you don't want people to see?~".format( diff --git a/cogs/utils/config.py b/cogs/utils/config.py index f67ac5a..86f519e 100644 --- a/cogs/utils/config.py +++ b/cogs/utils/config.py @@ -1,5 +1,4 @@ import yaml -import pymysql.cursors import asyncio import json @@ -19,18 +18,6 @@ botToken = global_config.get("bot_token", "") ownerID = global_config.get("owner_id", "") -def getCursor(): - global connection - connection = pymysql.connect(host=global_config.get("db_host"), user=global_config.get("db_user"), - password=global_config.get("db_user_pass"), charset='utf8mb4', - cursorclass=pymysql.cursors.DictCursor) - return connection.cursor() - - -def closeConnection(): - connection.commit() - connection.close() - def saveContent(key: str, content): with open("/home/phxntx5/public_html/Bonfire/config.json", "r+") as jf: data = json.load(jf)