コード例 #1
0
def create_custom_message(messager_profile_id, receiver_profile_id,
                          path_to_file):
    """Функция для создания кастомного сообщения. Есть шаблон письма. В нем
    есть ключевые места по тиму {name}
    функция будет заменять эти ключевые слова на собранные данные с
    получателя и отправителя пиьсма

    Keyword arguments:
    messager_profile_id -- ID того кто отправляет
    receiver_profile_id -- ID того кто отправляет
    path_to_file -- путь к файлу
    """
    receiver_data = collect_info_from_profile(receiver_profile_id)
    messager_data = collect_info_from_profile(messager_profile_id)
    message_text = read_file(path_to_file)

    # Receiver name check
    if receiver_data["Name"] == "Not specified":
        receiver_data["Name"] = receiver_data["Nickname"]
    # add to receiver_data My name, to replace it in 'for' cycle
    receiver_data['my_name'] = messager_data["Name"]

    # message_text = message_text.format(name=receiver_name,
    # my_name=messager_name, country=country)
    for key in receiver_data.keys():
        # Check if user is dummy, and not use paragraph character
        message_text = re.sub(' {3,}', '\n', message_text)

        # Find key in text
        if message_text.find("{" + key + "}") + message_text.find(
                "{" + key.lower() + "}") != -2:
            if receiver_data[key] == "Not specified":
                # print(re.sub("\n?[^\n]*{" + key + "}[^\n]*[\n]? {4,}", '',
                # message_text))
                # replace all paragraph with 'Not Specified' key to empty
                # string
                # args of re.sub: pattern, text fragment to replace,
                # text where replace
                # full pattern:   \n?[^\n]*{Country}[^\n]*[\n]?
                message_text = re.sub("\n?[^\n]*{" + key + "}[^\n]*[\n]?", '',
                                      message_text)
                message_text = re.sub(
                    "\n?[^\n]*{" + key.lower() + "}[^\n]*["
                    "\n]?", '', message_text)
                # We don't need to continue replacement with Not specified key
                continue

            # Check if key is Name, Country
            text_to_replace = receiver_data[key]
            if key not in ['name', 'my_name', 'country', 'nickname', 'city']:
                text_to_replace = text_to_replace

            # Replacement
            message_text = message_text.replace("{" + key + "}",
                                                text_to_replace)
            message_text = message_text.replace("{" + key.lower() + "}",
                                                text_to_replace)

    return message_text
コード例 #2
0
def profile_country(profile_id):
    """Исключаем ненужные страны из списка рассылки

    Keyword arguments:
    profile_id -- ID профиля, которому собираемся отослать сообщение
    """
    profile_info = collect_info_from_profile(profile_id)
    country = profile_info["Country"]
    # Если страна в списке исключенных, то не отправляем письмо
    if country in ["Azerbaijan", "India", "Tajikistan"]:
        return True

    return False
コード例 #3
0
def not_in_age_bounds(messager_age, receiver_profile_id):
    """Возраст отправителя должен быть меньше или равен возрасту профиля
    которому мы отсылаем

    Keyword arguments:
    messager_age -- возраст отправителя
    receiver_profile_id -- ID профиля, которому собираемся отослать сообщение
    """
    receiver_age = collect_info_from_profile(receiver_profile_id)["Age"]
    if messager_age > receiver_age:
        return True

    return False
コード例 #4
0
def forbidden_profile(profile_id):
    """Проверка на то, является ли профиль запрещенным (если отослать на
    него письмо, то наш аккаунт заблочат)

    Keyword arguments:
    profile_id -- ID профиля которому будет отправлено сообщение
    """
    # Собираем информацию о профиле
    data = collect_info_from_profile(profile_id)
    # Якорные слова которые обозначают профиль как ловушку
    anchor_words = read_file("anchor_words.csv").splitlines()[1:]
    # ищем якоря в DESCRIPTION
    for anchor in anchor_words:
        if anchor in data["Description"]:
            return True

    # Если нету, то False
    return False
コード例 #5
0
def forbidden_profile(profile_id):
    """Проверка на то, является ли профиль запрещенным (если отослать на
    него письмо, то наш аккаунт заблочат)

    Keyword arguments:
    profile_id -- ID профиля которому будет отправлено сообщение
    """
    from control_panel import db_get_rows
    # Собираем информацию о профиле
    data = collect_info_from_profile(profile_id)
    # Якорные слова которые обозначают профиль как ловушку
    anchor_words = db_get_rows([Tags.tag], Tags.forbidden)
    # ищем якоря в DESCRIPTION
    for anchor in anchor_words:
        if anchor[0] in data["Description"]:
            return True

    # Если нету, то False
    return False
