Beispiel #1
0
 def create(self):
     logging.info('Creating new download message')
     promise = Promise(self.bot.sendMessage,
                       args=(
                           self.chat_id,
                           self._get_new_text(),
                       ),
                       kwargs={
                           "disable_notification": True,
                           "parse_mode": "markdown",
                       })
     self.message_queue(promise)
     try:
         self.message_id = promise.result().message_id
     except telegram.error.TimedOut:
         logging.warning("Timeout when creating a new download message")
Beispiel #2
0
 def async_func(*args, **kwargs):
     """
     A wrapper to run a function in a thread
     """
     promise = Promise(func, args, kwargs)
     ASYNC_QUEUE.put(promise)
     return promise
Beispiel #3
0
 def delete(self):
     promise = Promise(self.bot.deleteMessage,
                       args=(),
                       kwargs={
                           "chat_id": self.chat_id,
                           "message_id": self.message_id
                       })
     self.message_queue(promise, is_group_msg=True)
Beispiel #4
0
 def update(self):
     self.torrent.update()
     promise = Promise(self.bot.editMessageText,
                       args=(self._get_new_text(), ),
                       kwargs={
                           "chat_id": self.chat_id,
                           "message_id": self.message_id,
                           "parse_mode": "markdown",
                       })
     self.message_queue(promise, is_group_msg=True)
     try:
         promise.result()
     except telegram.error.BadRequest as bad_request:
         if bad_request.message == 'Message to edit not found':
             raise MessageNotFound(bad_request.message)
         logging.warning(bad_request)
     except telegram.error.TimedOut:
         logging.warning('Timeout when editing message')
Beispiel #5
0
 def _run_async(self,
                func: Callable[..., Any],
                *args: Any,
                update: HandlerArg = None,
                error_handling: bool = True,
                **kwargs: Any) -> Promise:
     # TODO: Remove error_handling parameter once we drop the @run_async decorator
     promise = Promise(func, args, kwargs, update=update, error_handling=error_handling)
     self.__async_queue.put(promise)
     return promise
Beispiel #6
0
 def wrapped(self: 'Bot', *args: Any, **kwargs: Any) -> Any:
     # pylint: disable=W0212
     queued = kwargs.pop(
         'queued', self._is_messages_queued_default  # type: ignore[attr-defined]
     )
     isgroup = kwargs.pop('isgroup', False)
     if queued:
         prom = Promise(method, (self,) + args, kwargs)
         return self._msg_queue(prom, isgroup)  # type: ignore[attr-defined]
     return method(self, *args, **kwargs)
 def _run_async(self,
                func,
                *args,
                update=None,
                error_handling=True,
                **kwargs):
     # TODO: Remove error_handling parameter once we drop the @run_async decorator
     promise = Promise(func,
                       args,
                       kwargs,
                       update=update,
                       error_handling=error_handling)
     self.__async_queue.put(promise)
     return promise
Beispiel #8
0
    def run_async(self, func, *args, **kwargs):
        """Queue a function (with given args/kwargs) to be run asynchronously.

        Args:
            func (function): The function to run in the thread.
            args (Optional[tuple]): Arguments to `func`.
            kwargs (Optional[dict]): Keyword arguments to `func`.

        Returns:
            Promise

        """
        # TODO: handle exception in async threads
        #       set a threading.Event to notify caller thread
        promise = Promise(func, args, kwargs)
        self.__async_queue.put(promise)
        return promise
    def run_async(self, func, *args, **kwargs):
        """Queue a function (with given args/kwargs) to be run asynchronously.

        Warning:
            If you're using @run_async you cannot rely on adding custom attributes to
            :class:`telegram.ext.CallbackContext`. See its docs for more info.

        Args:
            func (:obj:`callable`): The function to run in the thread.
            *args (:obj:`tuple`, optional): Arguments to `func`.
            **kwargs (:obj:`dict`, optional): Keyword arguments to `func`.

        Returns:
            Promise

        """
        # TODO: handle exception in async threads
        #       set a threading.Event to notify caller thread
        promise = Promise(func, args, kwargs)
        self.__async_queue.put(promise)
        return promise
