diff --git a/bot.py b/bot.py index 11c4ed6..072f6d3 100644 --- a/bot.py +++ b/bot.py @@ -31,28 +31,31 @@ async def on_ready(): cursor.execute('update restart_server set channel_id=0 where id=1') config.closeConnection() + @bot.event async def on_message(message): if message.author.bot: return await bot.process_commands(message) + @bot.event async def on_member_join(member): - await bot.send_message(member.server,"Welcome to the '{0.server.name}' server {0.mention}!".format(member)) + await bot.send_message(member.server, "Welcome to the '{0.server.name}' server {0.mention}!".format(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 async def on_command_error(error, ctx): - if isinstance(error,discord.CommandNotFound): - await bot.send_message(ctx.message.channel,"That is not a valid command! If you need asistance on what command to use, please type '!help'") + if isinstance(error, discord.CommandNotFound): + fmt = "That is not a valid command! If you need asistance on what command to use, please type '!help'" + await bot.send_message(ctx.message.channel, fmt) fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' - await bot.send_message(ctx.message.channel,fmt.format(type(error).__name__, error)) + await bot.send_message(ctx.message.channel, fmt.format(type(error).__name__, error)) if __name__ == '__main__': for e in extensions: diff --git a/cogs/interaction.py b/cogs/interaction.py index 0cdab84..034dc47 100644 --- a/cogs/interaction.py +++ b/cogs/interaction.py @@ -21,23 +21,21 @@ def battlingOff(): def updateBattleRecords(winner, loser): cursor = config.getCursor() - cursor.execute('use {0}'.format(config.db_default)) + cursor.execute('use {}'.format(config.db_default)) # Update winners records - sql = "select record from battle_records where id={0}".format(winner.id) + sql = "select record from battle_records where id='{}'".format(winner.id) cursor.execute(sql) result = cursor.fetchone() if result is not None: result = result['record'].split('-') result[0] = str(int(result[0]) + 1) - sql = "update battle_records set record ='{0}' where id='{1}'".format("-".join(result), winner.id) + sql = "update battle_records set record ='{}' where id='{}'".format("-".join(result), winner.id) cursor.execute(sql) else: - sql = "insert into battle_records (id,record) values ('{0}','1-0')".format(winner.id) + sql = "insert into battle_records (id,record) values ('{}','1-0')".format(winner.id) cursor.execute(sql) - config.closeConnection() - # Update losers records sql = "select record from battle_records where id={0}".format(loser.id) cursor.execute(sql) @@ -87,11 +85,10 @@ class Interaction: t.start() battling = True - @commands.command(no_pm=True) - @checks.battled(battleP2) - async def accept(self): + @commands.command(pass_context=True, no_pm=True) + async def accept(self, ctx): """Accepts the battle challenge""" - if not battling: + if not battling or battleP2 != ctx.message.author: return num = random.randint(1, 100) fmt = config.battleWins[random.randint(0, len(config.battleWins) - 1)] @@ -103,11 +100,10 @@ class Interaction: updateBattleRecords(battleP2, battleP1) battlingOff() - @commands.command(no_pm=True) - @checks.battled(battleP2) - async def decline(self): + @commands.command(pass_context=True, no_pm=True) + async def decline(self, ctx): """Declines the battle challenge""" - if not battling: + if not battling or battleP2 != ctx.message.author: return await self.bot.say("{0} has chickened out! {1} wins by default!".format(battleP2.mention, battleP1.mention)) updateBattleRecords(battleP1, battleP2) diff --git a/cogs/twitch.py b/cogs/twitch.py index ffcf0d2..b8b8d5a 100644 --- a/cogs/twitch.py +++ b/cogs/twitch.py @@ -7,12 +7,14 @@ import discord import json import re + def channelOnline(channel: str): url = "https://api.twitch.tv/kraken/streams/{}".format(channel) response = urllib.request.urlopen(url) data = json.loads(response.read().decode('utf-8')) return data['stream'] is not None - + + async def checkChannels(bot): await bot.wait_until_ready() cursor = config.getCursor() @@ -25,28 +27,29 @@ async def checkChannels(bot): url = r['twitch_url'] live = int(r['live']) notify = int(r['notifications_on']) - user = re.search("(?<=twitch.tv/)(.*)",url).group(1) + user = re.search("(?<=twitch.tv/)(.*)", url).group(1) if not live and notify and channelOnline(user): cursor.execute('update twitch set live=1 where user_id="{}"'.format(r['user_id'])) - await bot.send_message(server,"{} has just gone live! View their stream at {}".format(member.name,url)) + await bot.send_message(server, "{} has just gone live! View their stream at {}".format(member.name, url)) elif live and not channelOnline(user): cursor.execute('update twitch set live=0 where user_id="{}"'.format(r['user_id'])) - await bot.send_message(server,"{} has just gone offline! Catch them next time they stream at {}".format(member.name,url)) + await bot.send_message(server, "{} has just gone offline! Catch them next time they stream at {}" + .format(member.name, url)) config.closeConnection() await asyncio.sleep(180) - - + + class Twitch: """Class for some twitch integration You can add or remove your twitch stream for your user I will then notify the server when you have gone live or offline""" + def __init__(self, bot): self.bot = bot - - @commands.group(pass_context=True,no_pm=True,invoke_without_command=True) - async def twitch(self, ctx, *, member : discord.Member = None): + + @commands.group(pass_context=True, no_pm=True, invoke_without_command=True) + async def twitch(self, ctx, *, member: discord.Member = None): """Use this command to check the twitch info of a user""" - pass if member is not None: cursor = config.getCursor() cursor.execute('use {}'.format(config.db_default)) @@ -54,7 +57,7 @@ class Twitch: result = cursor.fetchone() if result is not None: url = result['twitch_url'] - user = re.search("(?<=twitch.tv/)(.*)",url).group(1) + user = re.search("(?<=twitch.tv/)(.*)", url).group(1) result = urllib.request.urlopen("https://api.twitch.tv/kraken/channels/{}".format(user)) data = json.loads(result.read().decode('utf-8')) fmt = "Username: {}".format(data['display_name']) @@ -66,36 +69,38 @@ class Twitch: else: await self.bot.say("{} has not saved their twitch URL yet!".format(member.name)) config.closeConnection() - - @twitch.command(name='add',pass_context=True,no_pm=True) + + @twitch.command(name='add', pass_context=True, no_pm=True) async def add_twitch_url(self, ctx, url: str): """Saves your user's twitch URL""" try: - url=re.search("((?<=://)?twitch.tv/)+(.*)",url).group(0) + url = re.search("((?<=://)?twitch.tv/)+(.*)", url).group(0) except AttributeError: - url="https://www.twitch.tv/{}".format(url) + url = "https://www.twitch.tv/{}".format(url) else: - url="https://www.{}".format(url) - + url = "https://www.{}".format(url) + try: urllib.request.urlopen(url) except urllib.request.HTTPError: - await self.bot.say("That twitch user does not exist! What would be the point of adding a nonexistant twitch user? Silly") + await self.bot.say("That twitch user does not exist! " + "What would be the point of adding a nonexistant twitch user? Silly") return - + cursor = config.getCursor() cursor.execute('use {}'.format(config.db_default)) cursor.execute('select twitch_url from twitch where user_id="{}"'.format(ctx.message.author.id)) result = cursor.fetchone() if result is not None: - cursor.execute('update twitch set twitch_url="{}" where user_id="{}"'.format(url,ctx.message.author.id)) + cursor.execute('update twitch set twitch_url="{}" where user_id="{}"'.format(url, ctx.message.author.id)) else: - cursor.execute('insert into twitch (user_id,server_id,twitch_url,notifications_on,live) values ("{}","{}","{}",1,0)' - .format(ctx.message.author.id,ctx.message.server.id,url)) + cursor.execute('insert into twitch (user_id,server_id,twitch_url' + ',notifications_on,live) values ("{}","{}","{}",1,0)' + .format(ctx.message.author.id, ctx.message.server.id, url)) await self.bot.say("I have just saved your twitch url {}".format(ctx.message.author.mention)) config.closeConnection() - - @twitch.command(name='remove',aliases=['delete'],pass_context=True,no_pm=True) + + @twitch.command(name='remove', aliases=['delete'], pass_context=True, no_pm=True) async def remove_twitch_url(self, ctx): """Removes your twitch URL""" cursor = config.getCursor() @@ -107,14 +112,16 @@ class Twitch: await self.bot.say("I am no longer saving your twitch URL {}".format(ctx.message.author.mention)) config.closeConnection() else: - 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)) + 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)) config.closeConnection() - + @commands.group(pass_context=True, no_pm=True, invoke_without_command=True) async def notify(self, ctx): """This can be used to turn notifications on or off""" pass - + @notify.command(name='on', aliases=['start,yes'], pass_context=True, no_pm=True) async def notify_on(self, ctx): """Turns twitch notifications on""" @@ -123,19 +130,23 @@ class Twitch: cursor.execute('select notifications_on from twitch where user_id="{}"'.format(ctx.message.author.id)) result = cursor.fetchone() if result is None: - 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)) + 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)) config.closeConnection() return elif result['notifications_on']: - await self.bot.say("What do you want me to do, send two notifications? Not gonna happen {}".format(ctx.message.author.mention)) + await self.bot.say("What do you want me to do, send two notifications? Not gonna happen {}".format( + ctx.message.author.mention)) config.closeConnection() return else: cursor.execute('update twitch set notifications_on=1 where user_id="{}"'.format(ctx.message.author.id)) - 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)) + 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)) config.closeConnection() return - + @notify.command(name='off', aliases=['stop,no'], pass_context=True, no_pm=True) async def notify_off(self, ctx): """Turns twitch notifications off""" @@ -144,20 +155,26 @@ class Twitch: cursor.execute('select notifications_on from twitch where user_id="{}"'.format(ctx.message.author.id)) result = cursor.fetchone() if result is None: - 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)) + 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)) config.closeConnection() return elif not result['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)) + await self.bot.say("I am already set to not notify if you go live! Pay attention brah {}".format( + ctx.message.author.mention)) config.closeConnection() return else: cursor.execute('update twitch set notifications_on=0 where user_id="{}"'.format(ctx.message.author.id)) - 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(ctx.message.author.mention)) + 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( + ctx.message.author.mention)) config.closeConnection() return - - + + def setup(bot): bot.add_cog(Twitch(bot)) config.loop.create_task(checkChannels(bot)) diff --git a/cogs/utils/checks.py b/cogs/utils/checks.py index e74725c..b2b4272 100644 --- a/cogs/utils/checks.py +++ b/cogs/utils/checks.py @@ -30,7 +30,7 @@ def isPM(): return commands.check(predicate) -def battled(battleP2=""): +def battled(battleP2=None): def predicate(ctx): return ctx.message.author == battleP2 diff --git a/cogs/utils/config.py b/cogs/utils/config.py index 61ab7c1..4300227 100644 --- a/cogs/utils/config.py +++ b/cogs/utils/config.py @@ -7,6 +7,8 @@ loop = asyncio.get_event_loop() with open("/home/phxntx5/public_html/Bonfire/config.yml", "r") as f: global_config = yaml.load(f) +connection = None + db_default = global_config.get("db_default") db_boops = global_config.get("db_boops") @@ -24,13 +26,15 @@ openCommands = global_config.get("openCommands", {}) ownerCommands = global_config.get("ownerCommands", {}) voiceCommands = global_config.get("voiceCommands", {}) + 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) + password=global_config.get("db_user_pass"), charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) return connection.cursor() + def closeConnection(): connection.commit() connection.close()