コード例 #6
0
def profile_country(profile_id):
    """Исключаем ненужные страны из списка рассылки

    Keyword arguments:
    profile_id -- ID профиля, которому собираемся отослать сообщение
    """
    profile_info = collect_info_from_profile(profile_id)
    country = profile_info["Country"]
    # Если страна в списке исключенных, то не отправляем письмо
    if country in [
            "Azerbaijan", "India", "Tajikistan", "Taiwan", "Ecuador",
            "South Africa", "Colombia", "Saudi Arabia", "China", "Venezuela",
            "Egypt", "Kuwait", "Jordan", "Russia", "Ukraine", "Qatar",
            "Turkey", "Brazil", "Peru", "Costa Rica", "Macedonia", "Serbia",
            "Romania", "Honduras", "Nicaragua", "Morocco", "Bolivia",
            "Ecuador", "Panama", "Qatar", "Bahrain"
    ]:
        return True

    return False
コード例 #7
0
ファイル: main.py プロジェクト: aKondratyuk/NatalyBot-1
def tabulated_table(sheet):
    """Оформление таблицы и ее вывод

    Keyword arguments:
    sheet -- лист со значениями
    """
    data = get_sheet_values(sheet)
    new_data = []
    for i, profile_id in enumerate(data["Login"]):
        try:
            profile = collect_info_from_profile(str(profile_id))
        except Exception as ex:
            print(
                f"Профиль номер {i + 1} с логином {profile_id} не существует")
        row = [i + 1, profile_id, data["Password"][i + 1], profile["Name"],
               profile["Nickname"], profile["Age"],
               data["Path to text file"][i + 1]]
        new_data.append(row)
    header = ["Номер", "Логин", "Пароль", "Имя", "Никнейм", "Возраст",
              "Имя инвайта"]
    print(tabulate(new_data, headers=header, tablefmt="grid"))

    return data
