Пример #1
0
    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)
Пример #2
0
    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)
Пример #3
0
 def __init__(self, upd: Updater, port: int):
     super().__init__()
     app = tw.Application([
         tw.url(r"/notify", MainHandler, dict(upd=upd)),
     ])
     host = "0.0.0.0"
     self.webhooks = WebhookServer(host, port, app, None)
     logger.info(f'Tornado app created @ {host}:{port}')
Пример #4
0
    def _start_webhook(
        self,
        listen,
        port,
        url_path,
        cert,
        key,
        bootstrap_retries,
        clean,
        webhook_url,
        allowed_updates,
        ready=None,
        force_event_loop=False,
    ):
        self.logger.debug('Updater thread started (webhook)')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{}'.format(url_path)

        # Create Tornado app instance
        app = WebhookAppClass(url_path, self.bot, self.update_queue)

        # Form SSL Context
        # An SSLError is raised if the private key does not match with the certificate
        if use_ssl:
            try:
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.load_cert_chain(cert, key)
            except ssl.SSLError as exc:
                raise TelegramError('Invalid SSL Certificate') from exc
        else:
            ssl_ctx = None

        # Create and start server
        self.httpd = WebhookServer(listen, port, app, ssl_ctx)

        if use_ssl:
            # 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(force_event_loop=force_event_loop, ready=ready)
Пример #5
0
def main():
    bot = Bot(BOT_TOKEN)
    dp = Dispatcher(bot, None, 0)
    set_handlers(dp)
    update_queue = Queue()

    httpd = WebhookServer(('127.0.0.1', WEBHOOK_PORT), WebhookHandler,
                          update_queue, WEBHOOK_URI, bot)

    while True:
        try:
            httpd.handle_request()
            if not update_queue.empty():
                update = update_queue.get()
                dp.process_update(update)
        except KeyboardInterrupt:
            exit(0)
Пример #6
0
    def _start_webhook(self, listen, port, url_path, cert, key,
                       bootstrap_retries, 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)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._set_webhook(webhook_url, bootstrap_retries, open(cert, 'rb'))

        self.httpd.serve_forever(poll_interval=1)
Пример #7
0
    def _start_webhook(self, host, port, cert, key, listen):
        self.logger.info('Updater thread started')
        url_base = "https://%s:%d" % (host, port)
        url_path = "/%s" % self.bot.token

        # Remove webhook
        self.bot.setWebhook(webhook_url=None)

        # Set webhook
        self.bot.setWebhook(webhook_url=url_base + url_path,
                            certificate=open(cert, 'rb'))

        # Start server
        self.httpd = WebhookServer((listen, port), WebhookHandler,
                                   self.update_queue, url_path)

        # Check SSL-Certificate with openssl, if possible
        try:
            DEVNULL = open(os.devnull, 'wb')
            exit_code = subprocess.call(
                ["openssl", "x509", "-text", "-noout", "-in", cert],
                stdout=DEVNULL,
                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)
                self.httpd.serve_forever(poll_interval=1)
            except ssl.SSLError as error:
                self.logger.error(str(error))
            finally:
                self.logger.info('Updater thread stopped')
        else:
            raise TelegramError('SSL Certificate invalid')
Пример #8
0
 def _start_api(self, listen, api_port, api_key, api_db, msg_ipc_receivers):
     app = ApiAppClass("/api", self.bot, self.update_queue, api_key, api_db,
                       msg_ipc_receivers)
     asyncio.set_event_loop(asyncio.new_event_loop())
     self.httpapi = WebhookServer(api_port, app, None)
     self.httpapi.serve_forever()
Пример #9
0
 def __init__(self, bot):
     super().__init__()
     app = make_app(bot)
     # TODO enter setting
     self.webhooks = WebhookServer("0.0.0.0", 8888, app, None)