add HTTP API to the bot

we use aiohttp and directly grab the discord bot's asyncio handler to
create a shared loop. things seem to work?
This commit is contained in:
Brian S. Stephan 2018-01-09 10:23:36 -06:00
parent fa18533667
commit c2da9d09a3
2 changed files with 41 additions and 1 deletions

22
bot/api.py Normal file
View File

@ -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)

View File

@ -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()