Modified quite a few things

This commit is contained in:
Joan
2023-10-07 23:33:57 +02:00
parent a8c1b9d48e
commit ca6ba95c8c
4 changed files with 59 additions and 74 deletions

View File

@@ -1,4 +1,6 @@
SLEEP_QRCODE = 30 SLEEP_QRCODE = 30
SLEEP_LONG = 15 SLEEP_LONG = 15
SLEEP_SHORT = 1 SLEEP_SHORT = 1
REQUEST_URL = "http://example.com" REQUEST_URL = "http://example.com"
MAIL = "test@example.com"
PHONE = "666666666"

View File

@@ -10,7 +10,9 @@ RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable
RUN apt-get -y update RUN apt-get -y update
# Magic happens # Magic happens
RUN apt-get install -y google-chrome-stable RUN wget -O /tmp/google-chrome-stable.deb http://mirror.cs.uchicago.edu/google-chrome/pool/main/g/google-chrome-stable/google-chrome-stable_`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`-1_amd64.deb
RUN apt install -y /tmp/google-chrome-stable.deb
#RUN apt-get install -y google-chrome-stable
# Installing Unzip # Installing Unzip
RUN apt-get install -yqq unzip RUN apt-get install -yqq unzip

View File

@@ -5,10 +5,12 @@ import logging
from datetime import datetime from datetime import datetime
import requests import requests
import json import json
import base64
from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver from selenium import webdriver
logging.basicConfig( logging.basicConfig(
@@ -21,6 +23,8 @@ SLEEP_QRCODE = int(os.environ.get("SLEEP_QRCODE")) #30
SLEEP_LONG = int(os.environ.get("SLEEP_LONG")) #15 SLEEP_LONG = int(os.environ.get("SLEEP_LONG")) #15
SLEEP_SHORT = int(os.environ.get("SLEEP_SHORT")) #1 SLEEP_SHORT = int(os.environ.get("SLEEP_SHORT")) #1
REQUEST_URL = os.environ.get("REQUEST_URL") REQUEST_URL = os.environ.get("REQUEST_URL")
MAIL = os.environ.get("MAIL")
PHONE = os.environ.get("PHONE")
def get_chrome_options(): def get_chrome_options():
chrome_options = Options() chrome_options = Options()
@@ -37,45 +41,48 @@ def get_chrome_options():
def get_time(): def get_time():
return datetime.today().strftime('%Y-%m-%d-%H-%M-%S') return datetime.today().strftime('%Y-%m-%d-%H-%M-%S')
def find_number(number, driver): def whatsapp_login(driver):
logging.info(f"Searching for {number} in self conversation")
messages = driver.find_elements(By.CLASS_NAME, "selectable-text")
for message in messages:
if number in message.text:
message.click()
time.sleep(SLEEP_SHORT)
ltr = driver.find_elements(By.XPATH, '//span[@dir = "ltr"]')
for chat_with in ltr:
if number == chat_with.text.replace(" ", ""):
logging.info(f"{number} found")
return chat_with
time.sleep(SLEEP_SHORT)
break
def send_qr_code(location):
#requests.post(f"{REQUEST_URL}/send_qr", )
pass
def whatsapp_login(driver, tri=1):
driver.get("https://web.whatsapp.com/") driver.get("https://web.whatsapp.com/")
time.sleep(SLEEP_LONG) time.sleep(SLEEP_LONG)
if tri > 5: logged_in = False
logging.error(f"Couldn't login after {tri} tries") location = "/app/data/login.png"
return False driver.save_screenshot(location)
try: if not("QR code" in driver.page_source or "código QR" in driver.page_source):
driver.find_element(By.XPATH, '//span[@data-testid = "qrcode"]') logged_in = True
logging.info("Not logged in! Saving QR code and waiting 30 seconds")
location = f"/app/data/login-{get_time()}.png" while "QR code" in driver.page_source or "código QR" in driver.page_source:
driver.save_screenshot(location) logging.info("Not logged in! Comencing loop")
send_qr_code(location) requests.get(f"{REQUEST_URL}/solicitasesion.php?mail={MAIL}&phone={PHONE}")
time.sleep(SLEEP_QRCODE) logging.info(f"Requested session, waiting for {SLEEP_LONG} seconds...")
time.sleep(SLEEP_LONG)
while True:
response = requests.get(f"{REQUEST_URL}/abresesion.php")
logging.info("Checking if someones there...")
if response.content == "SI":
logging.info("Someones there! Getting QR code...")
driver.get("https://web.whatsapp.com/")
time.sleep(SLEEP_LONG)
driver.save_screenshot(location)
with open(location, "rb") as qrcode:
encoded_string = base64.b64encode(qrcode.read())
requests.post(f"{REQUEST_URL}/qrsesion.php", data=encoded_string)
logging.info("QR code sent through POST request! Waiting for user to scan it")
time.sleep(SLEEP_QRCODE)
driver.get("https://web.whatsapp.com/")
logging.info("Loading Whatsapp page again...")
time.sleep(SLEEP_LONG)
if "QR code" in driver.page_source or "código QR" in driver.page_source:
logging.info("Not logged in yet, doing another loop")
else:
logging.info("Logged in succesfully, continuing!")
logged_in = True
break
time.sleep(5)
pickle.dump(driver.get_cookies(), open("/app/data/cookies.pkl", "wb")) pickle.dump(driver.get_cookies(), open("/app/data/cookies.pkl", "wb"))
return whatsapp_login(driver, tri)
except: return logged_in
logging.info("Already logged in")
return True
def setup_driver(): def setup_driver():
driver = webdriver.Chrome(options=get_chrome_options()) driver = webdriver.Chrome(options=get_chrome_options())
@@ -88,21 +95,6 @@ def setup_driver():
return driver return driver
def go_to_self(driver):
logging.info("Going to self conversation")
new_chats = driver.find_element(By.XPATH, '//span[@data-testid = "chat"]')
new_chats.click()
time.sleep(SLEEP_SHORT)
user = driver.find_element(By.XPATH, '//span[@data-testid = "you-label"]')
user.click()
time.sleep(SLEEP_SHORT)
def send_message(message, driver):
logging.info(f"Sending message: {message}")
input_box = driver.find_element(By.XPATH, '//div[@data-testid = "conversation-compose-box-input"]')
input_box.send_keys(message + Keys.ENTER)
time.sleep(SLEEP_SHORT)
def message_check(message, status): def message_check(message, status):
try: try:
requests.get(f"{REQUEST_URL}/message_status?id={message['id']}&status={status}") requests.get(f"{REQUEST_URL}/message_status?id={message['id']}&status={status}")
@@ -115,38 +107,25 @@ def send_messages(messages):
return False return False
for message in messages: for message in messages:
go_to_self(driver) driver.get(f"https://web.whatsapp.com/send?phone={message['number']}&text={message['message']}")
conversation_link = find_number(message['number'], driver) time.sleep(SLEEP_LONG)
if conversation_link == None: actions = ActionChains(driver)
logging.info("Number not found, sending message to self") actions.send_keys(Keys.ENTER)
send_message(message['number'], driver) actions.perform()
conversation_link = find_number(message['number'], driver)
if conversation_link == None:
logging.error(f"Number {message['number']} may not be valid, couldn't click on link to open chat")
message_check(message, 'number_not_valid')
continue
conversation_link.click()
time.sleep(SLEEP_SHORT)
logging.info(f"Sending message to {message['number']}")
send_message(message['message'], driver)
message_check(message, 'ok') message_check(message, 'ok')
#driver.save_screenshot(f"/app/data/logged-{get_time()}.png")
driver.close() driver.close()
return True return True
def main() -> None: def main() -> None:
messages_json = '[{"id": "1", "number": "+34666666666", "message": "Mensaje de prueba 1"},{"id": "2", "number": "+34666666666", "message": "Mensaje de prueba 2"},{"id": "3", "number": "+34666666666", "message": "Mensaje de prueba 3"}]' #messages_json = '[{"id": "1", "number": "+34666666666", "message": "Mensaje de prueba 1"}]'
while True: while True:
time.sleep(5) time.sleep(5)
try: try:
logging.info("Checking for new messages...") logging.info("Checking for new messages...")
#response = requests.get(REQUEST_URL) response = requests.get(REQUEST_URL)
#if response.content != '': if response.content != '':
if True: messages = json.loads(response.content)
#messages = json.loads(response.content)
messages = json.loads(messages_json)
if send_messages(messages): if send_messages(messages):
logging.info("Messages sent successful") logging.info("Messages sent successful")
else: else:

View File

@@ -12,4 +12,6 @@ services:
- SLEEP_QRCODE=${SLEEP_QRCODE} - SLEEP_QRCODE=${SLEEP_QRCODE}
- SLEEP_LONG=${SLEEP_LONG} - SLEEP_LONG=${SLEEP_LONG}
- SLEEP_SHORT=${SLEEP_SHORT} - SLEEP_SHORT=${SLEEP_SHORT}
- REQUEST_URL=${REQUEST_URL} - REQUEST_URL=${REQUEST_URL}
- MAIL=${MAIL}
- PHONE=${PHONE}