Exemplo n.º 1
0
    def process_update(self, update: Union[str, Update,
                                           TelegramError]) -> None:
        """Processes a single update.

        Args:
            update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`):
                The update to process.

        """

        # An error happened while polling
        if isinstance(update, TelegramError):
            try:
                self.dispatch_error(None, update)
            except Exception:
                self.logger.exception(
                    'An uncaught error was raised while handling the error.')
            return

        context = None

        for group in self.groups:
            try:
                for handler in self.handlers[group]:
                    check = handler.check_update(update)
                    if check is not None and check is not False:
                        if not context and self.use_context:
                            context = CallbackContext.from_update(update, self)
                        handler.handle_update(update, self, check, context)

                        # If handler runs async updating immediately doesn't make sense
                        if not handler.run_async:
                            self.update_persistence(update=update)
                        break

            # Stop processing with any other handler.
            except DispatcherHandlerStop:
                self.logger.debug(
                    'Stopping further handlers due to DispatcherHandlerStop')
                self.update_persistence(update=update)
                break

            # Dispatch any error.
            except Exception as e:
                try:
                    self.dispatch_error(update, e)
                except DispatcherHandlerStop:
                    self.logger.debug('Error handler stopped further handlers')
                    break
                # Errors should not stop the thread.
                except Exception:
                    self.logger.exception(
                        'An uncaught error was raised while handling the error.'
                    )
Exemplo n.º 2
0
    def handle_update(self, update, dispatcher, check_result):
        """
        This method is called if it was determined that an update should indeed
        be handled by this instance. Calls :attr:`self.callback` along with its respectful
        arguments. To work with the :class:`telegram.ext.ConversationHandler`, this method
        returns the value returned from ``self.callback``.
        Note that it can be overridden if needed by the subclassing handler.

        Args:
            update (:obj:`str` | :class:`telegram.Update`): The update to be handled.
            dispatcher (:class:`telegram.ext.Dispatcher`): The calling dispatcher.
            check_result: The result from :attr:`check_update`.

        """
        if dispatcher.use_context:
            context = CallbackContext.from_update(update, dispatcher)
            self.collect_additional_context(context, update, dispatcher, check_result)
            return self.callback(update, context)
        else:
            optional_args = self.collect_optional_args(dispatcher, update, check_result)
            return self.callback(dispatcher.bot, update, **optional_args)
Exemplo n.º 3
0
    def process_update(self, update):
        """Processes a single update.

        Args:
            update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`):
                The update to process.

        """
        def persist_update(update):
            """Persist a single update.

            Args:
            update (:class:`telegram.Update`):
                The update to process.

            """
            if self.persistence and isinstance(update, Update):
                if self.persistence.store_bot_data:
                    try:
                        self.persistence.update_bot_data(self.bot_data)
                    except Exception as e:
                        try:
                            self.dispatch_error(update, e)
                        except Exception:
                            message = 'Saving bot data raised an error and an ' \
                                      'uncaught error was raised while handling ' \
                                      'the error with an error_handler'
                            self.logger.exception(message)
                if self.persistence.store_chat_data and update.effective_chat:
                    chat_id = update.effective_chat.id
                    try:
                        self.persistence.update_chat_data(
                            chat_id, self.chat_data[chat_id])
                    except Exception as e:
                        try:
                            self.dispatch_error(update, e)
                        except Exception:
                            message = 'Saving chat data raised an error and an ' \
                                      'uncaught error was raised while handling ' \
                                      'the error with an error_handler'
                            self.logger.exception(message)
                if self.persistence.store_user_data and update.effective_user:
                    user_id = update.effective_user.id
                    try:
                        self.persistence.update_user_data(
                            user_id, self.user_data[user_id])
                    except Exception as e:
                        try:
                            self.dispatch_error(update, e)
                        except Exception:
                            message = 'Saving user data raised an error and an ' \
                                      'uncaught error was raised while handling ' \
                                      'the error with an error_handler'
                            self.logger.exception(message)

        # An error happened while polling
        if isinstance(update, TelegramError):
            try:
                self.dispatch_error(None, update)
            except Exception:
                self.logger.exception(
                    'An uncaught error was raised while handling the error')
            return

        context = None

        for group in self.groups:
            try:
                for handler in self.handlers[group]:
                    check = handler.check_update(update)
                    if check is not None and check is not False:
                        if not context and self.use_context:
                            context = CallbackContext.from_update(update, self)
                        handler.handle_update(update, self, check, context)
                        persist_update(update)
                        break

            # Stop processing with any other handler.
            except DispatcherHandlerStop:
                self.logger.debug(
                    'Stopping further handlers due to DispatcherHandlerStop')
                persist_update(update)
                break

            # Dispatch any error.
            except Exception as e:
                try:
                    self.dispatch_error(update, e)
                except DispatcherHandlerStop:
                    self.logger.debug('Error handler stopped further handlers')
                    break
                # Errors should not stop the thread.
                except Exception:
                    self.logger.exception(
                        'An error was raised while processing the update and an '
                        'uncaught error was raised while handling the error '
                        'with an error_handler')
Exemplo n.º 4
0
    def process_update(self, update: object) -> None:
        """Processes a single update and updates the persistence.

        Note:
            If the update is handled by least one synchronously running handlers (i.e.
            ``run_async=False``), :meth:`update_persistence` is called *once* after all handlers
            synchronous handlers are done. Each asynchronously running handler will trigger
            :meth:`update_persistence` on its own.

        Args:
            update (:class:`telegram.Update` | :obj:`object` | \
                :class:`telegram.error.TelegramError`):
                The update to process.

        """

        # An error happened while polling
        if isinstance(update, TelegramError):
            try:
                self.dispatch_error(None, update)
            except Exception:
                self.logger.exception(
                    'An uncaught error was raised while handling the error.')
            return

        context = None
        handled = False
        sync_modes = []

        for group in self.groups:
            try:
                for handler in self.handlers[group]:
                    check = handler.check_update(update)
                    if check is not None and check is not False:
                        if not context and self.use_context:
                            context = CallbackContext.from_update(update, self)
                        handled = True
                        sync_modes.append(handler.run_async)
                        handler.handle_update(update, self, check, context)
                        break

            # Stop processing with any other handler.
            except DispatcherHandlerStop:
                self.logger.debug(
                    'Stopping further handlers due to DispatcherHandlerStop')
                self.update_persistence(update=update)
                break

            # Dispatch any error.
            except Exception as exc:
                try:
                    self.dispatch_error(update, exc)
                except DispatcherHandlerStop:
                    self.logger.debug('Error handler stopped further handlers')
                    break
                # Errors should not stop the thread.
                except Exception:
                    self.logger.exception(
                        'An uncaught error was raised while handling the error.'
                    )

        # Update persistence, if handled
        handled_only_async = all(sync_modes)
        if handled:
            # Respect default settings
            if all(mode is DEFAULT_FALSE
                   for mode in sync_modes) and self.bot.defaults:
                handled_only_async = self.bot.defaults.run_async
            # If update was only handled by async handlers, we don't need to update here
            if not handled_only_async:
                self.update_persistence(update=update)
Exemplo n.º 5
0
def call_handler(updater, handler, message):
    update = Update(update_id=1, message=message)
    context = CallbackContext.from_update(update, updater.dispatcher)
    return handler(update, context)