Beispiel #10
0
 def send_photo(self, *args, **kwargs):
     is_group = kwargs.get('chat_id', 0) >= 0
     return self._message_queue(Promise(super().send_photo, args, kwargs),
                                is_group)
    def reverse_image_search(
        self, bot: Bot, update: Update, media_file: str, message: Promise = None
    ):
        """Send a reverse image search link for the image sent to us

        Args:
            bot (:obj:`telegram.bot.Bot`): Telegram Api Bot Object.
            update (:obj:`telegram.update.Update`): Telegram Api Update Object
            media_file (:obj:`str`): Path to file to search for
            message (:obj:`telegram.message.Message`, optional): An message object to update. Instead of sending a new
        """

        image_extension = os.path.splitext(media_file)[1]
        image_name = "irs-" + str(uuid4())[:8]

        (
            iqdb_search,
            google_search,
            tineye_search,
            bing_search,
            yandex_search,
            saucenao_search,
            trace_search,
        ) = (
            IQDBReverseImageSearchEngine(),
            GoogleReverseImageSearchEngine(),
            TinEyeReverseImageSearchEngine(),
            BingReverseImageSearchEngine(),
            YandexReverseImageSearchEngine(),
            SauceNaoReverseImageSearchEngine(),
            TraceReverseImageSearchEngine(),
        )

        image_url = iqdb_search.upload_image(
            media_file, image_name + image_extension, remove_after=3600
        )

        if os.path.isfile(image_url):
            reply = "This bot is not configured for this functionality, contact an admin for more information /support."
            message = message.result()
            if message:
                message.edit_text(reply, reply_to_message_id=update.message.message_id)
            else:
                update.message.reply_text(
                    reply, reply_to_message_id=update.message.message_id
                )
            return

        button_list = [
            [InlineKeyboardButton(text="Go To Image", url=image_url)],
            [
                iqdb_search.button(image_url),
                saucenao_search.button(image_url),
            ],
            [
                google_search.button(image_url),
                yandex_search.button(image_url),
            ],
            [
                bing_search.button(image_url),
                trace_search.button(image_url),
            ],
            [
                tineye_search.button(image_url),
            ],
        ]

        reply = (
            "Tap on the search engine of your choice. For an even better experience with more search providers and"
            " in telegram search results use @reverse_image_search_bot."
        )
        reply_markup = InlineKeyboardMarkup(button_list)

        message = message.result()
        if message:
            bot.edit_message_text(
                chat_id=update.message.chat_id,
                message_id=message.message_id,
                text=reply,
                reply_markup=reply_markup,
            )
        else:
            update.message.reply_text(text=reply, reply_markup=reply_markup)
Beispiel #12
0
    def reverse_image_search(self,
                             bot: Bot,
                             update: Update,
                             media_file: str,
                             message: Promise = None):
        """Send a reverse image search link for the image sent to us

        Args:
            bot (:obj:`telegram.bot.Bot`): Telegram Api Bot Object.
            update (:obj:`telegram.update.Update`): Telegram Api Update Object
            media_file (:obj:`str`): Path to file to search for
            message (:obj:`telegram.message.Message`, optional): An message object to update. Instead of sending a new
        """

        image_extension = os.path.splitext(media_file)[1]
        image_name = 'irs-' + str(uuid4())[:8]

        iqdb_search, google_search, tineye_search, bing_search, yandex_search = (
            IQDBReverseImageSearchEngine(), GoogleReverseImageSearchEngine(),
            TinEyeReverseImageSearchEngine(), BingReverseImageSearchEngine(),
            YandexReverseImageSearchEngine())

        image_url = iqdb_search.upload_image(media_file,
                                             image_name + image_extension,
                                             remove_after=3600)

        if os.path.isfile(image_url):
            reply = 'This bot is not configured for this functionality, contact an admin for more information /support.'
            message = message.result()
            if message:
                message.edit_text(
                    reply, reply_to_message_id=update.message.message_id)
            else:
                update.message.reply_text(
                    reply, reply_to_message_id=update.message.message_id)
            return

        iqdb_url, google_url, tineye_url, bing_url, yandex_url = (
            iqdb_search.get_search_link_by_url(image_url),
            google_search.get_search_link_by_url(image_url),
            tineye_search.get_search_link_by_url(image_url),
            bing_search.get_search_link_by_url(image_url),
            yandex_search.get_search_link_by_url(image_url))

        button_list = [[
            InlineKeyboardButton(text='Go To Image', url=image_url)
        ],
                       [
                           InlineKeyboardButton(text='IQDB', url=iqdb_url),
                           InlineKeyboardButton(text='GOOGLE', url=google_url),
                       ],
                       [
                           InlineKeyboardButton(text='YANDEX', url=yandex_url),
                           InlineKeyboardButton(text='BING', url=bing_url),
                       ],
                       [
                           InlineKeyboardButton(text='TINEYE', url=tineye_url),
                       ]]

        reply = 'Tap on the search engine of your choice.'
        reply_markup = InlineKeyboardMarkup(button_list)

        message = message.result()
        if message:
            bot.edit_message_text(chat_id=update.message.chat_id,
                                  message_id=message.message_id,
                                  text=reply,
                                  reply_markup=reply_markup)
        else:
            update.message.reply_text(text=reply, reply_markup=reply_markup)
Beispiel #13
0
 def result(promise: Promise, type: Type[TP]) -> TP:
     return promise.result()