Esempio n. 1
0
    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]"""
Esempio n. 2
0
    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]"""
Esempio n. 3
0
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:
            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_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False):
        """
        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
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting the webhook. 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_webhook, "updater", listen,
                                  port, url_path, cert, key)

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

    def _start_polling(self, poll_interval, timeout, network_delay):
        """
        Thread target of thread 'updater'. Runs in background, pulls
        updates from Telegram and inserts them in the update queue of the
        Dispatcher.
        """

        cur_interval = poll_interval
        self.logger.info('Updater thread started')

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

        while self.running:
            try:
                updates = self.bot.getUpdates(self.last_update_id,
                                              timeout=timeout,
                                              network_delay=network_delay)
            except TelegramError as te:
                self.logger.error(
                    "Error while getting Updates: {0}".format(te))

                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)

                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                if not self.running:
                    if len(updates) > 0:
                        self.logger.info('Updates ignored and will be pulled '
                                         'again on restart.')
                    break

                if updates:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

                cur_interval = poll_interval

            sleep(cur_interval)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        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):
        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 '
                'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug("Requesting Dispatcher to stop...")
        self.dispatcher.stop()

    def _join_async_threads(self):
        with dispatcher.async_lock:
            threads = list(dispatcher.async_threads)
        total = len(threads)
        for i, thr in enumerate(threads):
            self.logger.info(
                'Waiting for async thread {0}/{1} to end'.format(i, total))
            thr.join()
            self.logger.debug(
                'async thread {0}/{1} has ended'.format(i, total))

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.info(
                'Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

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

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """
        Blocks until one of the signals are received 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. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
 def setUp(self):
     self.jq = JobQueue("Bot", tick_interval=0.005)
     self.result = 0
Esempio n. 5
0
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:
            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_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False):
        """
        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
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting the webhook. 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_webhook, "updater", listen, port,
                                  url_path, cert, key)

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

    def _start_polling(self, poll_interval, timeout, network_delay):
        """
        Thread target of thread 'updater'. Runs in background, pulls
        updates from Telegram and inserts them in the update queue of the
        Dispatcher.
        """

        cur_interval = poll_interval
        self.logger.info('Updater thread started')

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

        while self.running:
            try:
                updates = self.bot.getUpdates(self.last_update_id,
                                              timeout=timeout,
                                              network_delay=network_delay)
            except TelegramError as te:
                self.logger.error(
                    "Error while getting Updates: {0}".format(te))

                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)

                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                if not self.running:
                    if len(updates) > 0:
                        self.logger.info('Updates ignored and will be pulled '
                                         'again on restart.')
                    break

                if updates:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

                cur_interval = poll_interval

            sleep(cur_interval)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        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):
        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 '
                'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug("Requesting Dispatcher to stop...")
        self.dispatcher.stop()

    def _join_async_threads(self):
        with dispatcher.async_lock:
            threads = list(dispatcher.async_threads)
        total = len(threads)
        for i, thr in enumerate(threads):
            self.logger.info('Waiting for async thread {0}/{1} to end'.format(
                i, total))
            thr.join()
            self.logger.debug('async thread {0}/{1} has ended'.format(
                i, total))

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.info('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

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

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """
        Blocks until one of the signals are received 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. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
class JobQueueTest(BaseTest, unittest.TestCase):
    """
    This object represents Tests for Updater, Dispatcher, WebhookServer and
    WebhookHandler
    """
    def setUp(self):
        self.jq = JobQueue("Bot", tick_interval=0.005)
        self.result = 0

    def tearDown(self):
        if self.jq is not None:
            self.jq.stop()

    def job1(self, bot):
        self.result += 1

    def job2(self, bot):
        raise Exception("Test Error")

    def test_basic(self):
        print('Testing basic job queue function')
        self.jq.put(self.job1, 0.1)
        sleep(1.5)
        self.assertGreaterEqual(self.result, 10)

    def test_noRepeat(self):
        print('Testing job queue without repeat')
        self.jq.put(self.job1, 0.1, repeat=False)
        sleep(0.5)
        self.assertEqual(1, self.result)

    def test_nextT(self):
        print('Testing job queue with a set next_t value')
        self.jq.put(self.job1, 0.1, next_t=0.5)
        sleep(0.45)
        self.assertEqual(0, self.result)
        sleep(0.1)
        self.assertEqual(1, self.result)

    def test_multiple(self):
        print('Testing job queue with multiple jobs')
        self.jq.put(self.job1, 0.1, repeat=False)
        self.jq.put(self.job1, 0.2, repeat=False)
        self.jq.put(self.job1, 0.4)
        sleep(1)
        self.assertEqual(4, self.result)

    def test_error(self):
        print('Testing job queue starting twice with an erroneous job')
        self.jq.put(self.job2, 0.1)
        self.jq.put(self.job1, 0.2)
        self.jq.start()
        sleep(0.4)
        self.assertEqual(1, self.result)

    def test_inUpdater(self):
        print('Testing job queue created by updater')
        u = Updater(bot="MockBot", job_queue_tick_interval=0.005)
        u.job_queue.put(self.job1, 0.1)
        sleep(0.15)
        self.assertEqual(1, self.result)
        u.stop()
        sleep(0.4)
        self.assertEqual(1, self.result)