コード例 #8
0
ファイル: main.py プロジェクト: aKondratyuk/NatalyBot-1
         photos_only = "on"
         print(f"Изменено на: только с фото - да")
     else:
         print("\nНету такого пункта в меню\n")
 elif choice == "2":
     data = tabulated_table(sheet)
     choice = input(
         "\nНапишите через запятую номера аккаунтов: \n")
     numbers = [int(num) for num in choice.split(",")]
     for i in numbers:
         profile_login, password = str(data["Login"][i]), \
                                   data["Password"][i]
         values = login(profile_login, password)
         if values:
             session, my_profile_id = values
             my_data = collect_info_from_profile(
                 my_profile_id)
             nickname = my_data["Nickname"]
             print(
                 f"\nПРОФИЛЬ {nickname} НАЧИНАЕТ "
                 f"РАССЫЛКУ\n")
             idx = 1
             messages_has_sent = 0
             STOP = False
             while messages_has_sent != \
                     messages_need_to_be_sent:
                 if STOP:
                     break
                 profiles = search_for_profiles(
                         my_data["Sex"], looking_for,
                         my_data["Age"],
                         date_of_birth_end, page,
コード例 #9
0
def db_load_profile_description(profile_id: str) -> bool:
    from main import logger

    # check profile delete status
    if not db_profile_available(profile_id=profile_id):
        logger.info(f'User {current_user} opened load of profile '
                    f'description for profile_id: {profile_id},'
                    f'but this profile deleted on site')
        return False
    else:
        logger.info(f'User {current_user} opened load of profile '
                    f'description for profile_id: {profile_id}')
    db_session = Session()
    # collect info from site
    profile_details = collect_info_from_profile(profile_id=profile_id)

    # delete old profile info
    if db_duplicate_check([ProfileDescription],
                          ProfileDescription.profile_id == profile_id):
        logger.info(f'User {current_user} deleted old profile '
                    f'description for profile_id: {profile_id}')
    # delete profile description
    db_delete_rows([ProfileDescription],
                   ProfileDescription.profile_id == profile_id)
    # delete old category level
    db_delete_rows([ProfileCategories],
                   ProfileCategories.profile_id == profile_id)
    # delete old languages
    db_delete_rows([ProfileLanguages],
                   ProfileLanguages.profile_id == profile_id)

    # create new profile info
    new_pr_desc = ProfileDescription(profile_id=profile_id)
    for i in range(len(profile_details)):
        key = list(profile_details.keys())[i]
        val = profile_details[key]
        if type(val) == str:
            if val.lower() == 'not specified':
                val = None
        if key == 'Languages':
            # add new languages
            for lang in profile_details[key].keys():
                language = lang
                level_name = profile_details[key][lang]
                # check if user not specified languages
                if language.lower() == 'not specified':
                    continue
                elif level_name.lower() == 'not specified':
                    level_name = None

                new_lang_lvl = ProfileLanguages(profile_id=profile_id,
                                                language=language,
                                                level_name=level_name)
                db_session.add(new_lang_lvl)
                db_session.commit()
            continue

        # check if key in categories table
        elif db_duplicate_check([Categories],
                                Categories.category_name == key.lower()):
            # add new category levels
            new_category_lvl = ProfileCategories(category_name=key.lower(),
                                                 profile_id=profile_id,
                                                 level_name=val)
            db_session.add(new_category_lvl)
            db_session.commit()
            continue
        setattr(new_pr_desc, key.lower(), val)
    db_session.close()
    db_session = Session()
    db_session.add(new_pr_desc)
    db_session.commit()
    logger.info(f'User {current_user} added profile '
                f'description for profile_id: {profile_id}')
    db_session.close()
    return True
コード例 #10
0
def send_messages(profile_id_list: str,
                  looking_for: str = None,
                  photos_only: str = "off",
                  profiles: list = None) -> bool:
    """Send messages from profiles,
    checks how much messages each profile has already send today,
    calculate max available age with profile max_age_delta and profile age"""
    from main import logger
    # load profiles from DB
    profiles_list = db_get_rows(
        [
            Profiles.profile_id, Profiles.profile_password, Profiles.msg_limit,
            Profiles.max_age_delta, ProfileDescription.age,
            ProfileDescription.sex
        ], Profiles.profile_id.in_(profile_id_list), Profiles.profile_password,
        ProfileDescription.profile_id == Profiles.profile_id)
    for i in range(1, len(profiles_list) + 1):
        msg_have_sent_today = db_get_rows(
            [Messages.message_token],
            Profiles.profile_id == ChatSessions.profile_id,
            Messages.chat_id == ChatSessions.chat_id,
            Messages.send_time == datetime.now().date())
        msg_need_to_be_sent = profiles_list[i][2] - msg_have_sent_today

        # calculate max_age for message receivers
        date_of_birth_end = profiles_list[i][3] + profiles_list[i][4]

        profile_login, password = str(profiles_list[i][0]), \
                                  profiles_list[i][1]
        values = login(profile_login, password)
        # start page in site for search
        page = 1
        if not looking_for:
            if profiles_list[i][5] == 'male':
                looking_for = 'female'
            else:
                looking_for = 'male'
        if values:
            session, my_profile_id = values
            my_data = collect_info_from_profile(my_profile_id)
            logger.info(f"Profile with profile_id: {my_profile_id} "
                        f"start send messages")
            messages_has_sent = 0
            stop = False
            while messages_has_sent < msg_need_to_be_sent:
                if stop:
                    break
                if not profiles:
                    profiles = search_for_profiles(my_data["Sex"], looking_for,
                                                   my_data["Age"],
                                                   date_of_birth_end, page,
                                                   photos_only)
                profiles_id = get_id_profiles(profiles)
                profile_try_counter = 0
                page_try_counter = 0
                while len(profiles_id) == 0:
                    if profile_try_counter == 2:
                        page += 1
                        page_try_counter += 1
                    elif page_try_counter == 10:
                        logger.info(
                            f"Site don't show any profiles in 10 pages,"
                            f"messages sent from profile with"
                            f"profile_id: {my_profile_id} ended.")
                        messages_has_sent = \
                            msg_need_to_be_sent
                        break
                    profiles = search_for_profiles(my_data["Sex"], looking_for,
                                                   my_data["Age"],
                                                   date_of_birth_end, page,
                                                   photos_only)
                    profiles_id = get_id_profiles(profiles)
                    profile_try_counter += 1
                for profile_id in profiles_id:
                    check_response = check_for_filter(session, profile_id)
                    if check_response:
                        if check_response == "LIMIT OUT":
                            stop = True
                            break
                    else:
                        message_text = create_custom_message(
                            my_profile_id, profile_id)
                        if message_text is False:
                            logger.info(
                                f"Profile with profile_id {my_profile_id},"
                                f" without unused message templates")
                            messages_has_sent = \
                                msg_need_to_be_sent
                            break
                        message(session, profile_id, message_text)
                        dialog_download(observer_login=profiles_list[i][0],
                                        observer_password=profiles_list[i][1],
                                        sender_id=profiles_list[i][0],
                                        receiver_profile_id=profile_id)
                        messages_has_sent += 1
                        logger.info(
                            f"Successfully sent message to profile "
                            f"with profile_id: {profile_id}. "
                            f"Left to send: "
                            f" {msg_need_to_be_sent - messages_has_sent}")
                        if messages_has_sent == \
                                msg_need_to_be_sent:
                            logger.info(f"Profile with profile_id: "
                                        f"{my_profile_id}, "
                                        f"successfully sent messages")
                            break
                page += 1
    return True