From 6f9acb0d7a30e69add2e086f38f0637bbc3e22ab Mon Sep 17 00:00:00 2001 From: phxntxm Date: Tue, 30 Aug 2016 20:48:30 -0500 Subject: [PATCH] Changed up what was returned on invalid searches --- bot.py | 9 ++++++--- cogs/interaction.py | 6 ++++-- cogs/links.py | 6 ++++-- cogs/mod.py | 32 +++++++++++++++++++++----------- cogs/overwatch.py | 9 ++++++--- cogs/picarto.py | 18 +++++++++--------- cogs/stats.py | 8 ++++---- cogs/strawpoll.py | 6 +++--- cogs/tags.py | 8 ++++---- cogs/tictactoe.py | 2 +- cogs/twitch.py | 18 +++++++++--------- cogs/utils/config.py | 16 ++++++++-------- 12 files changed, 79 insertions(+), 59 deletions(-) diff --git a/bot.py b/bot.py index 684bfc6..6de4854 100644 --- a/bot.py +++ b/bot.py @@ -41,7 +41,8 @@ logging.basicConfig(level=logging.INFO, filename='bonfire.log') async def on_ready(): # Change the status upon connection to the default status await bot.change_status(discord.Game(name=config.default_status, type=0)) - channel_id = await config.get_content('restart_server') or 0 + channel_id = await config.get_content('restart_server') + channel_id = channel_id or 0 # Just in case the bot was restarted while someone was battling, clear it so they do not get stuck await config.save_content('battling', {}) @@ -56,7 +57,8 @@ async def on_ready(): @bot.event async def on_member_join(member): - notifications = await config.get_content('user_notifications') or {} + notifications = await config.get_content('user_notifications') + notifications = notifications or {} server_notifications = notifications.get(member.server.id) # By default, notifications should be off unless explicitly turned on @@ -69,7 +71,8 @@ async def on_member_join(member): @bot.event async def on_member_remove(member): - notifications = await config.get_content('user_notifications') or {} + notifications = await config.get_content('user_notifications') + notifications = notifications or {} server_notifications = notifications.get(member.server.id) # By default, notifications should be off unless explicitly turned on diff --git a/cogs/interaction.py b/cogs/interaction.py index b70dba6..30bac99 100644 --- a/cogs/interaction.py +++ b/cogs/interaction.py @@ -9,7 +9,8 @@ import random async def update_battle_records(winner, loser): # We're using the Harkness scale to rate # http://opnetchessclub.wikidot.com/harkness-rating-system - battles = await config.get_content('battle_records') or {} + battles = await config.get_content('battle_records') + battles = battles or {} # Start ratings at 1000 if they have no rating winner_stats = battles.get(winner.id) or {} @@ -173,7 +174,8 @@ class Interaction: await self.bot.say("Why the heck are you booping me? Get away from me >:c") return - boops = await config.get_content('boops') or {} + boops = await config.get_content('boops') + boops = boops or {} # This is only used to print the amount of times they've booped someone # Set to 1 for the first time someone was booped diff --git a/cogs/links.py b/cogs/links.py index c89d3d7..01383e7 100644 --- a/cogs/links.py +++ b/cogs/links.py @@ -69,7 +69,8 @@ class Links: if len(search) > 0: # This sets the url as url?q=search+terms url = 'https://derpibooru.org/search.json?q={}'.format('+'.join(search)) - nsfw_channels = await config.get_content("nsfw_channels") or {} + nsfw_channels = await config.get_content("nsfw_channels") + nsfw_channels = nsfw_channels or {} # If this is a nsfw channel, we just need to tack on 'explicit' to the terms # Also use the custom filter that I have setup, that blocks some certain tags # If the channel is not nsfw, we don't need to do anything, as the default filter blocks explicit @@ -125,7 +126,8 @@ class Links: # Due to this, send a message saying we're looking up the information first await self.bot.say("Looking up an image with those tags....") - nsfw_channels = await config.get_content("nsfw_channels") or {} + nsfw_channels = await config.get_content("nsfw_channels") + nsfw_channels = nsfw_channels or {} # e621 by default does not filter explicit content, so tack on # safe/explicit based on if this channel is nsfw or not if ctx.message.channel.id in nsfw_channels: diff --git a/cogs/mod.py b/cogs/mod.py index bf6153d..cc32377 100644 --- a/cogs/mod.py +++ b/cogs/mod.py @@ -19,7 +19,8 @@ class Mod: async def alerts(self, ctx, channel: discord.Channel): """This command is used to set a channel as the server's 'notifications' channel Any notifications (like someone going live on Twitch, or Picarto) will go to that channel""" - server_alerts = await config.get_content('server_alerts') or {} + server_alerts = await config.get_content('server_alerts') + server_alerts = server_alerts or {} # This will update/add the channel if an entry for this server exists or not server_alerts[ctx.message.server.id] = channel.id await config.save_content('server_alerts', server_alerts) @@ -36,7 +37,8 @@ class Mod: # So we base this channel on it's own and not from alerts # When mod logging becomes available, that will be kept to it's own channel if wanted as well on_off = ctx.message.channel.id if re.search("(on|yes|true)", on_off.lower()) else None - notifications = await config.get_content('user_notifications') or {} + notifications = await config.get_content('user_notifications') + notifications = notifications or {} notifications[ctx.message.server.id] = on_off await config.save_content('user_notifications', notifications) fmt = "notify" if on_off else "not notify" @@ -53,7 +55,8 @@ class Mod: @checks.custom_perms(kick_members=True) async def nsfw_add(self, ctx): """Registers this channel as a 'nsfw' channel""" - nsfw_channels = await config.get_content('nsfw_channels') or [] + nsfw_channels = await config.get_content('nsfw_channels') + nsfw_channels = nsfw_channels or [] if ctx.message.channel.id in nsfw_channels: await self.bot.say("This channel is already registered as 'nsfw'!") else: @@ -66,7 +69,8 @@ class Mod: @checks.custom_perms(kick_members=True) async def nsfw_remove(self, ctx): """Removes this channel as a 'nsfw' channel""" - nsfw_channels = await config.get_content('nsfw_channels') or [] + nsfw_channels = await config.get_content('nsfw_channels') + nsfw_channels = nsfw_channels or [] if ctx.message.channel.id not in nsfw_channels: await self.bot.say("This channel is not registered as a ''nsfw' channel!") else: @@ -95,7 +99,8 @@ class Mod: "Valid permissions are: ```\n{}```".format("\n".join("{}".format(i) for i in valid_perms))) return - custom_perms = await config.get_content('custom_permissions') or {} + custom_perms = await config.get_content('custom_permissions') + custom_perms = custom_perms or {} server_perms = custom_perms.get(ctx.message.server.id) or {} cmd = None @@ -205,7 +210,8 @@ class Mod: .format(permissions, "\n".join(valid_perms))) return - custom_perms = await config.get_content('custom_permissions') or {} + custom_perms = await config.get_content('custom_permissions') + custom_perms = custom_perms or {} server_perms = custom_perms.get(ctx.message.server.id) or {} # Save the qualified name, so that we don't get screwed up by aliases server_perms[cmd.qualified_name] = perm_value @@ -219,7 +225,8 @@ class Mod: @commands.has_permissions(manage_server=True) async def remove_perms(self, ctx, *command: str): """Removes the custom permissions setup on the command specified""" - custom_perms = await config.get_content('custom_permissions') or {} + custom_perms = await config.get_content('custom_permissions') + custom_perms = custom_perms or {} server_perms = custom_perms.get(ctx.message.server.id) or {} if server_perms is None: await self.bot.say("There are no custom permissions setup on this server yet!") @@ -228,7 +235,7 @@ class Mod: cmd = None # This is the same loop as the add command, we need this to get the # command object so we can get the qualified_name - for part in command[0:len(command) - 1]: + for part in command: try: if cmd is None: cmd = self.bot.commands.get(part) @@ -298,7 +305,8 @@ class Mod: @checks.custom_perms(send_messages=True) async def rules(self, ctx): """This command can be used to view the current rules on the server""" - rules = await config.get_content('rules') or {} + rules = await config.get_content('rules') + rules = 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! I see you like to live dangerously...") @@ -312,7 +320,8 @@ class Mod: async def rules_add(self, ctx, *, rule: str): """Adds a rule to this server's rules""" # Nothing fancy here, just get the rules, append the rule, and save it - rules = await config.get_content('rules') or {} + rules = await config.get_content('rules') + rules = rules or {} server_rules = rules.get(ctx.message.server.id) or [] server_rules.append(rule) rules[ctx.message.server.id] = server_rules @@ -325,7 +334,8 @@ class Mod: """Removes one of the rules from the list of this server's rules Provide a number to delete that rule; if no number is provided I'll print your current rules and ask for a number""" - rules = await config.get_content('rules') or {} + rules = await config.get_content('rules') + rules = rules or {} server_rules = rules.get(ctx.message.server.id) if server_rules is None or len(server_rules) == 0: await self.bot.say( diff --git a/cogs/overwatch.py b/cogs/overwatch.py index 4cf1260..87b17b8 100644 --- a/cogs/overwatch.py +++ b/cogs/overwatch.py @@ -39,7 +39,8 @@ class Overwatch: if user is None: user = ctx.message.author - ow_stats = await config.get_content('overwatch') or {} + ow_stats = await config.get_content('overwatch') + ow_stats = ow_stats or {} bt = ow_stats.get(user.id) if bt is None: @@ -111,7 +112,8 @@ class Overwatch: return # Now just save the battletag - ow = await config.get_content('overwatch') or {} + ow = await config.get_content('overwatch') + ow = ow or {} ow[ctx.message.author.id] = bt await config.save_content('overwatch', ow) await self.bot.say("I have just saved your battletag {}".format(ctx.message.author.mention)) @@ -120,7 +122,8 @@ class Overwatch: @checks.custom_perms(send_messages=True) async def delete(self, ctx): """Removes your battletag from the records""" - result = await config.get_content('overwatch') or {} + result = await config.get_content('overwatch') + result = result or {} if result.get(ctx.message.author.id): del result[ctx.message.author.id] await self.bot.say("I no longer have your battletag saved {}".format(ctx.message.author.mention)) diff --git a/cogs/picarto.py b/cogs/picarto.py index 7a2cf1f..4f09b46 100644 --- a/cogs/picarto.py +++ b/cogs/picarto.py @@ -46,7 +46,7 @@ class Picarto: await self.bot.wait_until_ready() # This is a loop that runs every 30 seconds, checking if anyone has gone online while not self.bot.is_closed: - picarto = await config.get_content('picarto') or {} + picarto = await config.get_content('picarto') # Get all online users before looping, so that only one request is needed online_users_list = await online_users() old_online_users = {m_id: data for m_id, data in picarto.items() if @@ -63,7 +63,7 @@ class Picarto: for server_id in r['servers']: # Get the channel to send the message to, based on the saved alert's channel server = self.bot.get_server(server_id) - server_alerts = await config.get_content('server_alerts') or {} + server_alerts = await config.get_content('server_alerts') channel_id = server_alerts.get(server_id) or server_id channel = self.bot.get_channel(channel_id) # Get the member that has just gone live @@ -82,7 +82,7 @@ class Picarto: for server_id in r['servers']: # Get the channel to send the message to, based on the saved alert's channel server = self.bot.get_server(server_id) - server_alerts = await config.get_content('server_alerts') or {} + server_alerts = await config.get_content('server_alerts') channel_id = server_alerts.get(server_id) or server_id channel = self.bot.get_channel(channel_id) # Get the member that has just gone live @@ -100,7 +100,7 @@ class Picarto: """This command can be used to view Picarto stats about a certain member""" # If member is not given, base information on the author member = member or ctx.message.author - picarto_urls = await config.get_content('picarto') or {} + picarto_urls = await config.get_content('picarto') try: member_url = picarto_urls.get(member.id)['picarto_url'] except: @@ -156,7 +156,7 @@ class Picarto: "What would be the point of adding a nonexistant Picarto user? Silly") return - picarto_urls = await config.get_content('picarto') or {} + picarto_urls = await config.get_content('picarto') result = picarto_urls.get(ctx.message.author.id) # If information for this user already exists, override just the url, and not the information @@ -177,7 +177,7 @@ class Picarto: @checks.custom_perms(send_messages=True) async def remove_picarto_url(self, ctx): """Removes your picarto URL""" - picarto = await config.get_content('picarto') or {} + picarto = await config.get_content('picarto') if picarto.get(ctx.message.author.id) is not None: del picarto[ctx.message.author.id] await config.save_content('picarto', picarto) @@ -195,7 +195,7 @@ class Picarto: member = ctx.message.author # If this user's picarto URL is not saved, no use in adding this server to the list that doesn't exist - picarto = await config.get_content('picarto') or {} + picarto = await config.get_content('picarto') result = picarto.get(member.id) if result is None: await self.bot.say( @@ -213,7 +213,7 @@ class Picarto: @checks.custom_perms(send_messages=True) async def notify_on(self, ctx): """Turns picarto notifications on""" - picarto = await config.get_content('picarto') or {} + picarto = await config.get_content('picarto') result = picarto.get(ctx.message.author.id) # Check if this user has saved their picarto URL first if result is None: @@ -234,7 +234,7 @@ class Picarto: @checks.custom_perms(send_messages=True) async def notify_off(self, ctx): """Turns picarto notifications off""" - picarto = await config.get_content('picarto') or {} + picarto = await config.get_content('picarto') # Check if this user has saved their picarto URL first if picarto.get(ctx.message.author.id) is None: await self.bot.say( diff --git a/cogs/stats.py b/cogs/stats.py index aa2dfbe..98eb690 100644 --- a/cogs/stats.py +++ b/cogs/stats.py @@ -14,7 +14,7 @@ class Stats: @checks.custom_perms(send_messages=True) async def mostboops(self, ctx): """Shows the person you have 'booped' the most, as well as how many times""" - boops = await config.get_content('boops') or {} + boops = await config.get_content('boops') 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 @@ -38,7 +38,7 @@ class Stats: @checks.custom_perms(send_messages=True) async def listboops(self, ctx): """Lists all the users you have booped and the amount of times""" - boops = await config.get_content('boops') or {} + boops = await config.get_content('boops') 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)) @@ -58,7 +58,7 @@ class Stats: @checks.custom_perms(send_messages=True) async def leaderboard(self, ctx): """Prints a leaderboard of everyone in the server's battling record""" - battles = await config.get_content('battle_records') or {} + battles = await config.get_content('battle_records') # Same concept as mostboops server_member_ids = [member.id for member in ctx.message.server.members] @@ -84,7 +84,7 @@ class Stats: """Prints the battling stats for you, or the user provided""" member = member or ctx.message.author - all_members = await config.get_content('battle_records') or {} + all_members = await config.get_content('battle_records') if member.id not in all_members: await self.bot.say("That user has not battled yet!") return diff --git a/cogs/strawpoll.py b/cogs/strawpoll.py index 1f81b36..4cd7f46 100644 --- a/cogs/strawpoll.py +++ b/cogs/strawpoll.py @@ -36,7 +36,7 @@ class Strawpoll: """This command can be used to show a strawpoll setup on this server""" # Strawpolls cannot be 'deleted' so to handle whether a poll is running or not on a server # Just save the poll in the config file, which can then be removed when it should not be "running" anymore - all_polls = await config.get_content('strawpolls') or {} + all_polls = await config.get_content('strawpolls') server_polls = all_polls.get(ctx.message.server.id) or {} if not server_polls: await self.bot.say("There are currently no strawpolls running on this server!") @@ -107,7 +107,7 @@ class Strawpoll: return # Save this strawpoll in the list of running strawpolls for a server - all_polls = await config.get_content('strawpolls') or {} + all_polls = await config.get_content('strawpolls') server_polls = all_polls.get(ctx.message.server.id) or {} server_polls[data['id']] = {'author': ctx.message.author.id, 'date': str(pendulum.utcnow()), 'title': title} all_polls[ctx.message.server.id] = server_polls @@ -121,7 +121,7 @@ class Strawpoll: """This command can be used to delete one of the existing strawpolls If you don't provide an ID it will print the list of polls available""" - all_polls = await config.get_content('strawpolls') or {} + all_polls = await config.get_content('strawpolls') server_polls = all_polls.get(ctx.message.server.id) or {} # Check if a poll_id was provided, if it is then we can continue, if not print the list of current polls diff --git a/cogs/tags.py b/cogs/tags.py index de8e8ef..82d0917 100644 --- a/cogs/tags.py +++ b/cogs/tags.py @@ -14,7 +14,7 @@ class Tags: @checks.custom_perms(send_messages=True) async def tags(self, ctx): """Prints all the custom tags that this server currently has""" - tags = await config.get_content('tags') or {} + tags = await config.get_content('tags') # Simple generator that adds a tag to the list to print, if the tag is for this server fmt = "\n".join("{}".format(tag['tag']) for tag in tags if tag['server_id'] == ctx.message.server.id) await self.bot.say('```\n{}```'.format(fmt)) @@ -24,7 +24,7 @@ class Tags: async def tag(self, ctx, *, tag: str): """This can be used to call custom tags The format to call a custom tag is !tag """ - tags = await config.get_content('tags') or {} + tags = await config.get_content('tags') # Same generator as the method for tags, other than the second check to get the tag that is provided result = [t for t in tags if t['tag'] == tag and t['server_id'] == ctx.message.server.id] if len(result) == 0: @@ -53,7 +53,7 @@ class Tags: "Please provide the format for the tag in: {}tag add - ".format(ctx.prefix)) return - tags = await config.get_content('tags') or [] + tags = await config.get_content('tags') for t in tags: # Attempt to find a tag with that name, so that we update it instead of making a duplicate if t['tag'] == tag and t['server_id'] == ctx.message.server.id: @@ -72,7 +72,7 @@ class Tags: async def del_tag(self, ctx, *, tag: str): """Use this to remove a tag that from use for this server Format to delete a tag is !tag delete """ - tags = await config.get_content('tags') or [] + tags = await config.get_content('tags') # Get a list of the tags that match this server, and the name provided (should only ever be one if any) result = [t for t in tags if t['tag'] == tag and t['server_id'] == ctx.message.server.id] # If we haven't found one, can't delete it diff --git a/cogs/tictactoe.py b/cogs/tictactoe.py index 5952234..1082eea 100644 --- a/cogs/tictactoe.py +++ b/cogs/tictactoe.py @@ -101,7 +101,7 @@ class Board: async def update_records(winner, loser): # This is the exact same formula as the battling update. # The only difference is I use the word "match" instead of "battle" - matches = await config.get_content('tictactoe') or {} + matches = await config.get_content('tictactoe') winner_stats = matches.get(winner.id) or {} winner_rating = winner_stats.get('rating') or 1000 diff --git a/cogs/twitch.py b/cogs/twitch.py index 2a1f96c..3d6e031 100644 --- a/cogs/twitch.py +++ b/cogs/twitch.py @@ -38,7 +38,7 @@ class Twitch: await self.bot.wait_until_ready() # Loop through as long as the bot is connected while not self.bot.is_closed: - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') # Online/offline is based on whether they are set to such, in the config file # This means they were detected as online/offline before and we check for a change online_users = {m_id: data for m_id, data in twitch.items() if data['notifications_on'] and data['live']} @@ -53,7 +53,7 @@ class Twitch: for server_id in r['servers']: # Get the channel to send the message to, based on the saved alert's channel server = self.bot.get_server(server_id) - server_alerts = await config.get_content('server_alerts') or {} + server_alerts = await config.get_content('server_alerts') channel_id = server_alerts.get(server_id) or server_id channel = self.bot.get_channel(channel_id) # Get the member that has just gone live @@ -72,7 +72,7 @@ class Twitch: for server_id in r['servers']: # Get the channel to send the message to, based on the saved alert's channel server = self.bot.get_server(server_id) - server_alerts = await config.get_content('server_alerts') or {} + server_alerts = await config.get_content('server_alerts') channel_id = server_alerts.get(server_id) or server_id channel = self.bot.get_channel(channel_id) # Get the member that has just gone live @@ -91,7 +91,7 @@ class Twitch: if member is None: member = ctx.message.author - twitch_channels = await config.get_content('twitch') or {} + twitch_channels = await config.get_content('twitch') 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)) @@ -137,7 +137,7 @@ class Twitch: "What would be the point of adding a nonexistant twitch user? Silly") return - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') result = twitch.get(ctx.message.author.id) # Check to see if this user has already saved a twitch URL @@ -155,7 +155,7 @@ class Twitch: @checks.custom_perms(send_messages=True) async def remove_twitch_url(self, ctx): """Removes your twitch URL""" - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') # Make sure the user exists before trying to delete them from the list if twitch.get(ctx.message.author.id) is not None: # Simply remove this user from the list, and save @@ -172,7 +172,7 @@ class Twitch: async def notify(self, ctx): """This can be used to modify notification settings for your twitch user Call this command by itself to add 'this' server as one that will be notified when you on/offline""" - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') result = twitch.get(ctx.message.author.id) # Check if this user is saved at all if result is None: @@ -189,7 +189,7 @@ class Twitch: async def notify_on(self, ctx): """Turns twitch notifications on""" # Make sure this user is saved before we attempt to modify their information - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') result = twitch.get(ctx.message.author.id) if result is None: await self.bot.say( @@ -211,7 +211,7 @@ class Twitch: async def notify_off(self, ctx): """Turns twitch notifications off""" # This method is exactly the same, except for turning off notifcations instead of on - twitch = await config.get_content('twitch') or {} + twitch = await config.get_content('twitch') if twitch.get(ctx.message.author.id) is None: await self.bot.say( "I do not have your twitch URL added {}. You can save your twitch url with !twitch add".format( diff --git a/cogs/utils/config.py b/cogs/utils/config.py index 1b36954..35258c0 100644 --- a/cogs/utils/config.py +++ b/cogs/utils/config.py @@ -81,7 +81,9 @@ db_name = global_config.get('db_name', 'Discord_Bot') db_cert = global_config.get('db_cert', '') # The rethinkdb port db_port = global_config.get('db_port', 28015) - +# We've set all the options we need to be able to connect +# so create a dictionary that we can use to unload to connect +db_opts = {'host': db_host, 'db': db_name, 'port': db_port, 'ssl': {'ca_certs': db_cert}} # The perms object we'll update perms = Perms() @@ -89,15 +91,14 @@ async def save_content(table: str, content): # We need to make sure we're using asyncio r.set_loop_type("asyncio") # Just connect to the database - opts = {'host': db_host, 'db': db_name, 'port': db_port, 'ssl': {'ca_certs': db_cert}} - conn = await r.connect(**opts) + conn = await r.connect(**db_opts) # We need to make at least one query to ensure the key exists, so attempt to create it as our query try: await r.table_create(table).run(conn) except r.ReqlOpFailedError: pass - # So now either the table was created already, or it has now been created, we can update the code - # Since we're handling everything that is rewritten in the code itself, we just need to delet then insert + # So the table already existed, or it has now been created, we can update the data now + # Since we're handling everything that is rewritten in the code itself, we just need to delete then insert await r.table(table).delete().run(conn) await r.table(table).insert(content).run(conn) @@ -111,14 +112,13 @@ async def get_content(key: str): # We need to make sure we're using asyncio r.set_loop_type("asyncio") # Just connect to the database - opts = {'host': db_host, 'db': db_name, 'port': db_port, 'ssl': {'ca_certs': db_cert}} - conn = await r.connect(**opts) + conn = await r.connect(**db_opts) # We should only ever get one result, so use it if it exists, otherwise return none try: cursor = await r.table(key).run(conn) items = list(cursor.items)[0] except (IndexError, r.ReqlOpFailedError): - return None + return {} # Rethink db stores an internal id per table, delete this and return the rest del items['id'] return items