def on_chosen_inline_query(
            self, client: 'pyrogram.Client',
            chosen_inline_result: 'pyrogram.types.ChosenInlineResult'):
        logger.debug(f"on_chosen_inline_query: {chosen_inline_result}")

        # todo: fix this
        db_from_user = self.db.get_user_by_user_id(
            chosen_inline_result.from_user.id)
        if not db_from_user:
            # update the user
            db_from_user = self.db.update_or_create_user(
                chosen_inline_result.from_user)

        reg = re.search(
            "^#(?P<command>[a-zA-Z0-9_]+)(\s(?P<arg1>[a-zA-Z0-9_]+))?",
            chosen_inline_result.query)
        if reg:
            # it's a custom command
            # todo: handle downloads from commands like `#download_history` in non-private chats
            logger.info(chosen_inline_result)

            button = InlineButton.get_button(reg.group("command"))
            if button:
                button.on_chosen_inline_query(
                    client,
                    chosen_inline_result,
                    self,
                    self.db,
                    self.telegram_client,
                    db_from_user,
                    reg,
                )

        else:
            inline_query_id, audio_key = chosen_inline_result.result_id.split(
                "->")

            db_download = self.db.get_or_create_download_from_chosen_inline_query(
                chosen_inline_result, self.telegram_client.telegram_id)
    def start(self):
        if self._client is None:
            self.init_client()

        logger.info("#" * 50)
        logger.info(self.name)
        logger.info("#" * 50)
        self._client.start()
Ejemplo n.º 3
0
def client_task(task: BaseTask, target_queue: 'Queue'):
    logger.info(f"@pyrogram_task_call: {prettify(task)}")

    # connections
    with Connection(
            config('RABBITMQ_URL'),
            userid=config('RABBITMQ_DEFAULT_USER'),
            password=config('RABBITMQ_DEFAULT_PASS'),
    ) as conn:
        # produce
        producer = conn.Producer(serializer='pickle')
        producer.publish(body=task,
                         exchange=tase_telegram_exchange,
                         routing_key=target_queue.name,
                         declare=[
                             target_queue,
                         ],
                         retry=True,
                         retry_policy={
                             'interval_start': 0,
                             'interval_step': 2,
                             'interval_max': 30,
                             'max_retries': 30,
                         })
Ejemplo n.º 4
0
    def run(self) -> None:
        logger.info(mp.current_process().name)
        logger.info(threading.current_thread())

        self.telegram_client.start()

        me = self.telegram_client.get_me()
        if me:
            self.telegram_client.telegram_id = me.id
            self.db.update_or_create_user(me)

        worker = ClientWorkerThread(
            telegram_client=self.telegram_client,
            index=0,
            db=self.db,
            task_queues=self.task_queues,
        )
        worker.start()

        self.init_handlers()
        self.register_update_handlers()

        idle()
        self.telegram_client.stop()
Ejemplo n.º 5
0
 def bot_message_handler(self, client: 'pyrogram.Client',
                         message: 'pyrogram.types.Message'):
     logger.info(f"bot_message_handler: {message}")
Ejemplo n.º 6
0
    def search_query_handler(self, client: 'pyrogram.Client',
                             message: 'pyrogram.types.Message'):
        logger.info(f"search_query_handler: {message.text}")
        # todo: fix this
        lang_code = message.from_user.language_code

        from_user = message.from_user
        chat = message.chat
        message_date = message.date
        query = message.text

        # update the user
        db_from_user = self.db.update_or_create_user(message.from_user)

        # todo: fix this
        db_from_user = self.db.get_user_by_user_id(message.from_user.id)

        found_any = True
        db_audio_docs = []

        if not query:
            found_any = False
        else:
            db_audio_docs, query_metadata = self.db.search_audio(query,
                                                                 size=10)
            if not db_audio_docs or not len(db_audio_docs) or not len(
                    query_metadata):
                found_any = False

            db_query, db_hits = self.db.get_or_create_query(
                self.telegram_client.telegram_id,
                from_user,
                query,
                query_date=get_timestamp(message.date),
                query_metadata=query_metadata,
                audio_docs=db_audio_docs,
            )

        if found_any:

            def process_item(index, db_audio, db_hit):
                duration = timedelta(seconds=db_audio.duration)
                d = datetime(1, 1, 1) + duration
                _performer = db_audio.performer or ""
                _title = db_audio.title or ""
                _file_name = db_audio.file_name or ""
                if not (len(_title) < 2 or len(_performer) < 2):
                    name = f"{_performer} - {_title}"
                elif not len(_performer) < 2:
                    name = f"{_performer} - {_file_name}"
                else:
                    name = _file_name

                return {
                    'index': f"{index + 1:02}",
                    'name': textwrap.shorten(name, width=35,
                                             placeholder='...'),
                    'file_size': round(db_audio.file_size / 1000_000, 1),
                    'time':
                    f"{str(d.hour) + ':' if d.hour > 0 else ''}{d.minute:02}:{d.second:02}",
                    'url': db_hit.download_url,
                    'sep': f"{40 * '-' if index != 0 else ''}",
                }

            items = [
                process_item(index, db_audio, db_hit)
                for index, (db_audio, db_hit) in reversed(
                    list(enumerate(zip(db_audio_docs, db_hits))))
            ]

            data = QueryResultsData(
                query=query,
                items=items,
                lang_code=db_from_user.chosen_language_code,
            )

            text = BaseTemplate.registry.query_results_template.render(data)
        else:
            text = BaseTemplate.registry.no_results_were_found_template.render(
                NoResultsWereFoundData(
                    query=query,
                    lang_code=db_from_user.chosen_language_code,
                ))

        message.reply_text(
            text=text,
            quote=True,
            parse_mode=ParseMode.HTML,
        )
Ejemplo n.º 7
0
 def wrap(*args, **kwargs):
     try:
         func(*args, **kwargs)
         logger.info(f'Task Finished')
     except Exception as e:
         logger.exception(e)
Ejemplo n.º 8
0
 def on_disconnect(self, client: 'pyrogram.Client'):
     logger.info(f"client {client.name} disconnected @ {arrow.utcnow()}")