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:
parent
fa18533667
commit
c2da9d09a3
22
bot/api.py
Normal file
22
bot/api.py
Normal 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)
|
@ -1,8 +1,11 @@
|
|||||||
"""Start the Discord bot and connect to Discord."""
|
"""Start the Discord bot and connect to Discord."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.management.base import BaseCommand
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
from bot import hitomi
|
from bot import hitomi
|
||||||
|
from bot.api import hitomi_api
|
||||||
|
|
||||||
|
|
||||||
@hitomi.event
|
@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))
|
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):
|
class Command(BaseCommand):
|
||||||
help = "Start the Discord bot and connect to Discord."
|
help = "Start the Discord bot and connect to Discord."
|
||||||
|
|
||||||
def handle(self, *args, **options):
|
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()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user