Esempio n. 7
0
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]):

    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.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
        self.__lock = Lock()

    def start_polling(self, poll_interval=0.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 0.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
        """

        with self.__lock:
            if not self.running:
                self.running = True

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

                # Start threads
                dispatcher_thread.start()
                updater_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
        """

        with self.__lock:
            if not self.running:
                self.running = True

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

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

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

    def _start_polling(self, poll_interval, timeout, network_delay):
        """
        Thread target of thread 'updater'. Runs in background, pulls
        updates from Telegram and inserts them in the update queue of the
        Dispatcher.
        """

        current_interval = poll_interval
        self.logger.info('Updater thread started')

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

        while self.running:
            try:
                updates = self.bot.getUpdates(self.last_update_id,
                                              timeout=timeout,
                                              network_delay=network_delay)
                if not self.running:
                    if len(updates) > 0:
                        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)

            except URLError as e:
                self.logger.error("Error while getting Updates: %s" % e)
                # increase waiting times on subsequent errors up to 30secs
                if current_interval == 0:
                    current_interval = 1
                elif current_interval < 30:
                    current_interval += current_interval / 2
                elif 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, the dispatcher and the job queue
        """

        self.job_queue.stop()
        with self.__lock:
            if self.running:
                self.running = False
                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.')

                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)):
        """
        Blocks until one of the signals are received 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. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
Esempio n. 8
0
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]):

    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 = Queue()
        self.job_queue = JobQueue(self.bot, job_queue_tick_interval)
        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
        self.__lock = Lock()

    def start_polling(self, poll_interval=0.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 0.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
        """

        with self.__lock:
            if not self.running:
                self.running = True

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

                # Start threads
                dispatcher_thread.start()
                updater_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
        """

        with self.__lock:
            if not self.running:
                self.running = True

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

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

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

    def _start_polling(self, poll_interval, timeout, network_delay):
        """
        Thread target of thread 'updater'. Runs in background, pulls
        updates from Telegram and inserts them in the update queue of the
        Dispatcher.
        """

        current_interval = poll_interval
        self.logger.info('Updater thread started')

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

        while self.running:
            try:
                updates = self.bot.getUpdates(self.last_update_id,
                                              timeout=timeout,
                                              network_delay=network_delay)
                if not self.running:
                    if len(updates) > 0:
                        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)

            except URLError as e:
                self.logger.error("Error while getting Updates: %s" % e)
                # increase waiting times on subsequent errors up to 30secs
                if current_interval == 0:
                    current_interval = 1
                elif current_interval < 30:
                    current_interval += current_interval / 2
                elif 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, the dispatcher and the job queue
        """

        self.job_queue.stop()
        with self.__lock:
            if self.running:
                self.running = False
                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.')

                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)):
        """
        Blocks until one of the signals are received 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. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
 def setUp(self):
     self.jq = JobQueue("Bot", tick_interval=0.005)
     self.result = 0
Esempio n. 10
0
class JobQueueTest(BaseTest, unittest.TestCase):
    """
    This object represents Tests for Updater, Dispatcher, WebhookServer and
    WebhookHandler
    """

    def setUp(self):
        self.jq = JobQueue("Bot", tick_interval=0.005)
        self.result = 0

    def tearDown(self):
        if self.jq is not None:
            self.jq.stop()

    def job1(self, bot):
        self.result += 1

    def job2(self, bot):
        raise Exception("Test Error")

    def test_basic(self):
        print('Testing basic job queue function')
        self.jq.put(self.job1, 0.1)
        sleep(1.5)
        self.assertGreaterEqual(self.result, 10)

    def test_noRepeat(self):
        print('Testing job queue without repeat')
        self.jq.put(self.job1, 0.1, repeat=False)
        sleep(0.5)
        self.assertEqual(1, self.result)

    def test_nextT(self):
        print('Testing job queue with a set next_t value')
        self.jq.put(self.job1, 0.1, next_t=0.5)
        sleep(0.45)
        self.assertEqual(0, self.result)
        sleep(0.1)
        self.assertEqual(1, self.result)

    def test_multiple(self):
        print('Testing job queue with multiple jobs')
        self.jq.put(self.job1, 0.1, repeat=False)
        self.jq.put(self.job1, 0.2, repeat=False)
        self.jq.put(self.job1, 0.4)
        sleep(1)
        self.assertEqual(4, self.result)

    def test_error(self):
        print('Testing job queue starting twice with an erroneous job')
        self.jq.put(self.job2, 0.1)
        self.jq.put(self.job1, 0.2)
        self.jq.start()
        sleep(0.4)
        self.assertEqual(1, self.result)

    def test_inUpdater(self):
        print('Testing job queue created by updater')
        u = Updater(bot="MockBot", job_queue_tick_interval=0.005)
        u.job_queue.put(self.job1, 0.1)
        sleep(0.15)
        self.assertEqual(1, self.result)
        u.stop()
        sleep(0.4)
        self.assertEqual(1, self.result)