Exemplo n.º 1
0
def main():
    bot = TeleBot(config.BotToken)
    list_of_hashes = ListOfHashes(config.FileWithListOfHashesOfImages)
    while True:
        list_of_images_for_post = get_names_of_not_posted_images(
            list_of_hashes)
        for image_name in list_of_images_for_post:
            try:
                path_to_image = config.DirectoryWithImages + '\\' + image_name
                image_for_post = open(path_to_image, 'rb')
                bot.send_chat_action(config.ChanelId, 'upload_photo')
                bot.send_photo(config.ChanelId, image_for_post)
                image_for_post.close()
            except:
                print('Error In Main')
Exemplo n.º 2
0
def form_and_send_new_cv_archive(bot: TeleBot, user: User):
    UPDATE_INTERVAL = 1  # minutes
    ejf = JobFair.objects.first()
    chat_id = user.chat_id

    # update archive only once in 10 min
    archive_last_update = ejf.cv_archive_last_update
    if archive_last_update:
        date_diff = (user.last_interaction_date -
                     archive_last_update).total_seconds() / 60.0
        if date_diff < UPDATE_INTERVAL:
            bot.send_message(
                chat_id,
                text=f"Почекай ще {UPDATE_INTERVAL-date_diff:.2f} хвилин...",
            )
            return

    # clear archives list
    ejf.cv_archive_file_id_list = list()

    for temp_archive_path in _form_max_size_archive(bot):
        # show sending document
        bot.send_chat_action(chat_id, action="upload_document")

        # send archive
        with open(temp_archive_path, "rb") as archive:
            message = bot.send_document(chat_id, archive)

        # update db info
        ejf.cv_archive_file_id_list += [message.document.file_id]

        # delete archive
        os.remove(temp_archive_path)

    # update db info
    ejf.cv_archive_size = User.objects.filter(cv_file_id__ne=None).count()
    ejf.cv_archive_last_update = user.last_interaction_date
    ejf.save()
Exemplo n.º 3
0

def get_price(hash_name):
    try:
        response = requests.get(
            'https://steamcommunity.com/market/priceoverview/?appid=730&country=US&currency=1&market_hash_name='
            + hash_name,
            proxies=proxy)
        return response.json()['lowest_price']
    except Exception as e:
        print('error passed', e)


os.system('cls')
while True:
    tb.send_chat_action(chat_id, 'typing')
    try:
        response = requests.get(
            'https://steamcommunity.com/market/recent?country=RU&language=russian&currency=1',
            proxies=proxy)
    except Exception as e:
        print('error passed', e)
        continue
    response_json = response.json()
    if not response_json:
        sleep(sleep_time)
        print('Blocked')
        continue
    contexts = response_json.get('assets', {}).get('730', {})
    for context in contexts:
        for item_id, item in contexts[context].items():
