def run(self) -> None: # noqa: C901 # pylint: disable=arguments-differ loop = self.loop # Additional startup behavior dsn = config["DATABASE_URI"] if dsn: loop.run_until_complete(self.connect_to_database(dsn)) for module in config["STARTUP_MODULES"]: self.load_extension(module) # Default behavior but calls self.shutdown instead of self.close try: loop.add_signal_handler(signal.SIGINT, loop.stop) loop.add_signal_handler(signal.SIGTERM, loop.stop) except NotImplementedError: pass async def runner() -> None: try: await self.start(config["TOKEN"]) finally: await self.shutdown() stop_loop_on_completion = lambda future: loop.stop() # noqa: E731 future = asyncio.ensure_future(runner(), loop=loop) future.add_done_callback(stop_loop_on_completion) try: loop.run_forever() except KeyboardInterrupt: logger.info("Received signal to terminate bot and event loop.") finally: future.remove_done_callback(stop_loop_on_completion) logger.info("Cleaning up tasks.") _cleanup_loop(loop) if not future.cancelled(): future.result()
def run(self, *args, **kwargs): """ Modified version of discord.py's bot.run() method. Use in exactly the same way. """ loop = self.loop try: loop.add_signal_handler(signal.SIGINT, lambda: loop.stop()) loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop()) except NotImplementedError: pass async def runner(): try: await self.setup() if self._use_socket: await self.extend_connection() else: self.logger.debug("extend_connection skipped.") await self.start(*args, **kwargs) finally: await self.close() def stop_loop_on_completion(f): loop.stop() future = asyncio.ensure_future(runner(), loop=loop) future.add_done_callback(stop_loop_on_completion) try: loop.run_forever() except KeyboardInterrupt: self.logger.info('Received signal to terminate bot and event loop.') finally: future.remove_done_callback(stop_loop_on_completion) self.logger.info('Cleaning up tasks.') _cleanup_loop(loop)
"stats_bot.cogs.reactions", "stats_bot.cogs.routines", "stats_bot.cogs.handlers", ] bot = commands.Bot(command_prefix="!", description=description) if __name__ == "__main__": loop = asyncio.get_event_loop() for extension in startup_extensions: try: bot.load_extension(extension) except Exception: logging.warn("Failed to load extension due to exception:") traceback.print_exc() logging.getLogger().setLevel(logging.INFO) loop.run_until_complete(database_reader.create_pool()) try: loop.run_until_complete(bot.start(passwords_and_tokens.discord_token)) except KeyboardInterrupt: loop.run_until_complete(bot.logout()) finally: loop.run_until_complete(database_reader.close_pool()) _cleanup_loop(bot.loop) loop.close()