예제 #1
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Start asyncio event loop
            loop = asyncio.get_event_loop()

            # initialise pluggable framework
            hooks.load(self)
            sinks.start(self)

            # Connect to Hangouts
            # If we are forcefully disconnected, try connecting again
            for retry in range(self._max_retries):
                try:
                    # create Hangups client (recreate if its a retry)
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(
                        self._on_disconnect)

                    loop.run_until_complete(self._client.connect())

                    logger.info("bot is exiting")

                    loop.run_until_complete(plugins.unload_all(self))

                    self.memory.flush()
                    self.config.flush()

                    sys.exit(0)
                except Exception as e:
                    logger.exception("CLIENT: unrecoverable low-level error")
                    print('Client unexpectedly disconnected:\n{}'.format(e))

                    loop.run_until_complete(plugins.unload_all(self))

                    logger.info('Waiting {} seconds...'.format(5 + retry * 5))
                    time.sleep(5 + retry * 5)
                    logger.info(
                        'Trying to connect again (try {} of {})...'.format(
                            retry + 1, self._max_retries))

            logger.error('Maximum number of retries reached! Exiting...')

        logger.error("Valid login required, exiting")

        sys.exit(1)
예제 #2
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Start asyncio event loop
            loop = asyncio.get_event_loop()

            # initialise pluggable framework
            hooks.load(self)
            sinks.start(self)

            # Connect to Hangouts
            # If we are forcefully disconnected, try connecting again
            for retry in range(self._max_retries):
                try:
                    # create Hangups client (recreate if its a retry)
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(
                        self._on_disconnect)

                    loop.run_until_complete(self._client.connect())
                    logger.info("bot is exiting")

                    loop.run_until_complete(plugins.unload_all(self))

                    self.memory.flush()
                    self.config.flush()

                    sys.exit(0)
                except Exception as e:
                    logger.exception("CLIENT: unrecoverable low-level error")
                    print('Client unexpectedly disconnected:\n{}'.format(e))

                    loop.run_until_complete(plugins.unload_all(self))

                    logger.info('Waiting {} seconds...'.format(5 + retry * 5))
                    time.sleep(5 + retry * 5)
                    logger.info('Trying to connect again (try {} of {})...'.format(
                        retry + 1, self._max_retries))

            logger.error('Maximum number of retries reached! Exiting...')

        logger.error("Valid login required, exiting")

        sys.exit(1)
예제 #3
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Start asyncio event loop
            loop = asyncio.get_event_loop()
            threads = self.get_config_option("max_threads") or 5
            loop.set_default_executor(ThreadPoolExecutor(max_workers=threads))

            # initialise pluggable framework
            hooks.load(self)
            sinks.start(self)

            # Connect to Hangouts
            # If we are forcefully disconnected, try connecting again
            for retry in range(self._max_retries):
                try:
                    # create Hangups client (recreate if its a retry)
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(
                        self._on_disconnect)

                    loop.run_until_complete(self._client.connect())

                except SystemExit:
                    logger.info("bot is exiting")
                    raise

                except:  # pylint:disable=bare-except
                    logger.exception("CLIENT: unrecoverable low-level error")
                finally:
                    loop.run_until_complete(plugins.unload_all(self))

                    self.memory.flush()
                    self.config.flush()

                logger.info('Waiting %s seconds...', 5 + retry * 5)
                time.sleep(5 + retry * 5)
                logger.info('Trying to connect again (try %s of %s)...',
                            retry + 1, self._max_retries)

            logger.error('Maximum number of retries reached! Exiting...')

        logger.error("Valid login required, exiting")

        sys.exit(1)
예제 #4
0
def exit_func():
    #End the session
    logging.info("Ending the session")
    #webapi.session().end(session_data)
    log.info("Shutting down.")
    plugins.unload_all()
예제 #5
0
파일: main.py 프로젝트: discord-math/bot
    import plugins
    import discord_client

    loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()

    async def async_main() -> None:
        await plugins.load("plugins.autoload")
        await discord_client.main_task()

    try:
        loop.run_until_complete(async_main())
    except:
        logger.critical("Exception during main event loop", exc_info=True)
    finally:
        logger.info("Unloading all plugins")
        loop.run_until_complete(plugins.unload_all())
        logger.info("Finalizing event loop")
        tasks = asyncio.all_tasks(loop=loop)
        for task in tasks:
            task.cancel()
        loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
        for task in tasks:
            if not task.cancelled() and task.exception() is not None:
                logger.critical("Unhandled exception in task",
                                exc_info=task.exception())
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.run_until_complete(loop.shutdown_default_executor())
        loop.close()
except:
    logger.critical("Exception in main", exc_info=True)
    raise
예제 #6
0
    def run(self):
        """Connect to Hangouts and run bot"""
        def _login():
            """Login to Google account

            Authenticate with saved cookies or prompt for user credentials

            Returns:
                dict, a dict of cookies to authenticate at Google
            """
            try:
                return hangups.get_auth_stdin(self._cookies_path)

            except hangups.GoogleAuthError as err:
                logger.error("LOGIN FAILED: %s", repr(err))
                return False

        cookies = _login()
        if not cookies:
            logger.critical("Valid login required, exiting")
            sys.exit(1)

        # Start asyncio event loop
        loop = asyncio.get_event_loop()

        # initialise pluggable framework
        sinks.start(self)

        # initialise plugin and command registration
        plugins.tracking.set_bot(self)
        command.set_bot(self)

        # retries for the hangups longpolling request
        max_retries_longpolling = (self._max_retries
                                   if self._max_retries > 5 else 5)

        # Connect to Hangouts
        # If we are forcefully disconnected, try connecting again
        while self.__retry < self._max_retries:
            self.__retry += 1
            try:
                # (re)create Hangups client
                self._client = hangups.Client(cookies, max_retries_longpolling)
                self._client.on_connect.add_observer(self._on_connect)
                self._client.on_disconnect.add_observer(
                    lambda: logger.warning("Event polling stopped"))
                self._client.on_reconnect.add_observer(
                    lambda: logger.warning("Event polling continued"))

                loop.run_until_complete(self._client.connect())
            except SystemExit:
                raise
            except:                                 # pylint:disable=bare-except
                logger.exception("low-level error")
            else:
                logger.critical("bot is exiting")
                sys.exit(0)

            finally:
                logger.info("bot started unloading")
                loop.run_until_complete(self.__stop())
                loop.run_until_complete(plugins.unload_all(self))

                self.memory.flush()
                self.config.flush()
                logger.info("bot unloaded")

            if self.__retry == self._max_retries:
                # the final retry failed, do not delay the exit
                break

            delay = self.__retry * 5
            logger.info("Waiting %s seconds", delay)
            task = asyncio.ensure_future(asyncio.sleep(delay))

            # a KeyboardInterrupt should cancel the delay task instead
            self.stop = task.cancel

            try:
                loop.run_until_complete(task)
            except asyncio.CancelledError:
                return

            # restore the functionality to stop the bot on KeyboardInterrupt
            self.stop = self._stop
            logger.info("Trying to connect again (try %s of %s)",
                        self.__retry, self._max_retries)

        logger.critical("Maximum number of retries reached! Exiting...")
        sys.exit(1)
예제 #7
0
def exit_func():
    #End the session
    logging.info("Ending the session")
    #webapi.session().end(session_data)
    log.info("Shutting down.")
    plugins.unload_all()