-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvisa_bot.py
executable file
·320 lines (234 loc) · 12 KB
/
visa_bot.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# -*- coding: utf-8 -*-
from email import message
import json
import token
import undetected_chromedriver as uc
from time import sleep
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import requests
import re
from notifiers import get_notifier
from auth_data import API_key, email, phone, telegram_bot_token, user_id, emailPin, numberOfCitiesMonitoring #Enter your data in auth_data.py !!!!!!!!!!!!
if __name__ == "__main__":
seconds = time.time()
loop = 1
count = 0
driver = uc.Chrome()
result_list = []
cities_list = ["Москва", "Казань", "Екатеринбург", "Ростов-на-Дону", "Новосибирск", "Нижний Новгород", "Самара"]
window_handlers = {
"Москва" : 0,
"Казань" : 0,
"Екатеринбург" : 0,
"Ростов-на-Дону" : 0,
"Новосибирск" : 0,
"Нижний Новгород" : 0,
"Самара" : 0,
"Почта" : 0
}
request_id = dict(window_handlers)
otp_token = dict(window_handlers)
telegram = get_notifier('telegram')
def check_exists_by_xpath(xpath):
try:
driver.find_element(By.XPATH, xpath)
except NoSuchElementException:
return False
return True
def check_exists_by_id(id):
try:
driver.find_element(By.ID, id)
except NoSuchElementException:
return False
return True
def wait(elem_type, elem):
try:
WebDriverWait(driver, 20).until(EC.presence_of_element_located((elem_type, elem)))
except:
if (check_exists_by_id("cf-challenge-hcaptcha-wrapper") and check_exists_by_id("cf-challenge-running")):
current_url = driver.current_url
driver.close()
driver.switch_to.new_window("tab")
driver.get(current_url)
else:
driver.refresh()
print("Error... Refreshing...")
wait(elem_type, elem)
def auth():
#Проверяем нет ли открытых вкладок с прошлых попыток бота
if len(driver.window_handles) != 1:
while len(driver.window_handles) != 1:
driver.switch_to.window(driver.window_handles[-1])
driver.close()
# Открываем страницы городов и отправляем капчи на решение
for city in cities_list[:numberOfCitiesMonitoring]: # "numberOfCitiesMonitoring" отвечает за количкство городов в работе
initial_auth(city)
sleep(1)
telegram.notify(token=telegram_bot_token, chat_id=user_id, message="Начинаю аунтефикацию!")
# Получаем OTP ключи для каждого города
for city in cities_list[:numberOfCitiesMonitoring]: #"numberOfCitiesMonitoring" отвечает за количкство городов в работе
OTP_auth(city)
# Ждём решения капчи и завершаем авторизацию
# for city in cities_list:
# wait_for_captha(city)
# Blsspain Page
def initial_auth(city):
initial_url = "https://blsspain-russia.com/moscow/apply_for.php"
try:
driver.get(initial_url)
except:
driver.switch_to.window(driver.window_handles[-1])
driver.close()
driver.switch_to.new_window("tab")
driver.get(initial_url)
window_handlers[city] = driver.current_window_handle #Записали ID текущей вкладки под названием города
wait(By.CLASS_NAME, "appByIndFam")
driver.find_elements(By.CLASS_NAME, "appByIndFam")[-1].click()
wait(By.LINK_TEXT, "Продолжить оформление записи")
driver.find_element(By.LINK_TEXT, "Продолжить оформление записи").click()
# hCaptcha
wait(By.CLASS_NAME, "h-captcha")
data_sitekey = driver.find_element(By.CLASS_NAME, "h-captcha").get_attribute("data-sitekey")
print(data_sitekey)
URL = f"http://rucaptcha.com/in.php?key={API_key}&method=hcaptcha&sitekey={data_sitekey}&pageurl=https://blsspain-russia.com/moscow/book_appointment.php&json=1"
response = requests.get(URL).json()
print(response)
request_id[city] = response["request"] # Отправили капчу на распознавание и записали ID запроса для ЭТОЙ вкладки
print(f"{city} Request ID = " + request_id[city])
wait(By.ID, "centre") # Выбрали город
city_list = Select(driver.find_element(By.ID, "centre"))
city_list.select_by_visible_text(city)
driver.switch_to.new_window('window') # Открыли новую вкладку для следующего города
def OTP_auth(city):
driver.switch_to.window(window_handlers[city]) #Переключаемся на вкладку нужного города
wait(By.ID, "category")
category_list = Select(driver.find_element(By.ID, "category"))
category_list.select_by_visible_text("Обычная подача")
wait(By.ID, "phone")
driver.find_element(By.ID, "phone").send_keys(phone)
driver.find_element(By.ID, "email").send_keys((email[city]))
driver.find_element(By.ID, "email").send_keys(("@mailto.plus"))
try:
driver.find_element(By.XPATH, '//a[@onclick="setCookie();"]').click()
except:
print("No cookie pop-up")
driver.find_element(By.ID, "verification_code").click()
sleep(1)
# Tempmail Page
driver.switch_to.new_window("tab")
window_handlers["Почта"] = driver.current_window_handle
driver.get("https://tempmail.plus/ru/#!")
try:
wait(By.ID, "pre_button")
driver.find_element(By.ID, "pre_button").send_keys(Keys.BACKSPACE*20)
driver.find_element(By.ID, "pre_button").send_keys(email[city])
driver.find_element(By.ID, "pre_button").send_keys(Keys.ENTER)
except:
print("Mail already log-in")
try:
sleep(1)
wait(By.ID, "pin")
driver.find_element(By.ID, "pin").send_keys(emailPin)
driver.find_element(By.ID, "verify").click()
except:
print("Don't need pin")
wait(By.XPATH, "//span[@class='font-weight-bold']")
driver.find_element(By.XPATH, "//span[@class='font-weight-bold']").click()
wait(By.LINK_TEXT, "Click here to view your verification code")
driver.find_element(By.LINK_TEXT, "Click here to view your verification code").click()
driver.close()
#Select and switch to OTP Page
# for window_handler in driver.window_handles:
# if window_handler not in window_handlers.values():
# driver.switch_to.window(window_handler)
# break
# OTP Page
driver.switch_to.window(driver.window_handles[-1])
wait(By.XPATH, "//input[@type='text']")
driver.find_element(By.XPATH, "//input[@type='text']").send_keys((email[city]))
driver.find_element(By.XPATH, "//input[@type='text']").send_keys(("@mailto.plus"))
driver.find_element(By.XPATH, "//input[@type='submit']").click()
wait(By.CLASS_NAME, "blurry-text")
otp_token[city] = driver.find_element(By.CLASS_NAME, "blurry-text").get_attribute("textContent").split(" ")[3] # Переменная с токеном
print(f"{city} OTP Token:", otp_token[city])
# Close OTP Page
driver.close()
# Blsspain Page
driver.switch_to.window(window_handlers[city])
sleep(1)
driver.find_element(By.ID, "otp").send_keys(otp_token[city])
# def wait_for_captha(city):
driver.switch_to.window(window_handlers[city])
URL = f"http://rucaptcha.com/res.php?key={API_key}&action=get&id={request_id[city]}&json=1"
print(URL)
response = requests.get(URL).json()
print(response)
while response["status"] == 0:
sleep(5)
print(f"{city} Captcha Not Ready Yet")
response = requests.get(URL).json()
print("Request Result: " + response["request"])
captcha_response = response["request"]
driver.execute_script(f"document.querySelector('textarea[name=\"g-recaptcha-response\"]').innerHTML = '{captcha_response}'")
driver.execute_script(f"document.querySelector('textarea[name=\"h-captcha-response\"]').innerHTML = '{captcha_response}'")
try:
driver.find_element(By.XPATH, '//a[@onclick="setCookie();"]').click()
except:
print("No cookie pop-up")
wait(By.XPATH, '//input[@onclick="return validateFrm();"]')
driver.find_element(By.XPATH, '//input[@onclick="return validateFrm();"]').click()
#Agree BTN
wait(By.NAME, "agree")
driver.find_element(By.NAME, "agree").click()
sleep(2)
def resultYes():
while True:
telegram.notify(token=telegram_bot_token, chat_id=user_id, message="Есть место, Хозяин!")
sleep(10)
def check_data_loop(cit):
try:
driver.switch_to.window(window_handlers[cit])
driver.find_element(By.ID, "app_date").is_displayed()
driver.find_element(By.ID, "app_date").click()
wait(By.CLASS_NAME, "table-condensed")
date_table = driver.find_element(By.CLASS_NAME, "table-condensed")
# count = count + 1
fullCapicity_dates = re.search(r'var fullCapicity_dates = (.*?);', driver.page_source).group().split(" = ")[1].replace("[", "").replace("]", "").replace('"', '').replace(";", "").split(",")
available_dates = re.search(r'var available_dates = (.*?);', driver.page_source).group().split(" = ")[1].replace("[", "").replace("]", "").replace('"', '').replace(";", "").split(",")
if (len(available_dates) <= 1):
result = "No"
else:
result = "YES"
result_list = []
result_list.append(
{
"result" : result,
"city" : cit,
# "number" : count,
"time" : time.strftime('%H:%M:%S'),
"available dates" : available_dates,
"full capicity dates" : fullCapicity_dates
}
)
with open(f"./cities/{cit}/log.json", "w") as file:
json.dump(result_list, file, indent=4, ensure_ascii=False)
date_table.screenshot(f"./cities/{cit}/img/{result}__{time.strftime('%H:%M:%S')}.png")
print(f"[INFO] {cit} Screen and log saves successfuly!")
if result == "YES":
resultYes()
driver.refresh()
except Exception as ex:
print(ex)
sleep(3)
auth()
auth()
while loop != 0:
for citya in cities_list[:2]:
check_data_loop(citya)
sleep(15)