Added logging for commands being run and all console output is now handled through logger.

doc_update
Joey Hines 2018-08-12 10:32:35 -05:00
parent 59c1078426
commit 6662c018a6
3 changed files with 41 additions and 26 deletions

View File

@ -8,6 +8,7 @@ import logging
import logging.handlers as handlers
import bot
from BotConfig import bot_config
from sys import stdout
def setup_logging():
@ -16,8 +17,8 @@ def setup_logging():
discord_logger.setLevel(logging.INFO)
sql_logger = logging.getLogger('sqlalchemy.engine')
sql_logger.setLevel(logging.INFO)
bot_logger = logging.getLogger('bot')
bot_logger.setLevel(logging.INFO)
bot_info_logger = logging.getLogger('bot')
bot_info_logger.setLevel(logging.INFO)
handler = handlers.TimedRotatingFileHandler(filename='Geoffrey.log', when='D',
interval=bot_config.rotation_duration, backupCount=bot_config.count,
@ -25,9 +26,14 @@ def setup_logging():
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
console = logging.StreamHandler(stdout)
console.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
discord_logger.addHandler(handler)
sql_logger.addHandler(handler)
bot_logger.addHandler(handler)
bot_info_logger.addHandler(handler)
bot_info_logger.addHandler(console)
if __name__ == '__main__':

43
bot.py
View File

@ -37,14 +37,20 @@ extensions = ['cogs.Add_Commands',
@bot.event
async def on_ready():
print('GeoffreyBot')
print('Username: ' + bot.user.name)
print('ID: ' + bot.user.id)
logger.info("Geoffrey Online, ID: %s", bot.user.id)
logger.info("%s Online, ID: %s", bot.user.name, bot.user.id)
await bot.change_presence(game=Game(name=bot_config.status))
@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)
@bot.event
async def on_command_error(error, ctx):
if hasattr(ctx, 'cog'):
@ -55,8 +61,13 @@ async def on_command_error(error, ctx):
elif isinstance(error, commands.CommandOnCooldown):
return
elif isinstance(error, commands.UserInputError):
error_str = 'Invalid syntax for **{}** you ding dong, please read ?help {}.'\
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.original, NoPermissionError):
error_str = 'You don\'t have permission for that cool command.'
elif isinstance(error.original, UsernameLookupFailed):
@ -84,23 +95,21 @@ async def username_update():
while not bot.is_closed:
session = bot_commands.interface.database.Session()
try:
print("Updating MC usernames...")
logger.info("Updating MC usernames...")
session = bot_commands.interface.database.Session()
player_list = session.query(Player).all()
for player in player_list:
player.name = grab_playername(player.mc_uuid)
session.commit()
print("Done.")
await asyncio.sleep(600)
logger.info("Username update done.")
except UsernameLookupFailed:
logger.info("Username lookup error.")
print("Username lookup error, are Mojang's servers down?")
session.rollback()
finally:
session.close()
await asyncio.sleep(600)
if session is not None:
session.close()
@ -113,15 +122,15 @@ def start_bot():
bot.load_extension(extension)
except Exception as e:
logger.info('Failed to load extension {}, {}'.format(extension, e))
print('Failed to load extension {}, {}'.format(extension, e))
try:
bot.loop.create_task(username_update())
logger.info('Logging into discord...')
logger.info('Logging into Discord...')
bot.run(bot_config.token)
except TimeoutError:
print("Disconnected, is Discord offline?")
logger.info('Disconnected, is Discord offline?')
except KeyboardInterrupt:
logger.info("Bot received keyboard interrupt")
except Exception as e:
logger.info('Bot encountered the following unhandled exception %s', e)
finally:
bot.loop.stop()
logger.info("Bot shutting down...")
print("Bot shutting down...")

View File

@ -30,7 +30,7 @@ class Admin_Commands:
elif isinstance(error, DeleteEntryError):
error_str = 'that player does not have a location by that name.'
else:
error_str = 'the bot encountered the following error: *{}*'.format(error.__str__())
error_str = 'the bot encountered the following error: {}'.format(error.__str__())
await self.bot.send_message(ctx.message.channel, '{}, {}'.format(ctx.message.author.mention, error_str))
@ -58,7 +58,7 @@ class Admin_Commands:
@mod.command(pass_context=True)
async def delete(self, ctx, discord_uuid: str, location_name: str):
"""
Deletes a location in the database/
Deletes a location in the database.
"""
bot_commands.delete(location_name, discord_uuid=discord_uuid)
await self.bot.say('{}, **{}** has been deleted.'.format(ctx.message.author.mention, location_name))
@ -83,7 +83,7 @@ class Admin_Commands:
@mod.command(pass_context=True)
async def update_mc_uuid(self, ctx, discord_uuid: str, mc_uuid: str):
"""
Updates a user's MC UUID
Updates a user's MC UUID.
"""
bot_commands.update_mc_uuid(discord_uuid, mc_uuid)
await self.bot.say('{}, **{}** has been updated.'.format(ctx.message.author.mention, discord_uuid))
@ -95,7 +95,7 @@ class Admin_Commands:
@mod.command(pass_context=True)
async def update_discord_uuid(self, ctx, current_discord_uuid: str, new_discord_uuid: str):
"""
Updates a user's Discord UUID
Updates a user's Discord UUID.
"""
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))
@ -107,7 +107,7 @@ class Admin_Commands:
@mod.command(pass_context=True)
async def update_mc_name(self, ctx, discord_uuid: str):
"""
Updates a user's MC name to the current name on the MC UUID
Updates a user's MC name to the current name on the MC UUID.
"""
bot_commands.update_mc_name(discord_uuid)
await self.bot.say('{}, user **{}**\'s MC name has update.'.format(ctx.message.author.mention, discord_uuid))
@ -119,7 +119,7 @@ class Admin_Commands:
@mod.command(pass_context=True)
async def status(self, ctx, status: str):
"""
Updates playing game status of the bot
Updates "playing [game]" status of the bot.
"""
await self.bot.change_presence(game=Game(name=status))
await self.bot.say('{}, status has been changed'.format(ctx.message.author.mention))