"""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 async def on_ready(): """Print some basic login info to the console, when the bot connects.""" 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): 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()