Exemplo n.º 4
0
class ArticleBot:
    def __init__(self, token: str, database: Database,
                 requests_session: Session, translate: dict) -> None:
        self.bot = TeleBot(token)
        self.requests_session = requests_session
        self.translate = translate['translate']
        self.translate_language = translate['to']
        self.translator = translate['translator']
        self.translate_links = translate['translate_links']
        self.database = database

    def _send_separator(self, chat_id: Union[int, str],
                        article_id: str) -> None:
        logger.debug('Bot: User {0} - {1} - Try to send separator...'.format(
            str(chat_id), article_id))
        self.bot.send_message(chat_id, '-' * 10)
        logger.debug('Bot: User {0} - {1} -  Separator sented'.format(
            str(chat_id), article_id))

    def _send_article_keywords(self, chat_id: Union[int, str],
                               article_match_words: list[str],
                               article_id: str) -> None:
        re_text = 'Ключевые слова:\n' + \
            (', '.join(article_match_words)
                if article_match_words else "Не обнаружено.")

        logger.debug('Bot: User {0} - {1} - Try to send key words...'.format(
            str(chat_id), article_id))
        self.bot.send_message(chat_id, re_text)
        logger.debug('Bot: User {0} - {1} -  Key words sented'.format(
            str(chat_id), article_id))

    def _send_article_translate_link(self, chat_id: Union[int, str],
                                     article_id: str, article_language: str,
                                     article_source: str) -> None:
        translate_link = 'https://translate.google.com/?source=gtx_c#view=home&op=translate&sl={0}&tl={1}&text={2}'.format(
            article_language, self.translate_language,
            urllib.parse.quote(article_source))
        translate_link_text = f'[Перевод статьи на Google Translate]({translate_link})'

        logger.debug(
            'Bot: User {0} - {1} - Try to send translate link...'.format(
                str(chat_id), article_id))
        self.bot.send_message(chat_id,
                              translate_link_text,
                              disable_web_page_preview=True,
                              parse_mode='Markdown')
        logger.debug('Bot: User {0} - {1} -  Translate link sented'.format(
            str(chat_id), article_id))

    def _send_full_article_text(self, chat_id: Union[int, str],
                                article_id: str, text: str) -> None:
        try:
            logger.debug(
                'Bot: User {0} - {1} - Try to send full text message...'.
                format(str(chat_id), article_id))
            self.bot.send_message(chat_id, text, disable_web_page_preview=True)
            logger.debug('Bot: User {0} - {1} - Message sented'.format(
                str(chat_id), article_id))
        except Exception as error:
            logger.exception(error)

    def _send_big_message_parts(self, chat_id: Union[int, str],
                                article_id: str, text: str) -> None:
        message_part = 0
        for x in range(0, len(text), 4096):
            try:
                logger.debug(
                    'Bot: User {0} - {1} - Try to send text message part...'.
                    format(str(chat_id), article_id))
                self.bot.send_message(chat_id,
                                      text[x:x + 4096],
                                      disable_web_page_preview=True)
                logger.debug(
                    'Bot: User {0} - {1} - Message part sented'.format(
                        str(chat_id), article_id))
            except Exception as error:
                logger.exception(error)

            message_part += 1

    def _send_article_images(
            self,
            chat_id: Union[str, int],
            article_id: str,
            images_group: list[InputMediaPhoto],
            forward: bool,
            forward_images_message: Union[None,
                                          list] = None) -> Union[list, None]:
        try:
            if not forward:
                logger.debug('Bot: User {0} - {1} - Try to send photos'.format(
                    str(chat_id), article_id))
                message_to_forward = self.bot.send_media_group(
                    chat_id, images_group)
                logger.debug('Bot: User {0} - {1} - Photos sented'.format(
                    str(chat_id), article_id))
                return message_to_forward
            else:
                logger.debug(
                    'Bot: User {0} - {1} - Try to forward photos'.format(
                        str(chat_id), article_id))
                self.bot.send_media_group(chat_id, [
                    InputMediaPhoto(image.photo[0].file_id)
                    for image in forward_images_message
                ])
                logger.debug('Bot: User {0} - {1} - Photos forwarded'.format(
                    str(chat_id), article_id))
                return None

        except Exception as error:
            logger.exception(error)

    def _translate_article_text(self, article: Article) -> dict:
        translated = {'article_title': None, 'article_text': None}

        if (article.text or article.title) and (
                article.language !=
                self.translate_language) and self.translate:
            try:
                if article.title:
                    translated['article_title'] = self.translator.translate(
                        article.title,
                        '-'.join([article.language,
                                  self.translate_language]))['text'][0]
                if article.text:
                    translated['article_text'] = self.translator.translate(
                        article.text,
                        '-'.join([article.language,
                                  self.translate_language]))['text'][0]
            except:
                logger.debug(
                    f'Bot: Article {article.id} - Can"t translate text using Yandex.Translate'
                )

        return translated

    def send_article(self, article: Article) -> int:
        current_users = self.database.get_users_list()
        if not current_users:
            return 1

        logger.info('Bot: {0} - Try to send article to all users...'.format(
            article.id))
        images_to_send = []

        for image_link in tools.delete_duplicates([article.main_image_link] +
                                                  article.article_images)[:7]:
            if image_link:
                images_to_send.append(InputMediaPhoto(image_link))

        translated = self._translate_article_text(article)

        if not self.translate or (article.language == self.translate_language):
            article_title = article.title
            article_text = article.text
        else:
            article_title = translated['article_title'] or article.title
            article_text = translated['article_text'] or article.text

        text = 'Источник: {2} {3}\n\nДата публикации: {1}\n\n{0}\n\n{4}'.format(
            article_title, article.publish_date, article.source_name,
            article.source, article_text)

        is_forward = False
        message_to_forward = None

        for user_id in current_users:
            try:
                self.bot.send_chat_action(user_id, 'typing')
            except apihelper.ApiTelegramException:
                current_users.remove(user_id)
                logger.warning(
                    'Bot: User {user_id} has been removed from subs')
                continue

            self._send_separator(chat_id=user_id, article_id=article.id)

            if article.send_key_words:
                self._send_article_keywords(
                    chat_id=user_id,
                    article_match_words=article.match_words,
                    article_id=article.id)

            if self.translate_links and (article.language !=
                                         self.translate_language):
                self._send_article_translate_link(
                    chat_id=user_id,
                    article_id=article.id,
                    article_language=article.language,
                    article_source=article.source)

            if len(text) > 4096:
                self._send_big_message_parts(chat_id=user_id,
                                             article_id=article.id,
                                             text=text)
            else:
                self._send_full_article_text(chat_id=user_id,
                                             article_id=article.id,
                                             text=text)
            if images_to_send:
                self.bot.send_chat_action(user_id, 'upload_photo')

                if not is_forward:
                    is_forward = True
                    message_to_forward = self._send_article_images(
                        chat_id=user_id,
                        article_id=article.id,
                        images_group=images_to_send,
                        forward=False)
                else:
                    self._send_article_images(
                        chat_id=user_id,
                        article_id=article.id,
                        images_group=images_to_send,
                        forward=True,
                        forward_images_message=message_to_forward)

            logger.info(f'Bot: {article.id} - Article sent to user {user_id}')

        return 0