• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python webhookhandler.WebhookServer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _start_webhook

    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)
开发者ID:Suyashc1295,项目名称:python-telegram-bot,代码行数:32,代码来源:updater.py


示例2: _start_webhook

    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)
开发者ID:noam09,项目名称:deluge-telegramer,代码行数:29,代码来源:updater.py


示例3: _start_webhook

    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)
开发者ID:JacyNewbs,项目名称:python-telegram-bot,代码行数:21,代码来源:updater.py


示例4: _start_webhook

    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')
开发者ID:gvaldez81,项目名称:python-telegram-bot,代码行数:39,代码来源:updater.py


示例5: Updater

class Updater(object):
    """
    This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to
    :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to
    receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a
    separate thread, so the user can interact with the bot, for example on the command line. The
    dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types. The updater can be started as a polling service or, for
    production, use a webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        user_sig_handler (:obj:`signal`): signals the updater will respond to.
        update_queue (:obj:`Queue`): Queue for the updates.
        job_queue (:class:`telegram.ext.JobQueue`): Jobqueue for the updater.
        dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that handles the updates and
            dispatches them to the handlers.
        running (:obj:`bool`): Indicates if the updater is running.

    Args:
        token (:obj:`str`, optional): The bot's token given by the @BotFather.
        base_url (:obj:`str`, optional): Base_url for the bot.
        workers (:obj:`int`, optional): Amount of threads in the thread pool for functions
            decorated with ``@run_async``.
        bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance. If a pre-initialized
            bot is used, it is the user's responsibility to create it using a `Request`
            instance with a large enough connection pool.
        user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
            arguments. This will be called when a signal is received, defaults are (SIGINT,
            SIGTERM, SIGABRT) setable with :attr:`idle`.
        request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a request
            object (ignored if `bot` argument is used).

    Note:
        You must supply either a :attr:`bot` or a :attr:`token` argument.

    Raises:
        ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.

    """

    _request = None

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 user_sig_handler=None,
                 request_kwargs=None):

        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        con_pool_size = workers + 4

        if bot is not None:
            self.bot = bot
            if bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            if request_kwargs is None:
                request_kwargs = {}
            if 'con_pool_size' not in request_kwargs:
                request_kwargs['con_pool_size'] = con_pool_size
            self._request = Request(**request_kwargs)
            self.bot = Bot(token, base_url, request=self._request)
        self.user_sig_handler = user_sig_handler
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
#.........这里部分代码省略.........
开发者ID:noam09,项目名称:deluge-telegramer,代码行数:101,代码来源:updater.py


示例6: token

class Updater:
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. It's
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]):
        job_queue_tick_interval(Optional[float]): The interval the queue should
            be checked for new tasks. Defaults to 1.0

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.
    """

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 job_queue_tick_interval=1.0):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            self.bot = Bot(token, base_url)
        self.update_queue = UpdateQueue()
        self.job_queue = JobQueue(self.bot, job_queue_tick_interval)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(self.bot, self.update_queue, workers,
                                     self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def start_polling(self, poll_interval=0.0, timeout=10, network_delay=2,
                      clean=False):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling
                updates from Telegram in seconds. Default is 0.0
            timeout (Optional[float]): Passed to Bot.getUpdates
            network_delay (Optional[float]): Passed to Bot.getUpdates
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is
                False.

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True
                if clean:
                    self._clean_updates()

                # Create & start threads
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater",
                                  poll_interval, timeout, network_delay)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name,
                     args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
#.........这里部分代码省略.........
开发者ID:Suyashc1295,项目名称:python-telegram-bot,代码行数:101,代码来源:updater.py


示例7: token

class Updater:
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. It's
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (str): The bots token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
    """

    def __init__(self, token, base_url=None, workers=4):

        self.bot = Bot(token, base_url)
        self.update_queue = Queue()
        self.dispatcher = Dispatcher(self.bot, self.update_queue,
                                     workers=workers)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None

    def start_polling(self, poll_interval=1.0, timeout=10, network_delay=2):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling
                updates from Telegram in seconds. Default is 1.0
            timeout (Optional[float]): Passed to Bot.getUpdates
            network_delay (Optional[float]): Passed to Bot.getUpdates

        Returns:
            Queue: The update queue that can be filled from the main thread
        """

        # Create Thread objects
        dispatcher_thread = Thread(target=self.dispatcher.start,
                                   name="dispatcher")
        event_handler_thread = Thread(target=self._start_polling,
                                      name="updater",
                                      args=(poll_interval, timeout,
                                            network_delay))

        self.running = True

        # Start threads
        dispatcher_thread.start()
        event_handler_thread.start()

        # Return the update queue so the main thread can insert updates
        return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (Optional[str]): IP-Address to listen on
            port (Optional[int]): Port the bot should be listening on
            url_path (Optional[str]): Path inside url
            cert (Optional[str]): Path to the SSL certificate file
            key (Optional[str]): Path to the SSL key file

        Returns:
            Queue: The update queue that can be filled from the main thread
        """

        # Create Thread objects
        dispatcher_thread = Thread(target=self.dispatcher.start,
                                   name="dispatcher")
        event_handler_thread = Thread(target=self._start_webhook,
                                      name="updater",
                                      args=(listen, port, url_path, cert, key))

        self.running = True

        # Start threads
#.........这里部分代码省略.........
开发者ID:gisho,项目名称:python-telegram-bot,代码行数:101,代码来源:updater.py


示例8: Updater

class Updater(object):
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. Its
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]): A pre-initialized bot instance. If a pre-initizlied bot is used, it is
            the user's responsibility to create it using a `Request` instance with a large enough
            connection pool.
        job_queue_tick_interval(Optional[float]): The interval the queue should
            be checked for new tasks. Defaults to 1.0

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.

    """
    _request = None

    def __init__(self, token=None, base_url=None, workers=4, bot=None):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            self._request = Request(con_pool_size=workers + 4)
            self.bot = Bot(token, base_url, request=self._request)
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=5.,
                      clean=False,
                      bootstrap_retries=0):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling updates from Telegram in
            seconds. Default is 0.0

            timeout (Optional[float]): Passed to Bot.getUpdates

            network_delay (Optional[float]): Passed to Bot.getUpdates
#.........这里部分代码省略.........
开发者ID:igorcmoura,项目名称:python-telegram-bot,代码行数:101,代码来源:updater.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python timer.delta_sec函数代码示例发布时间:2022-05-27
下一篇:
Python request.post函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap