当前位置: 首页>>代码示例>>Python>>正文


Python WebhookServer.serve_forever方法代码示例

本文整理汇总了Python中telegram.utils.webhookhandler.WebhookServer.serve_forever方法的典型用法代码示例。如果您正苦于以下问题:Python WebhookServer.serve_forever方法的具体用法?Python WebhookServer.serve_forever怎么用?Python WebhookServer.serve_forever使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telegram.utils.webhookhandler.WebhookServer的用法示例。


在下文中一共展示了WebhookServer.serve_forever方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Updater

# 需要导入模块: from telegram.utils.webhookhandler import WebhookServer [as 别名]
# 或者: from telegram.utils.webhookhandler.WebhookServer import serve_forever [as 别名]

#.........这里部分代码省略.........
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url, allowed_updates):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path,
                                   self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(
                max_retries=bootstrap_retries,
                clean=clean,
                webhook_url=webhook_url,
                cert=open(cert, 'rb'),
                allowed_updates=allowed_updates)
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    def _check_ssl_cert(self, cert, key):
        # Check SSL-Certificate with openssl, if possible
        try:
            exit_code = subprocess.call(
                ["openssl", "x509", "-text", "-noout", "-in", cert],
                stdout=open(os.devnull, 'wb'),
                stderr=subprocess.STDOUT)
        except OSError:
            exit_code = 0
        if exit_code is 0:
            try:
                self.httpd.socket = ssl.wrap_socket(
                    self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
            except ssl.SSLError as error:
                self.logger.exception('Failed to init SSL socket')
                raise TelegramError(str(error))
        else:
            raise TelegramError('SSL Certificate invalid')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.delete_webhook()
开发者ID:noam09,项目名称:deluge-telegramer,代码行数:70,代码来源:updater.py

示例2: token

# 需要导入模块: from telegram.utils.webhookhandler import WebhookServer [as 别名]
# 或者: from telegram.utils.webhookhandler.WebhookServer import serve_forever [as 别名]

#.........这里部分代码省略.........
                        self.logger.info('Updates ignored and will be pulled '
                                         'again on restart.')
                    break

                for update in updates:
                    self.update_queue.put(update)
                    self.last_update_id = update.update_id + 1
                    current_interval = poll_interval

                sleep(current_interval)
            except TelegramError as te:
                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)
                sleep(current_interval)

                # increase waiting times on subsequent errors up to 30secs
                if current_interval < 30:
                    current_interval += current_interval / 2
                if current_interval > 30:
                    current_interval = 30

        self.logger.info('Updater thread stopped')

    def _start_webhook(self, listen, port, url_path, cert, key):
        self.logger.info('Updater thread started')
        use_ssl = cert is not None and key is not None
        url_path = "/%s" % url_path

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler,
                                   self.update_queue, url_path)

        if use_ssl:
            # Check SSL-Certificate with openssl, if possible
            try:
                exit_code = subprocess.call(["openssl", "x509", "-text",
                                             "-noout", "-in", cert],
                                            stdout=open(os.devnull, 'wb'),
                                            stderr=subprocess.STDOUT)
            except OSError:
                exit_code = 0

            if exit_code is 0:
                try:
                    self.httpd.socket = ssl.wrap_socket(self.httpd.socket,
                                                        certfile=cert,
                                                        keyfile=key,
                                                        server_side=True)
                except ssl.SSLError as error:
                    raise TelegramError(str(error))
            else:
                raise TelegramError('SSL Certificate invalid')

        self.httpd.serve_forever(poll_interval=1)
        self.logger.info('Updater thread stopped')

    def stop(self):
        """
        Stops the polling/webhook thread and the dispatcher
        """
        self.logger.info('Stopping Updater and Dispatcher...')
        self.logger.debug('This might take a long time if you set a high value'
                          ' as polling timeout.')
        self.running = False

        if self.httpd:
            self.logger.info(
                'Waiting for current webhook connection to be closed... '
                'Send a Telegram message to the bot to exit immediately.')
            self.httpd.shutdown()
            self.httpd = None

        self.logger.debug("Requesting Dispatcher to stop...")
        self.dispatcher.stop()
        while dispatcher.running_async > 0:
            sleep(1)

        self.logger.debug("Dispatcher stopped.")

    def signal_handler(self, signum, frame):
        self.is_idle = False
        self.stop()

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """
        Waits for the user to press Ctrl-C and stops the updater

        Args:
            stop_signals: Iterable containing signals from the signal module
                that should be subscribed to. Updater.stop() will be called on
                receiving one of those signals.
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
开发者ID:gisho,项目名称:python-telegram-bot,代码行数:104,代码来源:updater.py

示例3: token

# 需要导入模块: from telegram.utils.webhookhandler import WebhookServer [as 别名]
# 或者: from telegram.utils.webhookhandler.WebhookServer import serve_forever [as 别名]

#.........这里部分代码省略.........
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key):
        self.logger.info('Updater thread started')
        use_ssl = cert is not None and key is not None
        url_path = "/%s" % url_path

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler,
                                   self.update_queue, url_path)

        if use_ssl:
            # Check SSL-Certificate with openssl, if possible
            try:
                exit_code = subprocess.call(["openssl", "x509", "-text",
                                             "-noout", "-in", cert],
                                            stdout=open(os.devnull, 'wb'),
                                            stderr=subprocess.STDOUT)
            except OSError:
                exit_code = 0

            if exit_code is 0:
                try:
                    self.httpd.socket = ssl.wrap_socket(self.httpd.socket,
                                                        certfile=cert,
                                                        keyfile=key,
                                                        server_side=True)
                except ssl.SSLError as error:
                    self.logger.exception('failed to init SSL socket')
                    raise TelegramError(str(error))
            else:
                raise TelegramError('SSL Certificate invalid')

        self.httpd.serve_forever(poll_interval=1)

    def _clean_updates(self):
        self.logger.info('Cleaning updates from Telegram server')
        updates = self.bot.getUpdates()
        while updates:
            updates = self.bot.getUpdates(updates[-1].update_id + 1)

    def stop(self):
        """
        Stops the polling/webhook thread, the dispatcher and the job queue
        """

        self.job_queue.stop()
        with self.__lock:
            if self.running:
                self.logger.info('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()
                # async threads must be join()ed only after the dispatcher
                # thread was joined, otherwise we can still have new async
                # threads dispatched
                self._join_async_threads()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.info(
                'Waiting for current webhook connection to be '
                'closed... Send a Telegram message to the bot to exit '
开发者ID:Suyashc1295,项目名称:python-telegram-bot,代码行数:70,代码来源:updater.py

示例4: Updater

# 需要导入模块: from telegram.utils.webhookhandler import WebhookServer [as 别名]
# 或者: from telegram.utils.webhookhandler.WebhookServer import serve_forever [as 别名]

#.........这里部分代码省略.........
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path,
                                   self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(
                max_retries=bootstrap_retries,
                clean=clean,
                webhook_url=webhook_url,
                cert=open(cert, 'rb'))
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    def _check_ssl_cert(self, cert, key):
        # Check SSL-Certificate with openssl, if possible
        try:
            exit_code = subprocess.call(
                ["openssl", "x509", "-text", "-noout", "-in", cert],
                stdout=open(os.devnull, 'wb'),
                stderr=subprocess.STDOUT)
        except OSError:
            exit_code = 0
        if exit_code is 0:
            try:
                self.httpd.socket = ssl.wrap_socket(
                    self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
            except ssl.SSLError as error:
                self.logger.exception('Failed to init SSL socket')
                raise TelegramError(str(error))
        else:
            raise TelegramError('SSL Certificate invalid')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    def _bootstrap(self, max_retries, clean, webhook_url, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.setWebhook(webhook_url='')
开发者ID:igorcmoura,项目名称:python-telegram-bot,代码行数:70,代码来源:updater.py


注:本文中的telegram.utils.webhookhandler.WebhookServer.serve_forever方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。