├── win.jpg ├── english ├── fb_log │ └── log.log ├── settings_en.ini ├── birthday_en.txt └── FacebookEN.py ├── russian ├── fb_log │ └── log.log ├── settings.ini ├── birthday.txt └── FacebookRU.py ├── LICENSE └── README.md /win.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/doevent/facebook-auto-liker/HEAD/win.jpg -------------------------------------------------------------------------------- /english/fb_log/log.log: -------------------------------------------------------------------------------- 1 | 2020-08-09 02:53:16,233: root - INFO - ============================================================== 2 | 2020-08-09 02:53:16,234: root - INFO - Start bot 3 | 2020-08-09 02:53:16,531: root - INFO - Current version: 0.3.1 4 | 2020-08-09 05:18:00,052: root - INFO - ============================================================== 5 | -------------------------------------------------------------------------------- /russian/fb_log/log.log: -------------------------------------------------------------------------------- 1 | 2020-08-09 02:53:16,233: root - INFO - ============================================================== 2 | 2020-08-09 02:53:16,234: root - INFO - Start bot 3 | 2020-08-09 02:53:16,531: root - INFO - Current version: 0.3.1 4 | 2020-08-09 05:18:00,052: root - INFO - ============================================================== 5 | -------------------------------------------------------------------------------- /english/settings_en.ini: -------------------------------------------------------------------------------- 1 | [Settings] 2 | version=0.3.1-beta.5 3 | ; chrome_user - username in the browser, if applicable. Example: chrome_user = andrey 4 | chrome_user = 5 | ; The width of the browser window. Example: width = 1024 6 | width = 1024 7 | ; The height of the browser window. Example: height = 720 8 | height = 720 9 | ; stories - number of like cycles per story. Example: stories = 150 10 | stories = 20 11 | ; birthday - maximum number of congratulations cycles. Example: birthday = 19 12 | birthday = 19 13 | ; feed maximum number of news feed varnish cycles. Example: feed = 300 14 | feed = 10 15 | ; feed_select - selection of the news feed option: 0 - shows relevant posts, 1 - new messages. Example: feed_select = 0 16 | feed_select = 0 17 | ; Enable and disable images: 0 - Disable images. Example: images = 0 18 | images = 1 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 doevent 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /russian/settings.ini: -------------------------------------------------------------------------------- 1 | [Settings] 2 | ; chrome_user - имя пользователя в браузере, если используется. Пример: chrome_user = andrey 3 | chrome_user = 4 | ; Ширина окна браузера. Пример: width = 1124 5 | width = 1124 6 | ; Высота окна браузера. Пример: height = 720 7 | height = 720 8 | ;Включает и отключает отображение картинок в браузере: 0 - картинки выключены: Пример: images = 0 9 | images = 1 10 | ; stories - количество циклов лайков в сториес. Пример: stories = 150 (не рекомендуется большое значение) 11 | stories = 30 12 | ; feed максимальное количество циклов лаков ленты новостей. Пример: feed = 300 (не рекомендуется большое значение) 13 | feed = 20 14 | ; feed_select - выбор варианта выдачи новостной ленты: 0 - показывает релевантные записи, 1 - новые сообщения. Пример: feed_select = 0 15 | feed_select = 0 16 | ;токен телеграм бота выдается при созаднии бота: BotFather (https://t.me/BotFather) Пример: token = 1387036342:AAGm4QWD5vUjH7FgQbejmz1jelfvh1WUDQI 17 | token = 0 18 | ;Ваш ID в телеграме. Можно узнать отправив сообщение боту: getmyid_bot (https://t.me/getmyid_bot). Пример: botid = 1251879074 19 | botid = 0 20 | [Birthday] 21 | detect_popup = False 22 | date = 2022-01-30 23 | -------------------------------------------------------------------------------- /english/birthday_en.txt: -------------------------------------------------------------------------------- 1 | Happy Birthday! 2 | Wishing you a Happy Birthday! 3 | Best wishes and a wonderful Birthday! 4 | Happy Birthday! Wishing you all the best on your special day! 5 | Congratulations and best wishes on your Birthday! 6 | I wish you a Happy Birthday and many happy returns of the day! 7 | From the bottom of my heart I wish you Happy Birthday! 8 | I hope all your birthday wishes come true! Happy Birthday! 9 | I wish you a Happy Birthday! Have a great time today! 10 | Warm and happy wishes on your Birthday! Have a wonderful day! 11 | Hope your special day brings you all you want! Happy Birthday! 12 | Wishing you the Best Birthday Ever! Have fun! Cheers! 13 | Happy Birthday and many happy days in a new year of yours! 14 | May all your dreams come true! Happy Birthday to you! 15 | Sending you Happy Birthday wishes wrapped in all my love! 16 | Wishing you everything happy on your Birthday! 17 | Wishing you a Birthday which is as special as you are! 18 | Thinking of you on your Birthday and wishing you happiness! Have a great day! 19 | May all your dreams come true! Happy Birthday to you! 20 | May be I am not by your side on your Birthday but I always think about you and send you all the best wishes! Happy Birthday! 21 | Let God keeps you away from evil tongues, sudden misfortune, clever enemies and small-minded friends! Happy Birthday! 22 | With lots of love I am sending you sweet Birthday wishes! Have a very Happy Birthday! 23 | Even though we are miles away, it is good to know that you are always there! Happy Birthday! 24 | With great pleasure I want to wish you much health, love, happiness and freedom in your dreams. Wish you eternal youth, original ideas, big success in everything you do! Be happy! Try to save you would not be happening. 25 | I wish you a long and amazing life. I wish you great health and excellent results in all your dealings. Most importantly, I wish you happiness without measure every minute in your life. Be loved, be happy, enjoy every day! 26 | You’re a miracle and a charm! Let you have happiness and good fortune without problems and troubles. I wish you and all your dearest to have also good health! Happy birthday! 27 | With all my heart I wish you many happy returns of the day! Let all your fond dreams, hopes and expectations come true in your new year. I wish you always to have cheerful mood, good health, strength to resist difficulties and patience, big success in all your dealings and great personal happiness! Thank you for the bright light you give me! Thank you for your being in this world! Happiness and good luck! Happy birthday! 28 | Happy birthday, wish you much health, happiness, freedom, success in everything you do and eternal youth. 29 | Wishing you all the best on your Birthday! -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Facebook Auto Liker (English, Russian) 2 | ![alt text](win.jpg) 3 | ### version v0.3.1-beta.5 4 | Facebook likes feeds, likes stories, send message birthday. 5 | 6 | Автоматический лайкер новостной ленты, историй и отправка поздравлений с днем рождения. 7 | 8 | ### Functions EN 9 | * Likes friends feed 10 | * Likes stories 11 | * Send Birthday Messages 12 | * Run from the command line 13 | 14 | ### Функции RU 15 | * Лайки ленты друзей 16 | * Лайки историй 17 | * Поздравления с днем рождения 18 | * Информирование через телеграм бота 19 | * Запуск из командной строки (например для запуска через планировщик) 20 | 21 | ### Install 22 | Python: 23 | ``` 24 | pip install selenium 25 | ``` 26 | ``` 27 | Download Chrome driver https://chromedriver.chromium.org/ 28 | ``` 29 | ``` 30 | Patch chromedriver.exe: Replacing cdc_ variable ($cdc_asdjflasutopfhvcZLmcfl_) 31 | ``` 32 | ## Settings 33 | 34 | #### Settings 35 | The setting is carried out without a graphical interface in a test format by editing the **setting.ini** file through a text editor or in a built-in text editor. 36 | 37 | **chrome_user** - username in the browser (optional). Example: 38 | ``` 39 | chrome_user = andrey 40 | ``` 41 | **width** - width of browser window. Example: 42 | ``` 43 | width = 1024 44 | ``` 45 | **height** - height of browser window. Example: 46 | ``` 47 | height = 720 48 | ``` 49 | **stories** - number of cycles of likes in stories (a large value is not recommended). Example: 50 | ``` 51 | stories = 150 52 | ``` 53 | **birthday** - maximum number of congratulations cycles (more than 20 is not recommended). Example: 54 | ``` 55 | birthday = 19 56 | ``` 57 | **feed** maximum number of cycles of news feed varnishes (a large value is not recommended). Example: 58 | ``` 59 | feed = 300 60 | ``` 61 | **token** - telegram bot token is issued when the bot is created: BotFather (https://t.me/BotFather) Example: 62 | ``` 63 | token = 1387036342:AAGm4QWD5vUjH7FgQbejmz1jelfvh1WUDQI 64 | ``` 65 | **botid** - your ID in telegram (not bot). You can find out by sending a message to the bot: getmyid_bot (https://t.me/getmyid_bot). Example: 66 | ``` 67 | botid = 1251879074 68 | ``` 69 | #### Setting birthday 70 | Setting is done by editing the file **birthday.txt**. One congratulations on one line, no hyphenation. Example: 71 | ``` 72 | Happy Birthday! 73 | Wishing you a Happy Birthday! 74 | Best wishes and a wonderful Birthday! 75 | Happy Birthday! Wishing you all the best on your special day! 76 | Congratulations and best wishes on your Birthday! 77 | I wish you a Happy Birthday and many happy returns of the day! 78 | ``` 79 | #### Command line 80 | Frends feed likes: 81 | ``` 82 | python FacebookRU.py feed 83 | FacebookRU.exe feed 84 | ``` 85 | Likes stories: 86 | ``` 87 | python FacebookRU.py story 88 | FacebookRU.exe story 89 | ``` 90 | Birthday: 91 | ``` 92 | python FacebookRU.py birthday 93 | FacebookRU.exe birthday 94 | ``` 95 | ### Compatibility 96 | * Windows 10, 2019 97 | * Python 3.7+ 98 | * Selenium 4.1.0 99 | * Chrome driver current test release version 90.0.4183.87 (for other version: [download driver](https://chromedriver.chromium.org/)) 100 | * Chrome current test release 90.0+ (chrome://settings/help) 101 | * Settings Facebook language: Russian, English 102 | * Switch to New Facebook design 103 | 104 | ## Author 105 | * **Skobeev Maksim** - [DoEvent](https://github.com/doevent/) 106 | 107 | 108 | ## License 109 | This project is licensed under the [MIT](https://en.wikipedia.org/wiki/MIT_License) License 110 | -------------------------------------------------------------------------------- /russian/birthday.txt: -------------------------------------------------------------------------------- 1 | Пусть жизнь дарит тысячи счастливых возможностей, и каждая из них будет использована на все сто. Счастья, удачи, благополучия! С Днём Рождения! 2 | Искренние пожелания счастья, удачи в любых начинаниях, душевного тепла и взаимопонимания. Новых встреч, новых достижений, исполнения всех желаний, С Днём Рождения! 3 | С днем рождения тебя! Желаю здоровья и хорошего настроения, всех благ и удовольствий жизни, благополучия и домашнего уюта, любви и человеческого счастья! 4 | С днем рождения тебя! Желаю побольше новых возможностей, интересных проектов и успешной их реализации. Пусть жизнь приносит тебе любовь и вдохновение. Пусть тебя будет достаточно сил, чтобы принять их в полной мере, а главное, использовать во благо. Ну и счастья, конечно, в качестве основы всего вышеперечисленного! 5 | Пусть жизнь дарит тысячи счастливых возможностей, и каждая из них будет использована на все сто. Счастья, удачи, благополучия! С Днём Рождения! 6 | С днем рождения! Желаю чудесного настроения, крепкого здоровья и всего самого лучшего. Пускай каждый новый день будет лучше предыдущего! 7 | Поздравляю тебя от всей души с Днем рождения! Пусть всё всегда сбывается! Желаю много улыбок, добра и радости, чтобы были верные друзья, любви чистой и взаимной, крепкого здоровья, счастья бесконечного, большого жизненного терпения, всех неземных благ и всего-всего самого доброго, прекрасного, и лучистого! 8 | С днем рождения! Желаю крепкого здоровья, удачи, благополучия, добра, радости, любви, счастья, хорошего настроения, улыбок, ярких впечатлений. Пусть тепло и уют всегда наполняют твой дом, пусть солнечный свет согревает в любую погоду, а желания исполняются при одной мысли о них. 9 | Поздравляю с днем рождения! Пусть жизнь дарит тебе побольше ярких моментов и сбудутся все твои самые смелые и заветные желания! Желаю, чтобы в твоем доме всегда царили счастье и понимание. И пусть тебя окружают только искренние, верные, надежные друзья и добрые люди! 10 | Прими мои поздравления с днем рождения! В твой лучший день хочу пожелать самого лучшего, чтобы в жизни было как можно больше хороших эмоций, приятных моментов и постоянного круговорота позитивных событий. Чтобы окружали только любимые, родные, дорогие сердцу люди. Чтобы во всем сопутствовал успех и везение. Ты этого заслуживаешь! 11 | С днем рождения! Пусть каждый день приносит радость, улыбки и подарки, пусть все мечты исполняются, а планы реализуются, пусть окружают только искренние люди, преданные друзья, и пусть не будет места для уныния и печалей! 12 | Поздравляю с Днём рождения! Желаю тебе хорошего настроения, огромного счастья, бесконечной любви, достатка в семье, карьерного роста, хороших друзей и, конечно же, здоровья тебе и всем, кто тебе дорог. Пусть мечты никогда не покидают тебя и превращаются в реальность. 13 | Поздравляю с днем рождения! Желаю, чтобы вся жизнь была полна радости, счастья, здоровья, улыбок, любви и приятных сюрпризов. Пусть удача станет неотъемлемым спутником, а во всех начинаниях всегда сопутствует только успех. Больше силы, чувств и смелости, чтобы сбывались даже самые необычные желания! 14 | Поздравляю с днем рождения! Кроме стандартных пожеланий — счастья, здоровья и всего наилучшего — я желаю, чтобы сбывались все мечты, чтобы каждый день приносил много приятных неожиданностей, чтобы Вас окружали только добрые и нужные люди. А еще везения. Везения во всём и всегда. И чтобы каждое начатое дело заканчивалось успешно! 15 | Поздравляю с днем рождения! Желаю, чтобы твоя жизнь была яркой и восхитительной, любимые дарили внимание, радость, тепло и ласку, друзья окружали искренним пониманием и поддержкой, коллеги уважали и дорожили. Пусть всё, что казалось несбыточным, сбудется, и самое желанное пусть произойдет! 16 | Поздравляю с днем рождения! Желаю прекрасной жизни, и пусть на каждом ее повороте всегда встречаются замечательные события. Желаю массу поводов для радости и здоровья крепкого! Пусть каждое утро будет счастливым и солнечным. 17 | Поздравляю с днем рождения! Яркого позитивного настроения, высоких достижений, душевной гармонии, процветания, крепкого здоровья, успехов во всём! Желаю никогда не останавливаться на достигнутом. Удачи в познании новых идей, саморазвития и стремления только к самому лучшему! 18 | Поздравляю с днем рождения! Пусть все мечты сбываются, желания исполняются, цели достигаются, здоровье улучшается и деньги прибавляются! Счастья, радости и душевной гармонии, блистательных удач, незабываемых впечатлений и головокружительных успехов, настоящей любви, верных друзей и яркой радуги эмоций! 19 | Поздравляю с днем рождения! В этот замечательный день желаю тебе крепкого здоровья, верных и преданных друзей, безграничного счастья, безразмерных доходов, сумасшедшей любви и побольше радостных дней! Хорошего тебе настроения и отличного праздника! 20 | С днем рождения! Пусть жизнь будет беспрерывным потоком счастливых дней и прекрасных мгновений. Желаю назад оглядываться только лишь с хорошими воспоминаниями, вперёд смотреть с уверенностью в собственных силах и доброй надеждой, а в настоящем всегда оставаться замечательным человеком с любящим сердцем и открытой душой! 21 | Поздравляем с днем рождения! Желаем здоровья, удачи, любви, везения, мира, добра, улыбок, благополучия. Пусть все мечты исполняются. Пусть жизнь будет долгой и гладкой, полной ярких и запоминающихся событий! 22 | От всей души прими мои самые искренние поздравления с днем рождения! Я желаю тебе крепкого здоровья, финансовой стабильности, гармонии во всем, любви во всех ее проявлениях, мирного неба над головой. Пусть по жизни сопутствует удача и успех, тебя окружают близкие по духу люди, а каждый твой день сияет новыми радужными красками! 23 | С днем рождения! Поздравлять хороших людей всегда приятно, а такого замечательного человека, как ты, — приятно вдвойне. Я искренне желаю, чтобы у тебя всегда было достаточно: улыбок, солнечных дней, удачных ситуаций, успеха, восхищений, любви, поздравлений, поддержки, верных друзей, гениальных идей, интересных затей, только важных людей, денег, чувств и эмоций, силы, смелости... Но, главное, чтобы в нужную минуту у тебя всегда было бы то, что тебе нужно. 24 | Поздравляю с днем рождения! Желаю безмерного счастья, крепкого здоровья, настоящей любви, удачи, достатка, исполнения желаний! Пусть жизнь будет наполнена положительными эмоциями, верными друзьями, радостными днями. Ярких, светлых, счастливых тебе событий! 25 | Поздравляю тебя с днём рождения! Желаю не болеть, не грустить, много улыбаться, сиять от счастья, с годами только хорошеть, верить в лучшее и в мечту, которая, несомненно, сбудется. Пусть удача будет твоим путеводителем, перед тобой открываются золотые горы благополучия и сладких грёз. Волшебные моменты пусть озаряют твой взгляд, любовь всегда будет рядом и доставляет тебе только удовольствие! 26 | Поздравляю с днём рождения тебя! Желаю прекрасной и удивительной жизни, океан безумной любви, бесконечно счастливого времени, только крепкого здоровья и отличного настроения! 27 | Желаю самого главного в жизни — здоровья. Пусть в семье тебя любят и ценят, пусть в работе будет востребованность и полная самореализация, пусть в сердце живёт счастье и радость. С днем рожденья! -------------------------------------------------------------------------------- /english/FacebookEN.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | 3 | import logging 4 | 5 | from selenium import webdriver 6 | from selenium.webdriver.common.by import By 7 | from selenium.webdriver.common.keys import Keys 8 | from selenium.webdriver.support.ui import WebDriverWait 9 | from selenium.webdriver.support.expected_conditions import element_to_be_clickable 10 | from selenium.webdriver.chrome.options import Options 11 | from selenium.webdriver import ActionChains 12 | from selenium.webdriver.support import expected_conditions as EC 13 | from selenium.common.exceptions import TimeoutException, WebDriverException, ElementClickInterceptedException, NoSuchElementException 14 | 15 | import time 16 | import random 17 | import datetime 18 | import configparser 19 | 20 | import tempfile 21 | import os 22 | import time 23 | import requests # get update version 24 | 25 | import tkinter as tk # windows 26 | import argparse # command line 27 | 28 | 29 | log_filename = f'fb_log\\facebook_select_en-{datetime.datetime.now().strftime("%d-%m-%Y")}.log' 30 | logging.basicConfig(filename=log_filename, level=logging.INFO, filemode='a', format=' %(asctime)s: %(name)s - %(levelname)s - %(message)s') 31 | print(log_filename) 32 | logging.info("==============================================================") 33 | logging.info("Start bot") 34 | 35 | 36 | 37 | # get ini 38 | try: 39 | config = configparser.ConfigParser() 40 | config.read('settings_en.ini') 41 | version = config.get("Settings", "version") 42 | chrome_user = config.get("Settings", "chrome_user") 43 | width_set = int(config.get("Settings", "width")) 44 | height_set = int(config.get("Settings", "height")) 45 | stories_set = int(config.get("Settings", "stories")) 46 | birthday_set = int(config.get("Settings", "birthday")) 47 | feed_set = int(config.get("Settings", "feed")) 48 | feed_select = int(config.get("Settings", "feed_select")) 49 | 50 | 51 | stories_set_end = stories_set - 1 52 | except Exception as e: 53 | logging.exception("Error load INI") 54 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error load INI") 55 | 56 | # get new version 57 | r_version = 0 58 | upd_version = 0 59 | try: 60 | r_version = requests.get('https://skobeev.design/fb/version.txt') 61 | r_version.encoding = 'utf-8' 62 | upd_version = r_version.text 63 | logging.info(f"Current version: {version}") 64 | if upd_version == version: 65 | print(f"Current version: {version}") 66 | else: 67 | print(f"Last Version: {upd_version}") 68 | except Exception as e: 69 | upd_version = "Not available" 70 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error get version.") 71 | logging.exception('Error get version') 72 | 73 | 74 | driver = 0 75 | size = 0 76 | position = 0 77 | 78 | 79 | def start_browser(): 80 | global driver 81 | global size 82 | global position 83 | 84 | # Chrome options 85 | options = webdriver.ChromeOptions() 86 | options.add_argument("disable-infobars") 87 | options.add_experimental_option("excludeSwitches", ["enable-automation"]) 88 | options.add_experimental_option('useAutomationExtension', False) 89 | options.add_argument(f"user-data-dir={os.path.expanduser('~')}\\AppData\\Local\\Google\\Chrome\\User Data\\{chrome_user}") 90 | 91 | try: 92 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Create browser window...") 93 | driver = webdriver.Chrome(options=options) 94 | except WebDriverException: 95 | logging.exception("Error TEMP catalog") 96 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error TEMP catalog\n{tempfile.gettempdir()}") 97 | try: 98 | if os.path.exists(tempfile.gettempdir()) == False: 99 | logging.warning("Directory not found. We create a new.\n{tempfile.gettempdir()}") 100 | os.mkdir(tempfile.gettempdir()) 101 | except Exception as e: 102 | logging.exception("Error create TEMP catalog") 103 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error create TEMP catalog\n{tempfile.gettempdir()}") 104 | except Exception as e: 105 | logging.exception('Error Create browser window') 106 | 107 | 108 | # mask browser 109 | driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { 110 | "source": """ 111 | Object.defineProperty(navigator, 'webdriver', { 112 | get: () => undefined 113 | }) 114 | """ 115 | }) 116 | 117 | driver.execute_cdp_cmd("Network.enable", {}) 118 | driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {"headers": {"User-Agent": "browser1"}}) 119 | 120 | driver.set_window_rect(10,10, width_set, height_set) 121 | driver.get("https://facebook.com/") 122 | time.sleep(3) 123 | 124 | size = driver.get_window_size() 125 | position = driver.get_window_position() 126 | print(f"Window size: width = {size['width']}px, height = {size['height']}px, x = {position['x']}, y = {position['y']}") 127 | logging.info(f"Window size: width = {size['width']}px, height = {size['height']}px, x = {position['x']}, y = {position['y']}") 128 | print(driver.capabilities['browserVersion']) 129 | logging.info(driver.capabilities['browserVersion']) 130 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() 131 | time.sleep(1) 132 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() 133 | ActionChains(driver).reset_actions() 134 | logging.info("Create browser window.") 135 | 136 | try: 137 | #Close tab 138 | driver.implicitly_wait(7) 139 | count_close = driver.find_elements_by_css_selector('[aria-label="Close tab"]') 140 | print(f'Close tab: {len(count_close)}') 141 | for send_close in count_close: 142 | send_close.click() 143 | time.sleep(5) 144 | try: 145 | driver.find_element_by_css_selector('[aria-label="ОК"]').click() 146 | time.sleep(5) 147 | except Exception as e: 148 | logging.debug(e) 149 | except Exception as e: 150 | logging.debug(e) 151 | 152 | #----------------------------------------------------------- 153 | def start_birthday_fb(): 154 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Start function of birthday greetings...") 155 | 156 | start_browser() 157 | logging.info('Start function of birthday greetings') 158 | 159 | time.sleep(10) 160 | driver.get("https://www.facebook.com/") 161 | driver.implicitly_wait(10) # seconds 162 | time.sleep(10) 163 | wait = WebDriverWait(driver, 10) 164 | WebDriverWait(driver, 10) 165 | 166 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() 167 | time.sleep(2) 168 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() 169 | time.sleep(2) 170 | ActionChains(driver).send_keys(Keys.HOME).perform() 171 | time.sleep(random.randrange(15,20)) 172 | 173 | try: 174 | driver.find_element_by_css_selector("[href='/events/birthdays/']").click() 175 | time.sleep(random.randrange(15,20)) 176 | except Exception as e: 177 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Birthday button not found.\n{e}") 178 | logging.warning(f"Birthday button not found.\n{e}") 179 | else: 180 | try: 181 | birthday_message() 182 | except Exception as e: 183 | driver.quit() 184 | logging.debug(e) 185 | 186 | # function of birthday 187 | def birthday_message(): 188 | driver.implicitly_wait(40) # seconds 189 | time.sleep(random.randrange(18,27)) 190 | 191 | try: 192 | with open("birthday_en.txt", "r", encoding="utf-8") as f: 193 | birthday = f.readlines() 194 | 195 | count_post = driver.find_elements_by_css_selector("[method='POST']") 196 | len_count = len(count_post)-1 197 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Found fields: {len_count}") 198 | 199 | logging.info(f'Found fields: {len_count}') 200 | num_msg = 0 # counter of sent messages 201 | 202 | for send_msg in range(0, len_count): 203 | if len_count <= 0: 204 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> No fields found №: {num_msg}") 205 | logging.info(f'No fields found №: {num_msg}') 206 | break 207 | elif send_msg >= birthday_set: 208 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Congratulations limit №: {num_msg}") 209 | logging.info(f'Congratulations limit №: {num_msg}') 210 | break 211 | 212 | for cv in range(0,13): 213 | ActionChains(driver).send_keys(Keys.TAB).perform() 214 | element = driver.switch_to.active_element 215 | driver.implicitly_wait(1) 216 | try: 217 | if element.find_element_by_tag_name('br').get_attribute('data-text') == 'true': 218 | try: 219 | cmess = driver.find_elements_by_css_selector('[method="POST"]') 220 | cmess[0].location_once_scrolled_into_view 221 | txt = str(random.choice(birthday).replace("\n", "")) 222 | ActionChains(driver).send_keys_to_element(element, txt, Keys.ENTER).perform() 223 | 224 | num_msg = num_msg + 1 225 | time.sleep(random.randrange(5,10)) 226 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Congratulations №: {num_msg}") 227 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Text: {txt}") 228 | ActionChains(driver).reset_actions() 229 | break 230 | 231 | except NoSuchElementException as e: 232 | print(e) 233 | logging.info(e) 234 | except Exception as e: 235 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error in the congratulations sending cycle. Congratulations №: {num_msg}.\n{e}") 236 | logging.exception(f"Error in the congratulations sending cycle. Congratulations №: {send_msg}.\n{e}") 237 | break 238 | 239 | except Exception as e: 240 | logging.debug(e) 241 | time.sleep(random.randrange(5,10)) 242 | 243 | logging.info(f'Messages sent: {num_msg} of {len_count}') 244 | print (f"\n\nMessages sent: {num_msg} of {len_count}") 245 | print (f"\n\n{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Waiting...\n") 246 | f.close() 247 | try: 248 | driver.quit() 249 | except Exception as e: 250 | logging.debug(e) 251 | 252 | except Exception as e: 253 | logging.exception("Error Messages sent.") 254 | try: 255 | driver.quit() 256 | except Exception as e: 257 | logging.debug(e) 258 | 259 | 260 | #----------------------------------------------------------- 261 | def start_stories_fb(): 262 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> START Stories like function...") 263 | start_browser() # создаем окно 264 | logging.info('START Stories like function.') 265 | 266 | driver.get("https://www.facebook.com/") 267 | 268 | driver.implicitly_wait(60) # seconds 269 | time.sleep(10) 270 | wait = WebDriverWait(driver, 60) 271 | 272 | time.sleep(random.randrange(15,20)) 273 | try: 274 | driver.find_element_by_css_selector("[aria-label='See all stories']").click() 275 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button See all stories FOUND.") 276 | logging.info("Button See all stories FOUND.") 277 | time.sleep(15) 278 | 279 | stories_likes() 280 | 281 | 282 | except Exception as e: 283 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button See all stories NOT FOUND.\n{e}") 284 | logging.exception("Button See all stories NOT FOUND.") 285 | driver.quit() 286 | 287 | def stories_likes(): 288 | 289 | count_like = 0 290 | count_super = 0 291 | count_next = 0 292 | count_together = 0 293 | count_skip = 0 294 | 295 | next_refrash = 0 296 | wait = WebDriverWait(driver, 30) 297 | driver.implicitly_wait(5) # seconds 298 | 299 | ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.RETURN).perform() 300 | time.sleep(random.randrange(4,8)) 301 | 302 | try: # Sound off 303 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Mute"]'))).click() 304 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Mute") 305 | except Exception as e: 306 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error Mute... \n{e}") 307 | logging.info("Error Mute...\n{e}") 308 | 309 | try: 310 | for stories in range(0, stories_set): 311 | wait = WebDriverWait(driver, 3) 312 | rnd_like = random.randrange(1,9) 313 | if rnd_like == 1: 314 | # one click like 315 | try: 316 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="1"]'))).click() 317 | except Exception as e: 318 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button LIKE not found.\n{e}") 319 | logging.info(f'Like button not found\n{e}') 320 | else: 321 | count_like = count_like + 1 322 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Like...") 323 | 324 | elif rnd_like == 2: 325 | # one click love 326 | try: 327 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="2"]'))).click() 328 | except Exception as e: 329 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love button not found.\n{e}") 330 | logging.info(f"Love button not found.\n{e}") 331 | else: 332 | count_super = count_super + 1 333 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Love...") 334 | 335 | elif rnd_like == 3: 336 | # generator like 337 | for mkmk in range(0,random.randrange(2,5)): 338 | try: 339 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="1"]'))).click() 340 | except Exception as e: 341 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button LIKE not found.\n{e}") 342 | logging.info(f'Like button not found\n{e}') 343 | else: 344 | count_like = count_like + 1 345 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Like...") 346 | 347 | elif rnd_like == 4: 348 | # generator super 349 | for mkmk in range(0, random.randrange(2,5)): 350 | try: 351 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="2"]'))).click() 352 | except Exception as e: 353 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love button not found.\n{e}") 354 | logging.info(f"Love button not found.\n{e}") 355 | else: 356 | time.sleep(random.randrange(0,3)) 357 | count_super = count_super + 1 358 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Love...") 359 | 360 | elif rnd_like == 5: 361 | try: 362 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="1"]'))).click() 363 | except Exception as e: 364 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button LIKE not found.\n{e}") 365 | logging.info(f'Like button not found\n{e}') 366 | else: 367 | count_like = count_like + 1 368 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Like...") 369 | time.sleep(random.randrange(1,4)) 370 | 371 | try: 372 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="2"]'))).click() 373 | except Exception as e: 374 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love button not found.\n{e}") 375 | logging.info(f"Love button not found.\n{e}") 376 | else: 377 | count_super = count_super + 1 378 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Love...") 379 | 380 | elif rnd_like == 6: 381 | try: 382 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="2"]'))).click() 383 | except Exception as e: 384 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love button not found.\n{e}") 385 | logging.info(f"Love button not found.\n{e}") 386 | else: 387 | count_super = count_super + 1 388 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Love...") 389 | time.sleep(random.randrange(1,4)) 390 | 391 | 392 | try: 393 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="1"]'))).click() 394 | except Exception as e: 395 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button LIKE not found.\n{e}") 396 | logging.info(f'Like button not found\n{e}') 397 | else: 398 | count_like = count_like + 1 399 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Like...") 400 | 401 | elif rnd_like == 7: 402 | try: 403 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="1"]'))).click() 404 | except Exception as e: 405 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Button LIKE not found.\n{e}") 406 | logging.info(f'Like button not found\n{e}') 407 | else: 408 | count_like = count_like + 1 409 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Like...") 410 | time.sleep(random.randrange(1,4)) 411 | 412 | try: 413 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="2"]'))).click() 414 | except Exception as e: 415 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love button not found.\n{e}") 416 | logging.info(f"Love button not found.\n{e}") 417 | else: 418 | count_super = count_super + 1 419 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Love...") 420 | time.sleep(random.randrange(0,3)) 421 | 422 | try: 423 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="16"]'))).click() 424 | except Exception as e: 425 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Care button not found.\n{e}") 426 | logging.info(f"Care button not found.\n{e}") 427 | else: 428 | count_together = count_together + 1 429 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Care...") 430 | time.sleep(random.randrange(1,4)) 431 | 432 | 433 | elif rnd_like == 8: 434 | try: 435 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-reaction="16"]'))).click() 436 | except Exception as e: 437 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Care button not found.") 438 | logging.info(f"Care button not found.\n{e}") 439 | else: 440 | count_together = count_together + 1 441 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Care..") 442 | 443 | # NEXT 444 | try: 445 | wait = WebDriverWait(driver, 0) 446 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[aria-label='Next Bucket Button']"))).click() 447 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Next Bucket Button") 448 | time.sleep(random.randrange(1,2)) 449 | next_refrash = 0 # clear count error 450 | except Exception as e: 451 | try: 452 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[aria-label='Next Card Button']"))).click() 453 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Next Card Button") 454 | time.sleep(random.randrange(1,2)) 455 | next_refrash = 0 # clear count error 456 | except Exception as e: 457 | try: 458 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[aria-label='Next bucket button']"))).click() 459 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Next bucket button") 460 | time.sleep(random.randrange(1,2)) 461 | next_refrash = 0 # clear count error 462 | except Exception as e: 463 | try: 464 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[aria-label='Next card button']"))).click() 465 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Next card button") 466 | time.sleep(random.randrange(1,2)) 467 | next_refrash = 0 # clear count error 468 | except Exception as e: 469 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Not found NEXT button. Refresh...") 470 | logging.warning("Not found NEXT button. Refresh..\n{e}") 471 | 472 | next_refrash = next_refrash + 1 473 | 474 | if next_refrash == 3: # if repeat error no button NEXT - quit 475 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Not found NEXT button. Quit...") 476 | logging.info("Not found NEXT button. Quit.") 477 | driver.quit() 478 | break 479 | 480 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Refresh...") 481 | driver.refresh() 482 | time.sleep(random.randrange(10,15)) 483 | ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.RETURN).perform() 484 | time.sleep(random.randrange(4,8)) 485 | try: # Mute 486 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Mute"]'))).click() 487 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Mute") 488 | except Exception as e: 489 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error Mute... \n{e}") 490 | logging.info("Error mute...\n{e}") 491 | time.sleep(random.randrange(2,4)) 492 | logging.info('Refresh browser. No button NEXT') 493 | 494 | 495 | count_next = count_next + 1 496 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Next story...") 497 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> № {stories} of {stories_set_end} ...\n") 498 | time.sleep(random.randrange(2,4)) 499 | 500 | if stories_set_end == stories: 501 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - Good") 502 | logging.info(f"Кол-во: {stories} - Good.") 503 | 504 | driver.quit() 505 | print (f"\n\nLikes: {count_like}\nLoves: {count_super}\nCares: {count_together}\nNext: {count_next}\nAll: {stories + 1}") 506 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Waiting...\n") 507 | 508 | except Exception as e: 509 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Error {e}") 510 | logging.exception("Error likes story") 511 | driver.quit() 512 | 513 | 514 | #----------------------------------------------------------- 515 | # Функция начала лайков в ленте 516 | def start_feed_likes(): 517 | logging.info("START news feed like function.") 518 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> START news feed like function...") 519 | 520 | start_browser() 521 | 522 | if feed_select == 0: 523 | driver.get("https://www.facebook.com/") 524 | else: 525 | driver.get("https://www.facebook.com/?sk=h_chr") 526 | 527 | time.sleep(random.randrange(10,15)) 528 | feed_likes() 529 | 530 | # Основная функция лайков 531 | def feed_likes(): 532 | err_like = 0 533 | count_like = 0 534 | count_super = 0 535 | count_together = 0 536 | count_select = 0 537 | 538 | for x_all in range(0, feed_set): 539 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() 540 | time.sleep(random.randrange(1,3)) 541 | 542 | 543 | try: # if slow server 1GB memory (free amason micro) error: "Out of memory" 544 | driver.find_element_by_tag_name('div') 545 | except Exception: 546 | driver.refresh() 547 | logging.info('Out of memory') 548 | time.sleep(random.randrange(15,20)) 549 | 550 | ActionChains(driver).send_keys("j").perform() 551 | time.sleep(random.randrange(6,10)) 552 | ActionChains(driver).send_keys("l").perform() 553 | ActionChains(driver).reset_actions() 554 | time.sleep(random.randrange(7,10)) 555 | 556 | rnd_like_feed = random.randrange(1,4) 557 | if rnd_like_feed == 1: 558 | ActionChains(driver).send_keys(Keys.SPACE).perform() 559 | count_like = count_like + 1 560 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Like: {count_like}") 561 | 562 | elif rnd_like_feed == 2: 563 | ActionChains(driver).send_keys(Keys.TAB).perform() 564 | time.sleep(random.randrange(2,4)) 565 | ActionChains(driver).send_keys(Keys.SPACE).perform() 566 | count_super = count_super + 1 567 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Love: {count_super}") 568 | 569 | 570 | elif rnd_like_feed == 3: 571 | ActionChains(driver).send_keys(Keys.TAB + Keys.TAB).perform() 572 | time.sleep(random.randrange(2,4)) 573 | ActionChains(driver).send_keys(Keys.SPACE).perform() 574 | count_together = count_together + 1 575 | print (f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Care: {count_together}") 576 | 577 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {x_all} of {feed_set - 1}\n") 578 | ActionChains(driver).reset_actions() 579 | 580 | time.sleep(random.randrange(1,5)) 581 | 582 | 583 | if x_all == feed_set - 1: 584 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Good.") 585 | print(f"\Likes: {count_like}\Loves: {count_super}\nCares: {count_together}\n{x_all} of {feed_set - 1}") 586 | logging.info("Good") 587 | driver.quit() 588 | 589 | time.sleep(random.randrange(1,5)) 590 | 591 | # open ini 592 | def open_file(): 593 | with open('settings_en.ini', "r") as input_file: 594 | text = input_file.read() 595 | txt_edit.insert(tk.END, text) 596 | window.title(f"Facebook autoclicker") 597 | 598 | # save ini 599 | def save_file(): 600 | with open('settings_en.ini', "w") as output_file: 601 | text = txt_edit.get(1.0, tk.END) 602 | output_file.write(text) 603 | 604 | 605 | window = tk.Tk() 606 | window.title("facebook-auto-liker-bot") 607 | window.rowconfigure(0, minsize=500, weight=1) 608 | window.columnconfigure(1, minsize=800, weight=1) 609 | 610 | txt_edit = tk.Text(window) 611 | fr_buttons = tk.Frame(window, relief=tk.RAISED) 612 | btn_open = tk.Button(fr_buttons, text="Open", command=open_file) 613 | btn_save = tk.Button(fr_buttons, text="Save", command=save_file) 614 | 615 | button1 = tk.Button(fr_buttons, text="Like stories", bg="blue", fg="yellow", command=start_stories_fb) 616 | button2 = tk.Button(fr_buttons, text="News feed", bg="orange", fg="blue", command=start_feed_likes) 617 | button3 = tk.Button(fr_buttons, text="Birthday", bg="purple", fg="white", command=start_birthday_fb) 618 | 619 | label1 = tk.Label(fr_buttons, text=f"Settings\n") 620 | label2 = tk.Label(fr_buttons, text=f"\nFunction\n") 621 | label3 = tk.Label(fr_buttons, text=f"\n\nCurrent version: {version}\nLast version: {upd_version}") 622 | label4 = tk.Label(fr_buttons, text=f"\n\ndisclaimer: please note that this\nis a research project. i am by no\nmeans responsible for any usage\nof this tool. use on your own \nbehalf. i'm also not responsible if\nyour accounts get banned due to\nextensive use of this tool..") 623 | 624 | site_link = tk.Entry(fr_buttons) 625 | label1.grid(row=0, column=0) 626 | btn_open.grid(row=1, column=0, sticky="ew") 627 | btn_save.grid(row=2, column=0, sticky="ew") 628 | 629 | label2.grid(row=3, column=0) 630 | fr_buttons.grid(row=0, column=0, sticky="ns") 631 | txt_edit.grid(row=0, column=1, sticky="nsew") 632 | 633 | button1.grid(row=4, column=0) 634 | button2.grid(row=5, column=0) 635 | button3.grid(row=6, column=0) 636 | label3.grid(row=7, column=0) 637 | site_link.grid(row=8, column=0) 638 | site_link.insert(0,'https://github.com/doevent/facebook-auto-liker') 639 | label4.grid(row=9, column=0) 640 | 641 | 642 | if __name__ == "__main__": 643 | parser = argparse.ArgumentParser() 644 | parser.add_argument ('name', nargs='?') 645 | namespace = parser.parse_args() 646 | 647 | # запуск из командной строки 648 | if namespace.name == 'story': 649 | start_stories_fb() 650 | elif namespace.name == 'feed': 651 | start_feed_likes() 652 | elif namespace.name == 'birthday': 653 | start_birthday_fb() 654 | else: 655 | window.mainloop() 656 | -------------------------------------------------------------------------------- /russian/FacebookRU.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | 3 | # patch chromedriver.exe: Replacing cdc_ variable ($cdc_asdjflasutopfhvcZLmcfl_) 4 | 5 | from selenium import webdriver 6 | from selenium.webdriver.common.by import By 7 | from selenium.webdriver.common.keys import Keys 8 | from selenium.webdriver.support.ui import WebDriverWait 9 | from selenium.webdriver.support.expected_conditions import element_to_be_clickable 10 | from selenium.webdriver.chrome.options import Options 11 | from selenium.webdriver import ActionChains 12 | from selenium.webdriver.support import expected_conditions as EC 13 | from selenium.common.exceptions import TimeoutException, WebDriverException, ElementClickInterceptedException, NoSuchElementException 14 | from selenium.webdriver.support.ui import Select 15 | 16 | import logging 17 | import configparser 18 | import os 19 | 20 | import time 21 | import datetime 22 | import random 23 | import requests 24 | 25 | import tkinter as tk # create window 26 | import argparse # command line 27 | 28 | 29 | log_filename = f'fb_log\\facebook_select_ru-{datetime.datetime.now().strftime("%d-%m-%Y")}.log' 30 | logging.basicConfig(filename=log_filename, level=logging.INFO, filemode='a', format=' %(asctime)s: %(name)s - %(levelname)s - %(message)s') 31 | print(log_filename) 32 | logging.info("==============================================================") 33 | logging.info("Start Script") 34 | 35 | # Loading settings from ini file 36 | try: 37 | config = configparser.ConfigParser() 38 | config.read('settings.ini') 39 | chrome_user = config.get("Settings", "chrome_user") # Username in Chrome browser 40 | width_set = int(config.get("Settings", "width")) # Browser window width 41 | height_set = int(config.get("Settings", "height")) # Browser window height 42 | images_set = int(config.get("Settings", "images")) # turns pictures on and off 43 | stories_set = int(config.get("Settings", "stories")) # count of cycle stories 44 | feed_set = int(config.get("Settings", "feed")) # count of cycle frends feed 45 | feed_select = int(config.get("Settings", "feed_select")) # relevant or new messages in the feed 46 | API_TOKEN = str(config.get("Settings", "token")) # Token telegram bot 47 | BOT_ID = str(config.get("Settings", "botid")) # Telegram ID of the user to whom to send messages 48 | DECTECT_POP = bool((config.get("Birthday", "detect_popup"))) # on\off autodetect popup window 49 | DATE_BIRTHDAY = str(config.get("Birthday", "date")) # ID last date of congratulation 50 | 51 | except Exception as e: 52 | logging.exception("INI load error") 53 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> INI load error") 54 | 55 | 56 | driver = 0 57 | # story counter variables 58 | count_like = 0 59 | count_super = 0 60 | count_together = 0 61 | next_refrash = 0 62 | 63 | 64 | # The function of sending messages to telegrams 65 | def telegram_sendmsg(bot_message): 66 | try: 67 | if API_TOKEN != '0' and BOT_ID != '0' and len(API_TOKEN) > 15 and len(BOT_ID) > 5: 68 | send_text = 'https://api.telegram.org/bot' + API_TOKEN + '/sendMessage?chat_id=' + BOT_ID + '&parse_mode=Html&text=' + bot_message 69 | response = requests.get(send_text) 70 | except Exception as e: 71 | logging.exception(f"Error send message telegram {e}") 72 | 73 | 74 | # Browser window creation function 75 | def start_browser(): 76 | global driver 77 | 78 | # chrome window creation settings 79 | options = webdriver.ChromeOptions() 80 | options.add_argument("disable-infobars") 81 | options.add_experimental_option("excludeSwitches", ["enable-automation"]) 82 | options.add_experimental_option('useAutomationExtension', False) 83 | options.add_argument(f"user-data-dir={os.path.expanduser('~')}\\AppData\\Local\\Google\\Chrome\\User Data\\{chrome_user}") 84 | if images_set == 0: # disable pictures 85 | prefs = {"profile.managed_default_content_settings.images": 2} 86 | options.add_experimental_option("prefs", prefs) 87 | try: 88 | # Create an empty browser window 89 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Create an empty browser window...") 90 | driver = webdriver.Chrome(options=options) 91 | except WebDriverException: 92 | logging.exception("Browser is already running.") 93 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Browser is already running.") 94 | except Exception as e: 95 | logging.exception('Browser is already running.') 96 | 97 | # Browser Disguise 98 | driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { 99 | "source": """ 100 | Object.defineProperty(navigator, 'webdriver', { 101 | get: () => undefined 102 | }) 103 | """ 104 | }) 105 | 106 | driver.execute_cdp_cmd("Network.enable", {}) 107 | driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {"headers": {"User-Agent": "browser1"}}) 108 | # End of Browser Disguise 109 | driver.set_window_rect(10, 10, width_set, height_set) 110 | driver.get("https://facebook.com/") 111 | time.sleep(3) 112 | 113 | size = driver.get_window_size() 114 | position = driver.get_window_position() 115 | print(f"Window size: width = {size['width']}px, height = {size['height']}px, x = {position['x']}, y = {position['y']}") 116 | logging.info(f"Window size: width = {size['width']}px, height = {size['height']}px, x = {position['x']}, y = {position['y']}") 117 | print(driver.capabilities['browserVersion']) 118 | logging.info(driver.capabilities['browserVersion']) 119 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() # press esc to remove pop-ups 120 | time.sleep(1) 121 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() # press esc to remove pop-ups 122 | ActionChains(driver).reset_actions() 123 | 124 | try: 125 | # Close tabs 126 | driver.implicitly_wait(7) 127 | count_close = driver.find_elements(By.CSS_SELECTOR, '[aria-label="Закрыть чат"]') 128 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Found open tabs: {len(count_close)}") 129 | for send_close in count_close: 130 | send_close.click() 131 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Closed tab") 132 | time.sleep(5) 133 | try: 134 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="ОК"]').click() 135 | time.sleep(5) 136 | except Exception as e: 137 | logging.debug(e) 138 | except Exception as e: 139 | logging.debug(e) 140 | 141 | # automatic detect birthdays pop-ups 142 | if DECTECT_POP is True and DATE_BIRTHDAY != str(datetime.date.today()): 143 | gift = driver.find_elements(By.CSS_SELECTOR, "[href='/events/birthdays/']") 144 | if gift: 145 | start_birthday_fb(auto=True) 146 | return False 147 | return True 148 | 149 | 150 | # ----------------------------------------------------------- 151 | # Launch the birthdays function 152 | def start_birthday_fb(auto: bool=False): 153 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Launch the birthdays function") 154 | 155 | if auto is False: 156 | start_browser() 157 | 158 | logging.info('Launch the birthdays function') 159 | telegram_sendmsg("Launch the birthdays function") 160 | 161 | try: 162 | driver.find_elements(By.CSS_SELECTOR, "[href='/events/birthdays/']")[0].click() 163 | time.sleep(random.randrange(15, 20)) 164 | except IndexError as e: 165 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Gift picture not found.") 166 | logging.debug(f"Gift picture not found.\n{e}") 167 | 168 | driver.implicitly_wait(10) # seconds 169 | driver.get("https://www.facebook.com/events/birthdays/") 170 | time.sleep(random.randrange(40, 50)) 171 | birthday_message(var='alt') 172 | else: 173 | birthday_message(var="standard") # Go to the function of sending messages 174 | 175 | 176 | # function of sending birthdays 177 | def birthday_message(var: str): 178 | start_time = time.time() 179 | driver.implicitly_wait(40) # seconds 180 | time.sleep(random.randrange(3, 5)) 181 | 182 | with open("birthday.txt", "r", encoding="utf-8") as f: 183 | birthday = f.readlines() 184 | 185 | count_post = driver.find_elements(By.CSS_SELECTOR, '[method="POST"]') 186 | len_count = len(count_post)-1 187 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Найдено полей для поздавлений: {len_count}") 188 | 189 | count_button = len(driver.find_elements(By.CSS_SELECTOR, '[aria-label="Сообщение"]')) 190 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Найдено кнопок СООБЩЕНИЕ (в личку): {count_button}") 191 | 192 | logging.info(f'Найдено полей для поздавлений: {len_count}') 193 | num_msg = 0 # счетчик отправленных хроник 194 | num_button = 0 195 | 196 | for cv in range(0, 200): # перебираем элементы и когда элемент окажется тектовым - отправляем поздравление 197 | ActionChains(driver).send_keys(Keys.TAB).perform() 198 | element = driver.switch_to.active_element 199 | # if element.find_elements(By.CSS_SELECTOR, 'span'): 200 | # print(element.get_attribute("innerHTML"), "\n") 201 | driver.implicitly_wait(0) 202 | if len_count == num_msg or len_count == 0 or num_msg >= 19: 203 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Поздравления в хронике кончились: {num_msg}. Циклов всего: {cv}") 204 | break 205 | try: 206 | if element.find_elements(By.TAG_NAME, 'br')[0].get_attribute('data-text') == 'true': 207 | try: 208 | cmess = driver.find_elements(By.CSS_SELECTOR, '[method="POST"]') 209 | txt = str(random.choice(birthday).replace("\n", "")) 210 | ActionChains(driver).send_keys_to_element(element, txt, Keys.ENTER).perform() 211 | num_msg += 1 212 | print( 213 | f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Поздравление в хронику №: {num_msg}") 214 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Текст: {txt}") 215 | time.sleep(random.randrange(10, 15)) 216 | ActionChains(driver).reset_actions() 217 | 218 | except NoSuchElementException as e: 219 | print(e) 220 | logging.info(e) 221 | except Exception as e: 222 | print( 223 | f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в цикле отправления поздравлений. Поздравление №: {num_msg}.\n{e}") 224 | logging.exception(f"Ошибка в цикле отправления поздравлений. Поздравление №: {send_msg}.\n{e}") 225 | break 226 | 227 | except NoSuchElementException: 228 | pass 229 | except Exception as e: 230 | logging.debug(f"Поздравления в хронику: {e}") 231 | 232 | if var == "standard": # если запуск не альтернативный, то поздравляем в личку 233 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Начало поздравлений в личку") 234 | if count_button != 1 or count_button == 0: # если 0 и 1 то не перезагружаем страницу 235 | for t in range(0, 2): 236 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() # жмем esc чтобы убрать всплывающие окна 237 | time.sleep(2) 238 | time.sleep(random.randrange(3, 6)) 239 | 240 | driver.implicitly_wait(10) 241 | driver.get("https://www.facebook.com/events/birthdays/") 242 | time.sleep(random.randrange(15, 30)) 243 | 244 | # Поиск кнопки 245 | try: 246 | for msgbut in driver.find_elements(By.CSS_SELECTOR,'[aria-label="Сообщение"]'): 247 | if count_button == num_button or count_button == 0 or num_button >= 15: 248 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Поздравления в личку кончились: {num_button}.") 249 | break 250 | # Клик по кнопке 251 | try: 252 | msgbut.click() 253 | except Exception as e: 254 | break 255 | # print(f'Ошибка в клике по кнопке СООБЩЕНИЕ. Пробуем второй способ {e}') 256 | # logging.info(f'Ошибка в клике по кнопке СООБЩЕНИЕ. Пробуем второй способ {e}') 257 | # ActionChains(driver).move_to_element(msgbut).click().perform() 258 | time.sleep(random.randrange(30, 40)) 259 | try: 260 | element = driver.switch_to.active_element 261 | # print(element.get_attribute("outerHTML"), "\n") 262 | # print(element.get_attribute("role")) 263 | # print(element.parent) 264 | if element.get_attribute("role") == "textbox": 265 | # print(element.get_attribute("innerHTML"), "\n") 266 | txt = str(random.choice(birthday).replace("\n", "")) 267 | ActionChains(driver).send_keys(txt, Keys.ENTER).perform() 268 | num_button += 1 269 | time.sleep(random.randrange(5, 10)) 270 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Поздравление в личку: {num_button}") 271 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Текст: {txt}") 272 | ActionChains(driver).reset_actions() 273 | 274 | driver.implicitly_wait(20) 275 | # закрываем вкладки 276 | count_close = driver.find_elements(By.CSS_SELECTOR, '[aria-label="Закрыть чат"]') 277 | 278 | for send_close in count_close: 279 | send_close.click() 280 | time.sleep(random.randrange(5, 10)) 281 | try: 282 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="ОК"]')[0].click() 283 | except IndexError as e: 284 | logging.debug(e) 285 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Закрыто вкладок: {len(count_close)}") 286 | logging.info(f'Закрыто вкладок: {len(count_close)}') 287 | time.sleep(random.randrange(15, 20)) 288 | except Exception as e: 289 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в поле личных сообщений: {e}") 290 | logging.exception('Ошибка в поле личных сообщений') 291 | break 292 | except Exception as e: 293 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в личных сообщениях: {e}") 294 | logging.warning(f"Ошибка в личных сообщениях: {e}") 295 | 296 | # save date config ini file 297 | if DECTECT_POP is True and DATE_BIRTHDAY != str(datetime.date.today()): 298 | config.set("Birthday", "date", str(datetime.date.today())) 299 | with open('settings.ini', 'w') as configfile: 300 | config.write(configfile) 301 | print(f"DATE: {DATE_BIRTHDAY} vs {datetime.date.today()}") 302 | 303 | logging.info(f'Отправлено поздравлений: {num_msg} из {len_count}') 304 | print(f"\n\nОправлено поздравлений в хронику: {num_msg} из {len_count}") 305 | print(f"Оправлено поздравлений в личку: {num_button} из {count_button}") 306 | print(f'Время выполнения: {round(time.time() - start_time, 1)} секунд') 307 | print(f"\n\n{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ожидание...\n") 308 | 309 | telegram_sendmsg(f"Конец функции BIRTHDAY.\n\nОправлено в хронику: {num_msg} из {len_count}" 310 | f"\nОправлено в личку: {num_button} из {count_button}" 311 | f"\nВремя выполнения: {round(time.time() - start_time, 1)} секунд") 312 | 313 | try: 314 | driver.quit() 315 | except Exception as e: 316 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка закрытия браузера...") 317 | 318 | 319 | # ----------------------------------------------------------- 320 | # Начало функций сториес 321 | def start_stories_fb(): 322 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Старт функции STORIES...") 323 | brow = start_browser() # создаем окно 324 | if brow is False: 325 | telegram_sendmsg("Skipping the Stories function.") 326 | driver.quit() 327 | return None 328 | logging.info('Старт сценария лайков сториес.') 329 | 330 | telegram_sendmsg("Старт сценария лайков STORIES.") 331 | 332 | driver.implicitly_wait(60) # seconds 333 | 334 | time.sleep(random.randrange(5, 10)) 335 | try: 336 | hs_button = driver.find_elements(By.CSS_SELECTOR, "[aria-label='Смотреть все истории']") 337 | if hs_button: 338 | hs_button[0].click() 339 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопка [Смотреть все истории] найдена.") 340 | logging.info("Кнопка ВСЕ ИСТОРИИ НАЙДЕНА.") 341 | time.sleep(20) 342 | stories_likes() 343 | else: 344 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Не найдена кнопка '[Смотреть все истории]'. \n{e}") 345 | logging.exception("Не найдена кнопка '[Смотреть все истории]'.") 346 | driver.quit() 347 | return None 348 | 349 | except Exception as e: 350 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в кнопке [Смотреть все истории] \n{e}") 351 | logging.exception("Ошибка в кнопке [Смотреть все истории].") 352 | stories_fb_alternative() # Ищем на странице кнопку, если не найдена, то переходим на альтернатиынй вариант 353 | 354 | 355 | # альтернативный сценарий входа в сториес 356 | def stories_fb_alternative(): 357 | logging.info("Включение функции альтернативного сценария сториес") 358 | 359 | driver.implicitly_wait(15) # seconds 360 | driver.get("https://www.facebook.com/stories") 361 | time.sleep(10) 362 | 363 | # перемещаемся по ссылкам на сториес человека 364 | ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB).perform() # нужны три таба, но плюс один когда есть своя сториес. 365 | time.sleep(random.randrange(5, 8)) 366 | ActionChains(driver).send_keys(Keys.RETURN).perform() 367 | stories_likes() # переходим в функцию поиска кнопок и лайков 368 | 369 | 370 | # кнопки лайк, супер и звук и тд... 371 | def stories_button(button, stories=None): 372 | # переменные счетчиков 373 | global count_like 374 | global count_super 375 | global count_together 376 | global next_refrash 377 | 378 | wait = WebDriverWait(driver, 3) 379 | driver.implicitly_wait(0) 380 | 381 | # Отключаем звук на компе 382 | if button == 'sound': 383 | try: 384 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="Выключить звук"]')[0].click() 385 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Звук выключен") 386 | except Exception as e: 387 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка кнопки вкл\выкл звука...\n{e}") 388 | logging.info("Ошибка кнопки вкл\выкл звука...\n{e}") 389 | 390 | elif button == 'like': 391 | buttonLIKE = driver.find_elements(By.CSS_SELECTOR, '[aria-label="Нравится"]') 392 | for btn_like in buttonLIKE: 393 | try: 394 | btn_like.click() 395 | # print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопка лайк - найдена...") 396 | break 397 | except Exception as e: 398 | logging.debug('Like button not found') 399 | # print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопка ЛАЙК не найдена. Ищем дальше...") 400 | count_like = count_like + 1 401 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - ЛАЙК...") 402 | elif button == 'love': 403 | try: 404 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="Супер"]')[0].click() 405 | except Exception as e: 406 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопка SUPER не найдена.\n{e}") 407 | logging.info(f"Блок Сториес. Не найдена кнопка SUPER.\n{e}") 408 | else: 409 | count_super += 1 410 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - СУПЕР...") 411 | 412 | elif button == 'cave': 413 | try: 414 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="Мы вместе"]')[0].click() 415 | except Exception as e: 416 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопка МЫ ВМЕСТЕ не найдена.\n{e}") 417 | logging.info(f"Блок Сториес. Не найдена кнопка МЫ ВМЕСТЕ.\n{e}") 418 | else: 419 | count_together += 1 # счетчик мы вместе 420 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} - МЫ ВМЕСТЕ..") 421 | elif button == 'next': 422 | # NEXT 423 | try: 424 | wait = WebDriverWait(driver, 1) 425 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '''[aria-label='Кнопка "Следующая подборка"']'''))).click() 426 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Кнопка: Следующая подборка") 427 | next_refrash = 0 # clear count error 428 | except Exception as e: 429 | try: 430 | wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '''[aria-label='Кнопка "Следующая открытка"']'''))).click() 431 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories} Кнопка: Следующая открытка") 432 | next_refrash = 0 # clear count error 433 | except Exception as e: 434 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Не найдены обе кнопки NEXT. Обновление...") 435 | logging.debug("Блок Сториес. Не найдены кнопки NEXT. Обновление.") 436 | 437 | next_refrash += 1 438 | 439 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Обновление окна.") 440 | logging.info('Refresh browser. No button NEXT') 441 | driver.get("https://www.facebook.com/stories") 442 | time.sleep(random.randrange(10, 15)) 443 | # перемещаемся по ссылкам на сториес человека 444 | try: 445 | driver.find_elements(By.LINK_TEXT, 'Воспроизвести все')[0].click() 446 | except Exception as e: 447 | logging.exception("no found text link") 448 | driver.quit() 449 | 450 | time.sleep(random.randrange(4, 8)) 451 | try: 452 | driver.find_elements(By.CSS_SELECTOR, '[aria-label="Выключить звук"]')[0].click() 453 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Звук выключен") 454 | except Exception as e: 455 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка кнопки вкл\выкл звука...\n{e}") 456 | logging.info(f"Ошибка кнопки вкл\выкл звука...\n{e}") 457 | 458 | 459 | # основная функция лайков сториес 460 | def stories_likes(): 461 | count_next = 0 462 | count_skip = 0 463 | global next_refrash 464 | list_names = [] 465 | start_time = time.time() 466 | wait = WebDriverWait(driver, 30) 467 | driver.implicitly_wait(30) # seconds 468 | 469 | try: 470 | driver.find_elements(By.LINK_TEXT, 'Воспроизвести все')[0].click() 471 | print('Кнопка "Воспроизвести все" найдена.') 472 | except NoSuchElementException: 473 | print('Кнопка "Воспроизвести все" не найдена.') 474 | ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, 475 | Keys.TAB).perform() # нужны три таба, но плюс один когда есть своя сториес. 476 | time.sleep(random.randrange(5, 8)) 477 | ActionChains(driver).send_keys(Keys.RETURN).perform() 478 | 479 | driver.implicitly_wait(5) # seconds 480 | stories_button('sound') 481 | try: 482 | # Главный Цикл лайков 483 | for stories in range(0, stories_set): 484 | # wait = WebDriverWait(driver, 4) 485 | 486 | # Находим имя и добавляем в список 487 | try: 488 | getms = driver.find_elements(By.CSS_SELECTOR, '[data-pagelet="StoriesContentPane"]')[0].find_elements(By.TAG_NAME, 'img') 489 | for x in getms: 490 | try: 491 | if x.get_attribute('height') == "40" and x.get_attribute('width') == "40": 492 | # print(x.get_attribute('alt')) 493 | getms = x.get_attribute('alt') 494 | break 495 | except Exception as e: 496 | getms = None 497 | # list_names = [] 498 | print(f"Не определилось имя...\n{e}") 499 | print(getms) 500 | list_names.append(getms) 501 | # print(list_names) 502 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {getms}: {list_names.count(getms)}") 503 | except Exception as e: 504 | print("Не найдено") 505 | print(e) 506 | # list_names = [] 507 | getms = None 508 | 509 | # Пропускаем длинные сториес 510 | if list_names.count(getms) >= 4: 511 | for xm in range(0, 20): 512 | 513 | try: 514 | getms = driver.find_elements(By.CSS_SELECTOR, '[data-pagelet="StoriesContentPane"]')[0].find_elements(By.TAG_NAME, 'img') 515 | for x in getms: 516 | if x.get_attribute('height') == "40" and x.get_attribute('width') == "40": 517 | # print(x.get_attribute('alt')) 518 | getms = x.get_attribute('alt') 519 | break 520 | except Exception as e: 521 | print(f"Не определилось имя в пропуске... {e}") 522 | list_names = [] 523 | getms = None 524 | 525 | if list_names.count(getms) >= 4: 526 | ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() 527 | 528 | # NEXT 529 | stories_button('next', stories) 530 | 531 | count_next += 1 532 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {getms} больше трех раз. Пропускаем.\n") 533 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Цикл № {stories + 1} из {stories_set} ...") 534 | else: 535 | break 536 | else: 537 | # print(getms.get_attribute("innerHTML"), "\n") 538 | 539 | rnd_like = random.randrange(1, 9) 540 | # генерация разных сценариев лайков 541 | if rnd_like == 1: 542 | # Одинарный лайк 543 | stories_button('like', stories) 544 | time.sleep(1) 545 | 546 | elif rnd_like == 2: 547 | # Одинарный супер 548 | stories_button('love', stories) 549 | time.sleep(1) 550 | 551 | elif rnd_like == 3: 552 | # Несколько лайков 553 | for mkmk in range(0, random.randrange(2, 5)): 554 | stories_button('like', stories) 555 | time.sleep(1) 556 | 557 | elif rnd_like == 4: 558 | # Несколько Супер 559 | for mkmk in range(0, random.randrange(2, 5)): 560 | stories_button('love', stories) 561 | time.sleep(1) 562 | 563 | elif rnd_like == 5: 564 | # Лайк + Супер 565 | stories_button('like', stories) 566 | time.sleep(random.randrange(1, 4)) 567 | stories_button('love', stories) 568 | time.sleep(1) 569 | 570 | elif rnd_like == 6: 571 | # Супер + Лайк 572 | stories_button('love', stories) 573 | time.sleep(random.randrange(1, 4)) 574 | stories_button('like', stories) 575 | time.sleep(1) 576 | 577 | elif rnd_like == 7: 578 | # Лайк, супер, мы вместе 579 | stories_button('like', stories) 580 | time.sleep(random.randrange(1, 4)) 581 | 582 | stories_button('love', stories) 583 | time.sleep(random.randrange(2, 4)) 584 | stories_button('cave', stories) 585 | time.sleep(1) 586 | 587 | elif rnd_like == 8: 588 | # Мы вместе 589 | stories_button('cave', stories) 590 | time.sleep(1) 591 | 592 | # driver.get_screenshot_as_file(f"png\\{datetime.datetime.now().strftime('%d-%m-%y-%H-%M-%S')}.png") 593 | # NEXT 594 | stories_button('next', stories) 595 | if next_refrash == 3: # if repeat error no button NEXT - quit browser 596 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Кнопки не найдены. Закрываем браузер...") 597 | logging.warning("Не найдены кнопки NEXT. Закрываем браузер.") 598 | driver.quit() 599 | break 600 | 601 | count_next += 1 602 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Цикл № {stories + 1} из {stories_set} ...") 603 | time.sleep(random.randrange(2, 4)) 604 | 605 | if stories_set - 1 == stories: # если цикл закончен, закрываем браузер 606 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> {stories + 1} - Цикл лайков успешно завершен") 607 | logging.info(f"Кол-во: {stories + 1} - Цикл лайков успешно завершен.") 608 | 609 | driver.quit() 610 | print(f"\n\nПоставлено лайков: {count_like}\nПоставленно сердечек: {count_super}\nПоставлено Мы вместе: " 611 | f"{count_together}\nПролистано: {count_next}\nВсего циклов: {stories + 1}\nВремя выполнения: " 612 | f"{round(time.time() - start_time, 1)} секунд") 613 | print(f"\n\n{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ожидание...\n") 614 | 615 | telegram_sendmsg(f"Конец функции LIKE STORIES:\n\nПоставлено лайков: {count_like}\nПоставленно сердечек: {count_super}" 616 | f"\nПоставлено Мы вместе: {count_together}\nПролистано: {count_next}" 617 | f"\nВсего циклов: {stories + 1}\nВремя выполнения: {round(time.time() - start_time, 1)} секунд") 618 | 619 | 620 | except Exception as e: 621 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в блоке цикла генерации вариантов лайков {e}") 622 | logging.exception("Функция лайков сториес. Ошибка в блоке цикла генерации вариантов лайков") 623 | driver.quit() 624 | 625 | 626 | # ----------------------------------------------------------- 627 | # Функция начала лайков в ленте 628 | def start_feed_likes(): 629 | logging.info("Старт сценария лайков ленты новостей.") 630 | 631 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Старт функции LIKES FEED...") 632 | 633 | brow = start_browser() # создаем окно 634 | if brow is False: 635 | telegram_sendmsg("Skipping the likes feed function.") 636 | driver.quit() 637 | return None 638 | telegram_sendmsg("Старт сценария лайков ленты новостей.") 639 | 640 | if feed_select != 0: 641 | driver.get("https://www.facebook.com/?sk=h_chr") 642 | 643 | feed_likes() 644 | 645 | 646 | # Основная функция лайков ленты друзей 647 | def feed_likes(): 648 | # переменные счетчиков 649 | count_ad = 0 650 | count_next = 0 651 | count_group = 0 652 | count_like = 0 653 | count_super = 0 654 | count_cave = 0 655 | time.sleep(random.randrange(20, 30)) 656 | start_time = time.time() 657 | driver.implicitly_wait(0) # seconds 658 | # основной цикл 659 | try: 660 | for x_all in range(0, feed_set): 661 | # driver.get_screenshot_as_file(f"png\\{datetime.datetime.now().strftime('%d-%m-%y-%H-%M-%S')}.png") 662 | ActionChains(driver).send_keys(Keys.ESCAPE).perform() # жмем esc чтобы убрать всплывающие окна 663 | time.sleep(random.randrange(1, 3)) 664 | 665 | ActionChains(driver).send_keys("j").perform() # Next Post 666 | 667 | element = driver.switch_to.active_element 668 | 669 | # print(element.get_attribute("innerHTML"), "\n") 670 | if element.find_elements(By.CSS_SELECTOR, '[dir="ltr"]'): 671 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Найдено сообщество. Пропускаем...") 672 | count_group += 1 673 | elif element.find_elements(By.CSS_SELECTOR, '[aria-label="Реклама"]'): 674 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Найдена реклама. Пропускаем...") 675 | count_ad += 1 676 | time.sleep(random.randrange(3, 6)) 677 | elif element.find_elements(By.CSS_SELECTOR, '[aria-label="Нравится"]'): 678 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Пост найден. Лайкаем...") 679 | 680 | time.sleep(random.randrange(6, 10)) 681 | 682 | ActionChains(driver).send_keys("l").perform() # Press Like 683 | ActionChains(driver).reset_actions() 684 | time.sleep(random.randrange(7, 10)) 685 | 686 | rnd_like_feed = random.randrange(1, 4) 687 | try: 688 | if rnd_like_feed == 1: 689 | ActionChains(driver).send_keys(Keys.SPACE).perform() # жмем пробел 690 | count_like += 1 691 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Нравится: {count_like}") 692 | 693 | elif rnd_like_feed == 2: 694 | ActionChains(driver).send_keys(Keys.RIGHT).perform() # жмем право 695 | time.sleep(random.randrange(2, 4)) 696 | ActionChains(driver).send_keys(Keys.SPACE).perform() # жмем пробел 697 | count_super += 1 698 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Супер: {count_super}") 699 | 700 | elif rnd_like_feed == 3: 701 | ActionChains(driver).send_keys(Keys.RIGHT, Keys.RIGHT).perform() # жмем право 702 | time.sleep(random.randrange(2, 4)) 703 | ActionChains(driver).send_keys(Keys.SPACE).perform() # жмем пробел 704 | count_cave += 1 705 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Мы вместе: {count_cave}") 706 | 707 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Сделано циклов {x_all + 1} из {feed_set}\n") 708 | ActionChains(driver).reset_actions() 709 | 710 | time.sleep(random.randrange(1, 5)) 711 | except TimeoutException as e: 712 | logging.exception(e) 713 | break 714 | except Exception as e: 715 | logging.exception(e) 716 | break 717 | else: 718 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Обнаружен уже поставленный лайк. Пропускаем...") 719 | count_next += 1 720 | 721 | if x_all == feed_set - 1: 722 | time.sleep(random.randrange(4, 7)) 723 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Цикл лайков ленты закончен.") 724 | print( 725 | f"\nНравится: {count_like}\nСупер: {count_super}\nМы вместе: {count_cave}" 726 | f"\nПропущено рекламы: {count_ad}\nПропущено сообществ: {count_group}\nУже было лайков: {count_next}\nВсего циклов: {feed_set}" 727 | f"\nСделано циклов: {x_all + 1}\nВремя выполнения: {round(time.time() - start_time, 1)} секунд") 728 | print(f"\n\n{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ожидание...\n") 729 | logging.info("Цикл лайков ленты закончен") 730 | 731 | telegram_sendmsg(f"Конец функции ЛАЙКИ ЛЕНТЫ НОВОСТЕЙ:\nНравится: {count_like}" 732 | f"\nСупер: {count_super}\nМы вместе: {count_cave}\nПропущено рекламы: {count_ad}" 733 | f"\nПропущено сообществ: {count_group}\nУже было лайков: {count_next}\nСделано циклов: {x_all + 1} из {feed_set}" 734 | f"\nВремя выполнения: {round(time.time() - start_time, 1)} секунд") 735 | driver.quit() 736 | 737 | except Exception as e: 738 | print(f"{datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')} >> Ошибка в блоке лайков ленты друзей {e}") 739 | logging.exception("Ошибка в блоке лайков ленты друзей") 740 | driver.quit() 741 | 742 | 743 | # Отрыть ini файл 744 | def open_file(): 745 | with open('settings.ini', "r") as input_file: 746 | text = input_file.read() 747 | txt_edit.insert(tk.END, text) 748 | window.title(f"Facebook autoclicker") 749 | 750 | 751 | # Сохранить ini файл 752 | def save_file(): 753 | with open('settings.ini', "w") as output_file: 754 | text = txt_edit.get(1.0, tk.END) 755 | output_file.write(text) 756 | 757 | 758 | window = tk.Tk() 759 | window.title("facebook-auto-liker-bot") 760 | window.rowconfigure(0, minsize=500, weight=1) 761 | window.columnconfigure(1, minsize=800, weight=1) 762 | 763 | txt_edit = tk.Text(window) 764 | fr_buttons = tk.Frame(window, relief=tk.RAISED) 765 | btn_open = tk.Button(fr_buttons, text="Открыть", command=open_file) 766 | btn_save = tk.Button(fr_buttons, text="Сохранить", command=save_file) 767 | 768 | # Текущая версия: {version}\nПоследняя версия: {upd_version} 769 | 770 | button1 = tk.Button(fr_buttons, text="Лайки сториес", bg="blue", fg="yellow", command=start_stories_fb) 771 | button2 = tk.Button(fr_buttons, text="Лайки ленты", bg="orange", fg="blue", command=start_feed_likes) 772 | button3 = tk.Button(fr_buttons, text="Поздравления с ДР", bg="purple", fg="white", command=start_birthday_fb) 773 | 774 | label1 = tk.Label(fr_buttons, text=f"Настройки бота\n") 775 | label2 = tk.Label(fr_buttons, text=f"\nФункции бота\n") 776 | label4 = tk.Label(fr_buttons, text=f"\n\nЭта программа написана для тестов\nбраузера на примере facebook." 777 | f"\nИспользуйте на свой страх и риск.\nАвтор не несет ответственности за" 778 | f"\nущерб от данной программы.") 779 | 780 | site_link = tk.Entry(fr_buttons) 781 | label1.grid(row=0, column=0) 782 | btn_open.grid(row=1, column=0, sticky="ew") 783 | btn_save.grid(row=2, column=0, sticky="ew") 784 | 785 | label2.grid(row=3, column=0) 786 | fr_buttons.grid(row=0, column=0, sticky="ns") 787 | txt_edit.grid(row=0, column=1, sticky="nsew") 788 | 789 | button1.grid(row=4, column=0) 790 | button2.grid(row=5, column=0) 791 | button3.grid(row=6, column=0) 792 | site_link.grid(row=8, column=0) 793 | site_link.insert(0, 'https://github.com/doevent/facebook-auto-liker') 794 | label4.grid(row=9, column=0) 795 | 796 | 797 | if __name__ == "__main__": 798 | parser = argparse.ArgumentParser() 799 | parser.add_argument('name', nargs='?') 800 | namespace = parser.parse_args() 801 | 802 | # запуск из командной строки 803 | if namespace.name == 'story': 804 | start_stories_fb() 805 | elif namespace.name == 'feed': 806 | start_feed_likes() 807 | elif namespace.name == 'birthday': 808 | start_birthday_fb(auto=False) 809 | else: 810 | window.mainloop() 811 | --------------------------------------------------------------------------------