From 6748f0120856e6dfe8d334d58d79943d060c77b4 Mon Sep 17 00:00:00 2001 From: Joey Hines Date: Thu, 30 Aug 2018 11:34:19 -0500 Subject: [PATCH] Refactored bot.py to wrap Geoffrey in his own class. This will be better for the future for expansions and allowed for cleaning up a lot of the config mess. The Config now all features back except for the named tunnel directions which are removed for now... --- geoffrey/BotConfig.py | 8 -- geoffrey/Commands.py | 5 +- geoffrey/DatabaseInterface.py | 4 +- geoffrey/DatabaseModels.py | 27 ++-- geoffrey/bot.py | 159 ++++++++++++------------ geoffrey/cogs/Add_Commands.py | 11 +- geoffrey/cogs/Admin_Commands.py | 21 ++-- geoffrey/cogs/Delete_Commands.py | 5 +- geoffrey/cogs/Edit_Commands.py | 7 +- geoffrey/cogs/Search_Commands.py | 13 +- geoffrey/tests/test_commands.py | 22 ++-- geoffrey/tests/test_geoffreyDatabase.py | 10 +- 12 files changed, 139 insertions(+), 153 deletions(-) diff --git a/geoffrey/BotConfig.py b/geoffrey/BotConfig.py index 0326892..647b175 100644 --- a/geoffrey/BotConfig.py +++ b/geoffrey/BotConfig.py @@ -18,10 +18,6 @@ def create_config(config, path): } config['Minecraft'] = {'Dynmap_Url': '', 'World_Name': '', - 'North_Tunnel': 'North', - "East_Tunnel": 'South', - "South_Tunnel": 'East', - "West_Tunnel": 'West' } config['Logging'] = {'Count': '7', 'Rotation_Duration': '1' @@ -59,10 +55,6 @@ class Config: self.error_users = self.config['Discord']['Error_Users'].split(',') self.dynmap_url = self.config['Minecraft']['Dynmap_Url'] - self.north_tunnel = self.config['Minecraft']['North_Tunnel'] - self.east_tunnel = self.config['Minecraft']['East_Tunnel'] - self.south_tunnel = self.config['Minecraft']['South_Tunnel'] - self.west_tunnel = self.config['Minecraft']['West_Tunnel'] self.count = int(self.config['Logging']['Count']) self.rotation_duration = int(self.config['Logging']['Rotation_Duration']) diff --git a/geoffrey/Commands.py b/geoffrey/Commands.py index 8754099..22f589c 100644 --- a/geoffrey/Commands.py +++ b/geoffrey/Commands.py @@ -88,8 +88,7 @@ class Commands: location_name = location_list[0].name - tunnel = self.interface.add_tunnel(session, player, tunnel_color, tunnel_number, location_name, - self.bot_config) + tunnel = self.interface.add_tunnel(session, player, tunnel_color, tunnel_number, location_name) tunnel_info = tunnel.__str__() finally: @@ -233,7 +232,7 @@ class Commands: location.tunnel.tunnel_direction = TunnelDirection.str_to_tunnel_dir(tunnel_color) location.tunnel.tunnel_number = tunnel_number else: - self.interface.add_tunnel(session, player, tunnel_color, tunnel_number, loc_name, self.bot_config) + self.interface.add_tunnel(session, player, tunnel_color, tunnel_number, loc_name) loc_str = location.__str__() diff --git a/geoffrey/DatabaseInterface.py b/geoffrey/DatabaseInterface.py index 51de0b4..2fdc42a 100644 --- a/geoffrey/DatabaseInterface.py +++ b/geoffrey/DatabaseInterface.py @@ -16,7 +16,7 @@ class DatabaseInterface: self.database.add_object(session, shop) return shop - def add_tunnel(self, session, owner, color, number, location_name, config): + def add_tunnel(self, session, owner, color, number, location_name): tunnels = self.find_tunnel_by_owner(session, owner) if location_name is None: if len(tunnels): @@ -33,7 +33,7 @@ class DatabaseInterface: except IndexError: raise LocationLookUpError - tunnel = Tunnel(owner, color, number, config, location) + tunnel = Tunnel(owner, color, number, location) self.database.add_object(session, tunnel) return tunnel diff --git a/geoffrey/DatabaseModels.py b/geoffrey/DatabaseModels.py index 91604e3..4efa9e6 100644 --- a/geoffrey/DatabaseModels.py +++ b/geoffrey/DatabaseModels.py @@ -16,7 +16,7 @@ SQL_Base = declarative_base() def check_similarity(a, b): ratio = SequenceMatcher(None, a, b).ratio() - if (ratio > 0.6) or (a[0] == b[0]): + if (ratio > 0.80) or (a[0] == b[0]): return True else: return False @@ -85,21 +85,22 @@ class GeoffreyDatabase: class TunnelDirection(enum.Enum): - North = "North" - East = "East" - South = "South" - West = "West" + North = "north" + East = "east" + South = "south" + West = "west" - def str_to_tunnel_dir(bot_config, arg): + + def str_to_tunnel_dir(arg): arg = arg.lower() - if check_similarity(bot_config.north_tunnel, arg): + if check_similarity(TunnelDirection.North.value, arg): return TunnelDirection.North - elif check_similarity(bot_config.east_tunnel, arg): + elif check_similarity(TunnelDirection.East.value, arg): return TunnelDirection.East - elif check_similarity(bot_config.south_tunnel, arg): + elif check_similarity(TunnelDirection.South.value, arg): return TunnelDirection.South - elif check_similarity(bot_config.west_tunnel, arg): + elif check_similarity(TunnelDirection.West.value, arg): return TunnelDirection.West else: raise InvalidTunnelError @@ -151,11 +152,11 @@ class Tunnel(SQL_Base): location_id = Column(Integer, ForeignKey('geoffrey_locations.id', ondelete='CASCADE')) location = relationship("Location", back_populates="tunnel", lazy="joined") - def __init__(self, owner, tunnel_color, tunnel_number, config, location=None): + def __init__(self, owner, tunnel_color, tunnel_number, location=None): try: self.owner = owner self.location = location - self.tunnel_direction = TunnelDirection.str_to_tunnel_dir(config, tunnel_color) + self.tunnel_direction = TunnelDirection.str_to_tunnel_dir(tunnel_color) self.tunnel_number = tunnel_number except (ValueError, IndexError): raise TunnelInitError @@ -293,4 +294,4 @@ class ItemListing(SQL_Base): return '**{}** **{}** for **{}D**'.format(self.amount, self.name, self.price) def __str__(self): - return '**{}**, selling {}'.format(self.shop.name, self.listing_str()) + return '**{}**, selling {}'.format(self.shop.name, self.listing_str()) \ No newline at end of file diff --git a/geoffrey/bot.py b/geoffrey/bot.py index a64b633..6e376bb 100644 --- a/geoffrey/bot.py +++ b/geoffrey/bot.py @@ -37,93 +37,95 @@ extensions = ['geoffrey.cogs.Add_Commands', 'geoffrey.cogs.Search_Commands', 'geoffrey.cogs.Admin_Commands'] -bot_config = None -bot_commands = None -bot = commands.Bot(command_prefix='?', description=description, case_insensitive=True) +class GeoffreyBot(commands.Bot): + def __init__(self, config): + super().__init__(command_prefix=config.prefix, description=description, pm_help=True, case_insensitive=True) + self.error_users = config.error_users + self.admin_users = config.bot_mod + self.bot_commands = Commands(config) + for extension in extensions: + try: + self.load_extension(extension) + except Exception as e: + logger.info('Failed to load extension {}'.format(extension)) + raise e -@bot.event -async def on_ready(): - logger.info("%s Online, ID: %s", bot.user.name, bot.user.id) - info = await bot.application_info() - url = oauth_url(info.id) - logger.info("Bot url: %s", url) - await bot.change_presence(game=Game(name="Geoffrey")) + async def on_ready(self): + logger.info("%s Online, ID: %s", self.user.name, self.user.id) + info = await self.application_info() + url = oauth_url(info.id) + logger.info("Bot url: %s", url) + await self.change_presence(game=Game(name="Geoffrey")) + async def on_command(self, command, ctx): + if ctx.invoked_subcommand is None: + subcommand = "" + else: + subcommand = ":" + ctx.invoked_subcommand -@bot.event -async def on_command(command, ctx): - if ctx.invoked_subcommand is None: - subcommand = "" - else: - subcommand = ":" + ctx.invoked_subcommand + logger.info("User %s, used command %s%s with context: %s", ctx.message.author, command, subcommand, + ctx.args) - logger.info("User %s, used command %s%s with context: %s", ctx.message.author, command, subcommand, - ctx.args) - - -@bot.event -async def on_command_error(error, ctx): - error_str = '' - if hasattr(ctx, 'cog'): - if "Admin_Commands" in ctx.cog.__str__(): + async def on_command_error(self, error, ctx): + error_str = '' + if hasattr(ctx, 'cog'): + if "Admin_Commands" in ctx.cog.__str__(): + return + if hasattr(error, 'original'): + if isinstance(error.original, NoPermissionError): + error_str = 'You don\'t have permission for that cool command.' + elif isinstance(error.original, UsernameLookupFailed): + error_str = 'Your user name was not found, either Mojang is having a fucky wucky ' \ + 'or your nickname is not set correctly. *stares at the Mods*' + elif isinstance(error.original, PlayerNotFound): + error_str = 'Make sure to use ?register first you ding dong.' + elif isinstance(error.original, EntryNameNotUniqueError): + error_str = 'An entry in the database already has that name you ding dong.' + elif isinstance(error.original, DatabaseValueError): + error_str = 'Use a shorter name or a smaller value, dong ding.' + elif isinstance(error.original, NotOnServerError): + error_str = 'Command needs to be run on 24CC. Run this command there whoever you are.'.format() + elif isinstance(error.original, OperationalError): + await self.send_error_message('Error connecting to the MySQL server, is it offline?') + error_str = 'Database connection issue, looks like some admin has to fix something.'.format() + elif isinstance(error, commands.CommandOnCooldown): return - if hasattr(error, 'original'): - if isinstance(error.original, NoPermissionError): - error_str = 'You don\'t have permission for that cool command.' - elif isinstance(error.original, UsernameLookupFailed): - error_str = 'Your user name was not found, either Mojang is having a fucky wucky ' \ - 'or your nickname is not set correctly. *stares at the Mods*' - elif isinstance(error.original, PlayerNotFound): - error_str = 'Make sure to use ?register first you ding dong.' - elif isinstance(error.original, EntryNameNotUniqueError): - error_str = 'An entry in the database already has that name you ding dong.' - elif isinstance(error.original, DatabaseValueError): - error_str = 'Use a shorter name or a smaller value, dong ding.' - elif isinstance(error.original, NotOnServerError): - error_str = 'Command needs to be run on 24CC. Run this command there whoever you are.'.format() - elif isinstance(error.original, OperationalError): - await send_error_message('Error connecting to the MySQL server, is it offline?') - error_str = 'Database connection issue, looks like some admin has to fix something.'.format() - elif isinstance(error, commands.CommandOnCooldown): - return - elif isinstance(error, commands.UserInputError): - error_str = 'Invalid syntax for **{}** you ding dong:' \ - .format(ctx.invoked_with, ctx.invoked_with) + elif isinstance(error, commands.UserInputError): + error_str = 'Invalid syntax for **{}** you ding dong:' \ + .format(ctx.invoked_with, ctx.invoked_with) - pages = bot.formatter.format_help_for(ctx, ctx.command) - for page in pages: - error_str = error_str + '\n' + page - elif isinstance(error, commands.CommandNotFound): - return + pages = self.formatter.format_help_for(ctx, ctx.command) + for page in pages: + error_str = error_str + '\n' + page + elif isinstance(error, commands.CommandNotFound): + return - if error_str is None: - await send_error_message( - 'Geoffrey encountered unhandled exception: {}. Context:'.format(error, ctx.args)) + if error_str is '': + await self.send_error_message( + 'Geoffrey encountered unhandled exception: {}. Context:'.format(error, ctx.args)) - logger.error("Geoffrey encountered unhandled exception: %s", error) - error_str = bad_error_message.format(ctx.invoked_with) + logger.error("Geoffrey encountered unhandled exception: %s", error) + error_str = bad_error_message.format(ctx.invoked_with) - await bot.send_message(ctx.message.channel, - '{} **Error Running Command:** {}'.format(ctx.message.author.mention, - error_str)) + await self.send_message(ctx.message.channel, + '{} **Error Running Command:** {}'.format(ctx.message.author.mention, + error_str)) + + async def send_error_message(self, msg): + for user_id in self.error_users: + user = await self.get_user_info(user_id) + await self.send_message(user, msg) -async def send_error_message(msg): - for user_id in bot_config.error_users: - user = await bot.get_user_info(user_id) - await bot.send_message(user, msg) - - - -async def username_update(): +async def username_update(bot): await bot.wait_until_ready() while not bot.is_closed: - session = bot_commands.interface.database.Session() + session = bot.bot_commands.interface.database.Session() try: logger.info("Updating MC usernames...") - session = bot_commands.interface.database.Session() + session = bot.bot_commands.interface.database.Session() player_list = session.query(Player).all() for player in player_list: player.name = grab_playername(player.mc_uuid) @@ -135,7 +137,7 @@ async def username_update(): logger.info("Username lookup error.") session.rollback() except OperationalError: - await send_error_message('Error connecting to the MySQL server, is it offline?') + await bot.send_error_message('Error connecting to the MySQL server, is it offline?') logger.info("MySQL connection error") finally: session.close() @@ -169,20 +171,13 @@ def setup_logging(config): def start_bot(config_path="{}/GeoffreyConfig.ini".format(path.dirname(path.abspath(__file__)))): try: - global bot_config, bot_commands bot_config = get_config(config_path) + + bot = GeoffreyBot(bot_config) + setup_logging(bot_config) - bot_commands = Commands(bot_config) - - for extension in extensions: - try: - bot.load_extension(extension) - except Exception as e: - logger.info('Failed to load extension {}'.format(extension)) - raise e - - logger.info('Logging into Discord...') + bot.loop.create_task(username_update(bot)) bot.run(bot_config.token) except KeyboardInterrupt: diff --git a/geoffrey/cogs/Add_Commands.py b/geoffrey/cogs/Add_Commands.py index 0cf269f..c2a5dce 100644 --- a/geoffrey/cogs/Add_Commands.py +++ b/geoffrey/cogs/Add_Commands.py @@ -2,7 +2,6 @@ from discord.ext import commands from geoffrey.BotErrors import * from geoffrey.DiscordHelperFunctions import * -from geoffrey.bot import bot_commands, bot_config @commands.cooldown(5, 60, commands.BucketType.user) @@ -25,7 +24,7 @@ class Add_Commands: try: player_name = get_nickname(ctx.message.author, bot_config) - bot_commands.register(player_name, ctx.message.author.id) + self.bot.bot_commands.register(player_name, ctx.message.author.id) await self.bot.say('{}, you have been added to the database.'.format(ctx.message.author.mention)) except AttributeError: raise NotOnServerError @@ -43,7 +42,7 @@ class Add_Commands: name = get_name(args) try: - base = bot_commands.add_base(x_pos, z_pos, base_name=name, discord_uuid=ctx.message.author.id) + base = self.bot.bot_commands.add_base(x_pos, z_pos, base_name=name, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, your base has been added to the database: \n\n{}'.format(ctx.message.author.mention, base)) except LocationInitError: @@ -68,7 +67,7 @@ class Add_Commands: name = get_name(args) try: - shop = bot_commands.add_shop(x_pos, z_pos, shop_name=name, discord_uuid=ctx.message.author.id) + shop = self.bot.bot_commands.add_shop(x_pos, z_pos, shop_name=name, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, your shop has been added to the database: \n\n{}'.format(ctx.message.author.mention, shop)) except LocationInitError: @@ -93,7 +92,7 @@ class Add_Commands: loc_name = get_name(args) try: - bot_commands.add_tunnel(tunnel_color, tunnel_number, discord_uuid=ctx.message.author.id, + self.bot.bot_commands.add_tunnel(tunnel_color, tunnel_number, discord_uuid=ctx.message.author.id, location_name=loc_name) await self.bot.say('{}, your tunnel has been added to the database'.format(ctx.message.author.mention)) except LocationLookUpError: @@ -120,7 +119,7 @@ class Add_Commands: """ shop_name = get_name(args) try: - bot_commands.add_item(item_name, quantity, diamond_price, shop_name=shop_name, + self.bot.bot_commands.add_item(item_name, quantity, diamond_price, shop_name=shop_name, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, **{}** has been added to the inventory of your shop.'.format(ctx.message.author.mention, diff --git a/geoffrey/cogs/Admin_Commands.py b/geoffrey/cogs/Admin_Commands.py index 59bbc25..b582d0a 100644 --- a/geoffrey/cogs/Admin_Commands.py +++ b/geoffrey/cogs/Admin_Commands.py @@ -2,13 +2,12 @@ from discord import Game from discord.ext import commands from geoffrey.BotErrors import * -from geoffrey.bot import bot_commands, bot_config -def check_mod(user): +def check_mod(user, admin_users): try: for role in user.roles: - if role.id in bot_config.bot_mod: + if role.id in admin_users: return True except AttributeError: raise NotOnServerError @@ -39,7 +38,7 @@ class Admin_Commands: """ Checks if the bot is alive. """ - if check_mod(ctx.message.author): + if check_mod(ctx.message.author, self.bot.admin_users): await self.bot.say('I\'m here you ding dong') else: raise NoPermissionError @@ -49,7 +48,7 @@ class Admin_Commands: """ Bot moderation tools. """ - if check_mod(ctx.message.author): + if check_mod(ctx.message.author, self.bot.admin_users): if ctx.invoked_subcommand is None: await self.bot.say('{}, invalid sub-command for command **mod**.'.format(ctx.message.author.mention)) else: @@ -60,7 +59,7 @@ class Admin_Commands: """ Deletes a location in the database. """ - bot_commands.delete(location_name, discord_uuid=discord_uuid) + self.bot.bot_commands.delete(location_name, discord_uuid=discord_uuid) await self.bot.say('{}, **{}** has been deleted.'.format(ctx.message.author.mention, location_name)) @delete.error @@ -72,7 +71,7 @@ class Admin_Commands: """ Edits the name of a location in the database. """ - bot_commands.edit_name(new_name, current_name, discord_uuid=discord_uuid) + self.bot.bot_commands.edit_name(new_name, current_name, discord_uuid=discord_uuid) await self.bot.say('{}, **{}** has been rename to **{}**.'.format(ctx.message.author.mention, current_name, new_name)) @@ -85,7 +84,7 @@ class Admin_Commands: """ Updates a user's MC UUID. """ - bot_commands.update_mc_uuid(discord_uuid, mc_uuid) + self.bot.bot_commands.update_mc_uuid(discord_uuid, mc_uuid) await self.bot.say('{}, **{}** has been updated.'.format(ctx.message.author.mention, discord_uuid)) @update_mc_uuid.error @@ -97,7 +96,7 @@ class Admin_Commands: """ Updates a user's Discord UUID. """ - bot_commands.update_mc_uuid(current_discord_uuid, new_discord_uuid) + self.bot.bot_commands.update_mc_uuid(current_discord_uuid, new_discord_uuid) await self.bot.say('{}, user **{}** has been updated.'.format(ctx.message.author.mention, current_discord_uuid)) @update_discord_uuid.error @@ -109,7 +108,7 @@ class Admin_Commands: """ Updates a user's MC name to the current name on the MC UUID. """ - bot_commands.update_mc_name(discord_uuid) + self.bot.bot_commands.update_mc_name(discord_uuid) await self.bot.say('{}, user **{}**\'s MC name has update.'.format(ctx.message.author.mention, discord_uuid)) @update_mc_name.error @@ -121,7 +120,7 @@ class Admin_Commands: """ Updates "playing [game]" status of the bot. """ - await self.bot.change_presence(activity=Game(status)) + await self.bot.change_presence(game=Game(name=status)) await self.bot.say('{}, status has been changed'.format(ctx.message.author.mention)) diff --git a/geoffrey/cogs/Delete_Commands.py b/geoffrey/cogs/Delete_Commands.py index f9ff93f..742d427 100644 --- a/geoffrey/cogs/Delete_Commands.py +++ b/geoffrey/cogs/Delete_Commands.py @@ -2,7 +2,6 @@ from discord.ext import commands from geoffrey.BotErrors import * from geoffrey.DiscordHelperFunctions import * -from geoffrey.bot import bot_commands, bot_config class Delete_Commands: @@ -26,7 +25,7 @@ class Delete_Commands: if loc is None: raise commands.UserInputError - bot_commands.delete(loc, discord_uuid=ctx.message.author.id) + self.bot.bot_commands.delete(loc, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, your location named **{}** has been deleted.'.format(ctx.message.author.mention, loc)) except (DeleteEntryError, PlayerNotFound): @@ -42,7 +41,7 @@ class Delete_Commands: shop = get_name(args) try: - bot_commands.delete_item(item, shop, discord_uuid=ctx.message.author.id) + self.bot.bot_commands.delete_item(item, shop, discord_uuid=ctx.message.author.id) await self.bot.say('{}, **{}** has been removed from the inventory of **{}**.'. format(ctx.message.author.mention, item, shop)) diff --git a/geoffrey/cogs/Edit_Commands.py b/geoffrey/cogs/Edit_Commands.py index 1884680..d819644 100644 --- a/geoffrey/cogs/Edit_Commands.py +++ b/geoffrey/cogs/Edit_Commands.py @@ -2,7 +2,6 @@ from discord.ext import commands from geoffrey.BotErrors import * from geoffrey.DiscordHelperFunctions import * -from geoffrey.bot import bot_commands, bot_config class Edit_Commands: @@ -21,7 +20,7 @@ class Edit_Commands: """ loc = get_name(args) try: - loc_str = bot_commands.edit_pos(x_pos, y_pos, loc, discord_uuid=ctx.message.author.id) + loc_str = self.bot.bot_commands.edit_pos(x_pos, y_pos, loc, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, the following location has been updated: \n\n{}'.format(ctx.message.author.mention, loc_str)) @@ -38,7 +37,7 @@ class Edit_Commands: """ loc = get_name(args) try: - loc_str = bot_commands.edit_tunnel(tunnel_color, tunnel_number, loc, discord_uuid=ctx.message.author.id) + loc_str = self.bot.bot_commands.edit_tunnel(tunnel_color, tunnel_number, loc, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, the following location has been updated: \n\n{}'.format(ctx.message.author.mention, loc_str)) @@ -58,7 +57,7 @@ class Edit_Commands: ?edit_name [New Name] [Current Name] """ try: - loc_str = bot_commands.edit_name(new_name, current_name, discord_uuid=ctx.message.author.id) + loc_str = self.bot.bot_commands.edit_name(new_name, current_name, discord_uuid=ctx.message.author.id) await self.bot.say( '{}, the following location has been updated: \n\n{}'.format(ctx.message.author.mention, loc_str)) diff --git a/geoffrey/cogs/Search_Commands.py b/geoffrey/cogs/Search_Commands.py index 118b9f2..584b30e 100644 --- a/geoffrey/cogs/Search_Commands.py +++ b/geoffrey/cogs/Search_Commands.py @@ -2,7 +2,6 @@ from discord.ext import commands from geoffrey.BotErrors import * from geoffrey.DiscordHelperFunctions import * -from geoffrey.bot import bot_commands, bot_config class Search_Commands: @@ -26,7 +25,7 @@ class Search_Commands: if search is None: raise commands.UserInputError - result = bot_commands.find(search) + result = self.bot.bot_commands.find(search) await self.bot.say( '{}, The following entries match **{}**:\n{}'.format(ctx.message.author.mention, search, result)) @@ -42,7 +41,7 @@ class Search_Commands: ?tunnel [Player] """ try: - result = bot_commands.tunnel(player) + result = self.bot.bot_commands.tunnel(player) await self.bot.say( '{}, **{}** owns the following tunnels: \n{}'.format(ctx.message.author.mention, player, result)) @@ -78,7 +77,7 @@ class Search_Commands: if args[1] == '-d': dimension = args[2] - base_string = bot_commands.find_around(x_pos, z_pos, radius, dimension) + base_string = self.bot.bot_commands.find_around(x_pos, z_pos, radius, dimension) if len(base_string) != 0: await self.bot.say('{}, the following locations(s) within **{}** blocks of that point: \n {}'.format( @@ -101,7 +100,7 @@ class Search_Commands: ?selling [item] """ try: - result = bot_commands.selling(item_name) + result = self.bot.bot_commands.selling(item_name) await self.bot.say( '{}, the following shops sell **{}**: \n{}'.format(ctx.message.author.mention, item_name, result)) except ItemNotFound: @@ -121,7 +120,7 @@ class Search_Commands: if loc is None: raise commands.UserInputError - info_str = bot_commands.info(loc) + info_str = self.bot.bot_commands.info(loc) await self.bot.say(info_str) except IndexError: await self.bot.say('{}, no locations in the database match **{}**.'.format(ctx.message.author.mention, loc)) @@ -134,7 +133,7 @@ class Search_Commands: """ try: - loc_str = bot_commands.me(discord_uuid=ctx.message.author.id) + loc_str = self.bot.bot_commands.me(discord_uuid=ctx.message.author.id) await self.bot.say('{}, here are your locations in the database: \n {}'.format(ctx.message.author.mention, loc_str)) except PlayerNotFound: diff --git a/geoffrey/tests/test_commands.py b/geoffrey/tests/test_commands.py index d7b7ef9..db91eff 100644 --- a/geoffrey/tests/test_commands.py +++ b/geoffrey/tests/test_commands.py @@ -1,3 +1,4 @@ +import os from unittest import TestCase from Commands import * @@ -6,7 +7,8 @@ from BotConfig import get_config class TestCommands(TestCase): def setUp(self): - self.bot_config = get_config() + path = os.path.dirname(os.path.abspath(__file__)) + self.bot_config = get_config('{}/GeoffreyConfig.ini'.format(path)) self.commands = Commands(self.bot_config, True) self.session = self.commands.interface.database.Session() self.commands.interface.database.clear_all(self.session) @@ -50,13 +52,13 @@ class TestCommands(TestCase): self.commands.register('ZeroHD', '143072699567177728') self.commands.add_shop(0, 0, shop_name='test shop', discord_uuid='143072699567177728') - tunnel2 = self.commands.add_tunnel(self.bot_config.east_tunnel, 50, location_name='test_shop', + tunnel2 = self.commands.add_tunnel("East", 50, location_name='test_shop', discord_uuid='143072699567177728') - if self.bot_config.east_tunnel not in tunnel2: + if "East" not in tunnel2: self.fail() - self.assertRaises(LocationHasTunnelError, self.commands.add_tunnel, self.bot_config.east_tunnel, 50, + self.assertRaises(LocationHasTunnelError, self.commands.add_tunnel, "East", 50, location_name='test_shop', discord_uuid='143072699567177728') def test_find(self): @@ -127,11 +129,11 @@ class TestCommands(TestCase): self.commands.register('ZeroHD', '143072699567177728') self.commands.add_shop(0, 0, shop_name='frick', discord_uuid='143072699567177728') - self.commands.add_tunnel(self.bot_config.north_tunnel, 50, location_name='frick', discord_uuid='143072699567177728') + self.commands.add_tunnel("West", 50, location_name='frick', discord_uuid='143072699567177728') result = self.commands.info('frick') - if self.bot_config.north_tunnel in result: + if "West" in result: pass else: self.fail() @@ -140,11 +142,11 @@ class TestCommands(TestCase): self.commands.register('ZeroHD', '143072699567177728') self.commands.add_shop(0, 0, shop_name='test shop', discord_uuid='143072699567177728') - self.commands.add_tunnel(self.bot_config.south_tunnel, 50, None, discord_uuid='143072699567177728') + self.commands.add_tunnel("soUTH", 50, None, discord_uuid='143072699567177728') result = self.commands.tunnel('ZeroHD') - if self.bot_config.south_tunnel in result: + if "South" in result: pass else: self.fail() @@ -191,11 +193,11 @@ class TestCommands(TestCase): self.commands.register('ZeroHD', '143072699567177728') self.commands.add_shop(0, 0, shop_name='test shop', discord_uuid='143072699567177728') - self.commands.edit_tunnel(self.bot_config.east_tunnel, 500, 'test shop', discord_uuid='143072699567177728') + self.commands.edit_tunnel("West", 500, 'test shop', discord_uuid='143072699567177728') result = self.commands.info('test shop') - if self.bot_config.east_tunnel in result: + if "West" in result: pass else: self.fail() diff --git a/geoffrey/tests/test_geoffreyDatabase.py b/geoffrey/tests/test_geoffreyDatabase.py index 5f33f21..59f38d1 100644 --- a/geoffrey/tests/test_geoffreyDatabase.py +++ b/geoffrey/tests/test_geoffreyDatabase.py @@ -1,3 +1,4 @@ +import os from unittest import TestCase from DatabaseInterface import * @@ -5,14 +6,15 @@ from BotConfig import * class TestGeoffreyDatabase(TestCase): def setUp(self): - self.config = get_config() - self.interface = DatabaseInterface(self.config, debug=True) + path = os.path.dirname(os.path.abspath(__file__)) + self.bot_config = get_config('{}/GeoffreyConfig.ini'.format(path)) + self.interface = DatabaseInterface(self.bot_config, True) self.session = self.interface.database.Session() self.interface.database.clear_all(self.session) self.owner = Player('ZeroHD', '143072699567177728') self.loc = Location('test', 1, 3, self.owner, dimension='Nether') - self.tunnel = Tunnel(self.owner, self.config.west_tunnel, 105, self.config, self.loc) + self.tunnel = Tunnel(self.owner, "west", 105, self.loc) def tearDown(self): self.session.commit() @@ -91,7 +93,7 @@ class TestGeoffreyDatabase(TestCase): def test_add_tunnel(self): player = self.add_player() - tunnel1 = self.interface.add_tunnel(self.session, player, self.config.south_tunnel, 155, None, self.config) + tunnel1 = self.interface.add_tunnel(self.session, player, "South", 155, None) tunnel2 = self.interface.find_tunnel_by_owner_name(self.session, 'ZeroHD')[0] self.assertEqual(tunnel1, tunnel2)