diff --git a/bot/api.py b/bot/api.py new file mode 100644 index 0000000..8d5f36c --- /dev/null +++ b/bot/api.py @@ -0,0 +1,22 @@ +"""Create a simple API to the bot.""" +from aiohttp import web + + +async def index(request): + """Provide a basic index to the API.""" + return web.Response(text="hitomi") + + +async def greet(request): + """Provide a simple greeting.""" + name = request.match_info.get('name', 'Anonymous') + text = "Hello {0:s}".format(name) + return web.Response(text=text) + +# initialize the API +hitomi_api = web.Application() + +# add our basic stuff above +hitomi_api.router.add_get('/', index) +hitomi_api.router.add_get('/greet', greet) +hitomi_api.router.add_get('/greet/{name}', greet) diff --git a/bot/management/commands/starthitomi.py b/bot/management/commands/starthitomi.py index dd64b1b..cac8952 100644 --- a/bot/management/commands/starthitomi.py +++ b/bot/management/commands/starthitomi.py @@ -1,8 +1,11 @@ """Start the Discord bot and connect to Discord.""" +import asyncio + from django.conf import settings from django.core.management.base import BaseCommand from bot import hitomi +from bot.api import hitomi_api @hitomi.event @@ -11,8 +14,23 @@ async def on_ready(): print("Logged in as {0:s} ({1:s})".format(hitomi.user.name, hitomi.user.id)) +async def run_bot(): + """Initialize and begin the bot in an asyncio context.""" + await hitomi.login(settings.DISCORD_BOT_TOKEN) + await hitomi.connect() + + class Command(BaseCommand): help = "Start the Discord bot and connect to Discord." def handle(self, *args, **options): - hitomi.run(settings.DISCORD_BOT_TOKEN) + loop = asyncio.get_event_loop() + handler = hitomi_api.make_handler() + api_server = loop.create_server(handler, '0.0.0.0', 8080) + futures = asyncio.gather(run_bot(), api_server) + try: + loop.run_until_complete(futures) + except: + loop.run_until_complete(hitomi.logout()) + finally: + loop.close()