diff --git a/hitomi/__init__.py b/hitomi/__init__.py index 280625d..4fe7ec8 100644 --- a/hitomi/__init__.py +++ b/hitomi/__init__.py @@ -1,29 +1,29 @@ -"""Create the basic bot for plugins to hook onto.""" -import logging - -from discord.ext import commands - -import hitomi.config - -BOT_DESCRIPTION = "A simple Discord bot." - -logger = logging.getLogger(__name__) - - -class Hitomi(commands.Bot): - """Extend the discord.py Bot, to add more cool stuff.""" - - def __init__(self, *args, **kwargs): - """Initialize bot, and cool stuff.""" - super(Hitomi, self).__init__(*args, **kwargs) - self.on_message_handlers = [] - - -bot = Hitomi(command_prefix=hitomi.config.BOT_COMMAND_PREFIX, description=BOT_DESCRIPTION, - max_messages=hitomi.config.BOT_MAX_MESSAGES) - - -@bot.event -async def on_ready(): - """Print some basic login info to the console, when the bot connects.""" - logger.info("Logged in as %s (%d)", bot.user.name, bot.user.id) +"""Create the basic bot for plugins to hook onto.""" +import logging + +from discord.ext import commands + +import hitomi.config + +BOT_DESCRIPTION = "A simple Discord bot." + +logger = logging.getLogger(__name__) + + +class Hitomi(commands.Bot): + """Extend the discord.py Bot, to add more cool stuff.""" + + def __init__(self, *args, **kwargs): + """Initialize bot, and cool stuff.""" + super(Hitomi, self).__init__(*args, **kwargs) + self.on_message_handlers = [] + + +bot = Hitomi(command_prefix=hitomi.config.BOT_COMMAND_PREFIX, description=BOT_DESCRIPTION, + max_messages=hitomi.config.BOT_MAX_MESSAGES) + + +@bot.event +async def on_ready(): + """Print some basic login info to the console, when the bot connects.""" + logger.info("Logged in as %s (%d)", bot.user.name, bot.user.id) diff --git a/hitomi/backends.py b/hitomi/backends.py index 7f1644e..27da9b1 100644 --- a/hitomi/backends.py +++ b/hitomi/backends.py @@ -1,44 +1,44 @@ -"""Wrap backend requests for usage in commands.""" -import logging -from urllib.parse import urljoin - -import requests - -import hitomi.config as config - -logger = logging.getLogger(__name__) - - -class DrBotzoError(requests.HTTPError): - """Wrap HTTPError with the error detail from the dr.botzo API, if available.""" - - def __init__(self, *args, **kwargs): - """Initialize DrBotzoError.""" - detail = kwargs.pop('detail', None) - self.detail = detail - super(DrBotzoError, self).__init__(*args, **kwargs) - - -class DrBotzoBackend(object): - """Basic HTTP requests API, wrapped with some authentication and config stuff.""" - - def post(self, url, **kwargs): - """Wrap requests.post with authentication and hostname settings.""" - try: - response = requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url), - auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs) - response.raise_for_status() - return response - except requests.ConnectionError as cex: - logger.exception("received a connection error during POST %s", url) - raise DrBotzoError(cex, detail="A connection error occurred.") - except requests.HTTPError as httpex: - logger.exception("received an HTTP error during POST %s", url) - try: - detail = httpex.response.json()['detail'] - raise DrBotzoError(httpex, detail=detail) - except (ValueError, KeyError): - raise DrBotzoError(httpex, detail="An unexpected error occurred.") - - -dr_botzo = DrBotzoBackend() +"""Wrap backend requests for usage in commands.""" +import logging +from urllib.parse import urljoin + +import requests + +import hitomi.config as config + +logger = logging.getLogger(__name__) + + +class DrBotzoError(requests.HTTPError): + """Wrap HTTPError with the error detail from the dr.botzo API, if available.""" + + def __init__(self, *args, **kwargs): + """Initialize DrBotzoError.""" + detail = kwargs.pop('detail', None) + self.detail = detail + super(DrBotzoError, self).__init__(*args, **kwargs) + + +class DrBotzoBackend(object): + """Basic HTTP requests API, wrapped with some authentication and config stuff.""" + + def post(self, url, **kwargs): + """Wrap requests.post with authentication and hostname settings.""" + try: + response = requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url), + auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs) + response.raise_for_status() + return response + except requests.ConnectionError as cex: + logger.exception("received a connection error during POST %s", url) + raise DrBotzoError(cex, detail="A connection error occurred.") + except requests.HTTPError as httpex: + logger.exception("received an HTTP error during POST %s", url) + try: + detail = httpex.response.json()['detail'] + raise DrBotzoError(httpex, detail=detail) + except (ValueError, KeyError): + raise DrBotzoError(httpex, detail="An unexpected error occurred.") + + +dr_botzo = DrBotzoBackend() diff --git a/hitomi/config.py b/hitomi/config.py index dcda3ad..0c41d16 100644 --- a/hitomi/config.py +++ b/hitomi/config.py @@ -1,45 +1,45 @@ -"""Configuration dials for the hitomi bot.""" -import logging.config -import os - -BOT_TOKEN = os.environ.get('HITOMI_BOT_TOKEN') - -BOT_COMMAND_PREFIX = os.environ.get('HITOMI_BOT_COMMAND_PREFIX', '!') -BOT_MAX_MESSAGES = int(os.environ.get('HITOMI_BOT_MAX_MESSAGES', '5000')) - -BOT_PLUGIN_STR = os.environ.get('HITOMI_BOT_PLUGINS', '') -BOT_PLUGINS = BOT_PLUGIN_STR.split(',') if BOT_PLUGIN_STR != '' else [] - -DR_BOTZO_BACKEND_HOST = os.environ.get('HITOMI_DR_BOTZO_BACKEND_HOST', 'http://localhost:8000/') -DR_BOTZO_BACKEND_USER = os.environ.get('HITOMI_DR_BOTZO_BACKEND_USER', '') -DR_BOTZO_BACKEND_PASS = os.environ.get('HITOMI_DR_BOTZO_BACKEND_PASS', '') - -logging.config.dictConfig({ - 'version': 1, - 'disable_existing_loggers': False, - 'formatters': { - 'standard': { - 'format': '%(asctime)s [%(levelname)-8s] %(name)s: %(message)s' - }, - }, - 'handlers': { - 'default': { - 'level': 'DEBUG', - 'formatter': 'standard', - 'class': 'logging.StreamHandler', - 'stream': 'ext://sys.stdout', - }, - }, - 'loggers': { - '': { - 'handlers': ['default'], - 'level': 'INFO', - 'propagate': True - }, - 'hitomi': { - 'handlers': ['default'], - 'level': 'DEBUG', - 'propagate': False - }, - } -}) +"""Configuration dials for the hitomi bot.""" +import logging.config +import os + +BOT_TOKEN = os.environ.get('HITOMI_BOT_TOKEN') + +BOT_COMMAND_PREFIX = os.environ.get('HITOMI_BOT_COMMAND_PREFIX', '!') +BOT_MAX_MESSAGES = int(os.environ.get('HITOMI_BOT_MAX_MESSAGES', '5000')) + +BOT_PLUGIN_STR = os.environ.get('HITOMI_BOT_PLUGINS', '') +BOT_PLUGINS = BOT_PLUGIN_STR.split(',') if BOT_PLUGIN_STR != '' else [] + +DR_BOTZO_BACKEND_HOST = os.environ.get('HITOMI_DR_BOTZO_BACKEND_HOST', 'http://localhost:8000/') +DR_BOTZO_BACKEND_USER = os.environ.get('HITOMI_DR_BOTZO_BACKEND_USER', '') +DR_BOTZO_BACKEND_PASS = os.environ.get('HITOMI_DR_BOTZO_BACKEND_PASS', '') + +logging.config.dictConfig({ + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'standard': { + 'format': '%(asctime)s [%(levelname)-7s] %(name)s: %(message)s' + }, + }, + 'handlers': { + 'default': { + 'level': 'DEBUG', + 'formatter': 'standard', + 'class': 'logging.StreamHandler', + 'stream': 'ext://sys.stdout', + }, + }, + 'loggers': { + '': { + 'handlers': ['default'], + 'level': 'INFO', + 'propagate': True + }, + 'hitomi': { + 'handlers': ['default'], + 'level': 'DEBUG', + 'propagate': False + }, + } +}) diff --git a/hitomi/dice.py b/hitomi/dice.py index 778d7c0..ea2fa5d 100644 --- a/hitomi/dice.py +++ b/hitomi/dice.py @@ -1,36 +1,36 @@ -"""Commands for dice rolling type behavior.""" -import logging -import re - -from discord.ext import commands - -from hitomi import bot -from hitomi.backends import dr_botzo, DrBotzoError - -logger = logging.getLogger(__name__) - - -class Dice(commands.Cog): - """Commands for rolling dice and whatnot.""" - - @commands.command() - async def roll(self, ctx, *, dice): - """Roll a provided dice string. - - Format: T#K/NdS+M; T = times, K = keep, N = number, S = sides, M = modifier - """ - await ctx.trigger_typing() - logger.info("rolling dice: %s", dice) - try: - response = dr_botzo.post('/dice/rpc/roll/', json={'dice': dice}) - response.raise_for_status() - logger.debug("result of rolling dice: HTTP %s, %s", response.status_code, response.text) - output = re.sub(r'(\d+)(.*?\s+)(\(.*?\))', r'**\1**\2\3', response.json()['result']) - output = '\n'.join(output.split('; ')) - await ctx.send(output) - except DrBotzoError as drex: - logger.exception("received an error from dr.botzo attempting to roll %s: %s", dice, drex) - await ctx.send(f"*{drex.detail}*") - - -bot.add_cog(Dice(bot)) +"""Commands for dice rolling type behavior.""" +import logging +import re + +from discord.ext import commands + +from hitomi import bot +from hitomi.backends import dr_botzo, DrBotzoError + +logger = logging.getLogger(__name__) + + +class Dice(commands.Cog): + """Commands for rolling dice and whatnot.""" + + @commands.command() + async def roll(self, ctx, *, dice): + """Roll a provided dice string. + + Format: T#K/NdS+M; T = times, K = keep, N = number, S = sides, M = modifier + """ + await ctx.trigger_typing() + logger.info("rolling dice: %s", dice) + try: + response = dr_botzo.post('/dice/rpc/roll/', json={'dice': dice}) + response.raise_for_status() + logger.debug("result of rolling dice: HTTP %s, %s", response.status_code, response.text) + output = re.sub(r'(\d+)(.*?\s+)(\(.*?\))', r'**\1**\2\3', response.json()['result']) + output = '\n'.join(output.split('; ')) + await ctx.send(output) + except DrBotzoError as drex: + logger.exception("received an error from dr.botzo attempting to roll %s: %s", dice, drex) + await ctx.send(f"*{drex.detail}*") + + +bot.add_cog(Dice(bot))