dos2unix **/*

This commit is contained in:
Brian S. Stephan 2019-07-01 12:11:07 -05:00
parent 061a15caa3
commit 8f0ae10fd4
4 changed files with 154 additions and 154 deletions

View File

@ -1,29 +1,29 @@
"""Create the basic bot for plugins to hook onto.""" """Create the basic bot for plugins to hook onto."""
import logging import logging
from discord.ext import commands from discord.ext import commands
import hitomi.config import hitomi.config
BOT_DESCRIPTION = "A simple Discord bot." BOT_DESCRIPTION = "A simple Discord bot."
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Hitomi(commands.Bot): class Hitomi(commands.Bot):
"""Extend the discord.py Bot, to add more cool stuff.""" """Extend the discord.py Bot, to add more cool stuff."""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Initialize bot, and cool stuff.""" """Initialize bot, and cool stuff."""
super(Hitomi, self).__init__(*args, **kwargs) super(Hitomi, self).__init__(*args, **kwargs)
self.on_message_handlers = [] self.on_message_handlers = []
bot = Hitomi(command_prefix=hitomi.config.BOT_COMMAND_PREFIX, description=BOT_DESCRIPTION, bot = Hitomi(command_prefix=hitomi.config.BOT_COMMAND_PREFIX, description=BOT_DESCRIPTION,
max_messages=hitomi.config.BOT_MAX_MESSAGES) max_messages=hitomi.config.BOT_MAX_MESSAGES)
@bot.event @bot.event
async def on_ready(): async def on_ready():
"""Print some basic login info to the console, when the bot connects.""" """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) logger.info("Logged in as %s (%d)", bot.user.name, bot.user.id)

View File

@ -1,44 +1,44 @@
"""Wrap backend requests for usage in commands.""" """Wrap backend requests for usage in commands."""
import logging import logging
from urllib.parse import urljoin from urllib.parse import urljoin
import requests import requests
import hitomi.config as config import hitomi.config as config
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class DrBotzoError(requests.HTTPError): class DrBotzoError(requests.HTTPError):
"""Wrap HTTPError with the error detail from the dr.botzo API, if available.""" """Wrap HTTPError with the error detail from the dr.botzo API, if available."""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Initialize DrBotzoError.""" """Initialize DrBotzoError."""
detail = kwargs.pop('detail', None) detail = kwargs.pop('detail', None)
self.detail = detail self.detail = detail
super(DrBotzoError, self).__init__(*args, **kwargs) super(DrBotzoError, self).__init__(*args, **kwargs)
class DrBotzoBackend(object): class DrBotzoBackend(object):
"""Basic HTTP requests API, wrapped with some authentication and config stuff.""" """Basic HTTP requests API, wrapped with some authentication and config stuff."""
def post(self, url, **kwargs): def post(self, url, **kwargs):
"""Wrap requests.post with authentication and hostname settings.""" """Wrap requests.post with authentication and hostname settings."""
try: try:
response = requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url), response = requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url),
auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs) auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs)
response.raise_for_status() response.raise_for_status()
return response return response
except requests.ConnectionError as cex: except requests.ConnectionError as cex:
logger.exception("received a connection error during POST %s", url) logger.exception("received a connection error during POST %s", url)
raise DrBotzoError(cex, detail="A connection error occurred.") raise DrBotzoError(cex, detail="A connection error occurred.")
except requests.HTTPError as httpex: except requests.HTTPError as httpex:
logger.exception("received an HTTP error during POST %s", url) logger.exception("received an HTTP error during POST %s", url)
try: try:
detail = httpex.response.json()['detail'] detail = httpex.response.json()['detail']
raise DrBotzoError(httpex, detail=detail) raise DrBotzoError(httpex, detail=detail)
except (ValueError, KeyError): except (ValueError, KeyError):
raise DrBotzoError(httpex, detail="An unexpected error occurred.") raise DrBotzoError(httpex, detail="An unexpected error occurred.")
dr_botzo = DrBotzoBackend() dr_botzo = DrBotzoBackend()

View File

@ -1,45 +1,45 @@
"""Configuration dials for the hitomi bot.""" """Configuration dials for the hitomi bot."""
import logging.config import logging.config
import os import os
BOT_TOKEN = os.environ.get('HITOMI_BOT_TOKEN') BOT_TOKEN = os.environ.get('HITOMI_BOT_TOKEN')
BOT_COMMAND_PREFIX = os.environ.get('HITOMI_BOT_COMMAND_PREFIX', '!') BOT_COMMAND_PREFIX = os.environ.get('HITOMI_BOT_COMMAND_PREFIX', '!')
BOT_MAX_MESSAGES = int(os.environ.get('HITOMI_BOT_MAX_MESSAGES', '5000')) BOT_MAX_MESSAGES = int(os.environ.get('HITOMI_BOT_MAX_MESSAGES', '5000'))
BOT_PLUGIN_STR = os.environ.get('HITOMI_BOT_PLUGINS', '') BOT_PLUGIN_STR = os.environ.get('HITOMI_BOT_PLUGINS', '')
BOT_PLUGINS = BOT_PLUGIN_STR.split(',') if BOT_PLUGIN_STR != '' else [] 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_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_USER = os.environ.get('HITOMI_DR_BOTZO_BACKEND_USER', '')
DR_BOTZO_BACKEND_PASS = os.environ.get('HITOMI_DR_BOTZO_BACKEND_PASS', '') DR_BOTZO_BACKEND_PASS = os.environ.get('HITOMI_DR_BOTZO_BACKEND_PASS', '')
logging.config.dictConfig({ logging.config.dictConfig({
'version': 1, 'version': 1,
'disable_existing_loggers': False, 'disable_existing_loggers': False,
'formatters': { 'formatters': {
'standard': { 'standard': {
'format': '%(asctime)s [%(levelname)-8s] %(name)s: %(message)s' 'format': '%(asctime)s [%(levelname)-7s] %(name)s: %(message)s'
}, },
}, },
'handlers': { 'handlers': {
'default': { 'default': {
'level': 'DEBUG', 'level': 'DEBUG',
'formatter': 'standard', 'formatter': 'standard',
'class': 'logging.StreamHandler', 'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout', 'stream': 'ext://sys.stdout',
}, },
}, },
'loggers': { 'loggers': {
'': { '': {
'handlers': ['default'], 'handlers': ['default'],
'level': 'INFO', 'level': 'INFO',
'propagate': True 'propagate': True
}, },
'hitomi': { 'hitomi': {
'handlers': ['default'], 'handlers': ['default'],
'level': 'DEBUG', 'level': 'DEBUG',
'propagate': False 'propagate': False
}, },
} }
}) })

View File

@ -1,36 +1,36 @@
"""Commands for dice rolling type behavior.""" """Commands for dice rolling type behavior."""
import logging import logging
import re import re
from discord.ext import commands from discord.ext import commands
from hitomi import bot from hitomi import bot
from hitomi.backends import dr_botzo, DrBotzoError from hitomi.backends import dr_botzo, DrBotzoError
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Dice(commands.Cog): class Dice(commands.Cog):
"""Commands for rolling dice and whatnot.""" """Commands for rolling dice and whatnot."""
@commands.command() @commands.command()
async def roll(self, ctx, *, dice): async def roll(self, ctx, *, dice):
"""Roll a provided dice string. """Roll a provided dice string.
Format: T#K/NdS+M; T = times, K = keep, N = number, S = sides, M = modifier Format: T#K/NdS+M; T = times, K = keep, N = number, S = sides, M = modifier
""" """
await ctx.trigger_typing() await ctx.trigger_typing()
logger.info("rolling dice: %s", dice) logger.info("rolling dice: %s", dice)
try: try:
response = dr_botzo.post('/dice/rpc/roll/', json={'dice': dice}) response = dr_botzo.post('/dice/rpc/roll/', json={'dice': dice})
response.raise_for_status() response.raise_for_status()
logger.debug("result of rolling dice: HTTP %s, %s", response.status_code, response.text) 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 = re.sub(r'(\d+)(.*?\s+)(\(.*?\))', r'**\1**\2\3', response.json()['result'])
output = '\n'.join(output.split('; ')) output = '\n'.join(output.split('; '))
await ctx.send(output) await ctx.send(output)
except DrBotzoError as drex: except DrBotzoError as drex:
logger.exception("received an error from dr.botzo attempting to roll %s: %s", dice, drex) logger.exception("received an error from dr.botzo attempting to roll %s: %s", dice, drex)
await ctx.send(f"*{drex.detail}*") await ctx.send(f"*{drex.detail}*")
bot.add_cog(Dice(bot)) bot.add_cog(Dice(bot))