added monthly knd_bot
This commit is contained in:
parent
ce25dd58b8
commit
a3055c947b
@ -22,7 +22,7 @@ def complete_task(session, headers, task, address):
|
||||
photos = natsorted(photos)
|
||||
"""В папке лежит фото графика, которое отправляется из модуля des, поэтому убираем отсюда"""
|
||||
# if len(photos) == 11 or len(photos) == 14:
|
||||
if len(photos) == 3:
|
||||
if len(photos) == 3 or len(photos) == 4:
|
||||
photos.pop()
|
||||
id_task = task['id']
|
||||
quest = get_questions(id_task, session, headers)
|
||||
|
||||
142
classes/proverka_monthly.py
Normal file
142
classes/proverka_monthly.py
Normal file
@ -0,0 +1,142 @@
|
||||
import os
|
||||
import datetime
|
||||
import time
|
||||
from natsort import natsorted
|
||||
|
||||
|
||||
def assign_task(session, headers, task, address):
|
||||
# print('assign_task')
|
||||
# print("Start monthly")
|
||||
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
|
||||
task_assign = session.put(url, headers=headers)
|
||||
if task_assign.status_code == 200:
|
||||
print(f'Получили задание по адресу: {address}')
|
||||
complete_task(session, headers, task, address)
|
||||
else:
|
||||
print(f"Не смогли получить задание {address} {task['id']}!")
|
||||
|
||||
|
||||
def complete_task(session, headers, task, address):
|
||||
photos = get_photo(address, headers['uid'])
|
||||
if len(photos) > 0:
|
||||
# photos.sort()
|
||||
photos = natsorted(photos)
|
||||
"""В папке лежит фото графика, которое отправляется из модуля des, поэтому убираем отсюда"""
|
||||
# print(len(photos))
|
||||
if len(photos) == 11 or len(photos) == 14:
|
||||
# if len(photos) == 3 or len(photos) == 4:
|
||||
photos.pop()
|
||||
id_task = task['id']
|
||||
quest = get_questions(id_task, session, headers)
|
||||
length_question = get_length_questions(quest)
|
||||
prepared_answers = []
|
||||
if len(photos) == length_question:
|
||||
prepared_answers = prepare_answer(quest, photos, session, task, headers)
|
||||
ans = {"question_chains": prepared_answers}
|
||||
# print(ans)
|
||||
session_t = session
|
||||
session_t.headers.update(
|
||||
{
|
||||
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
|
||||
'x-platform': 'android',
|
||||
'accept': '*/*'
|
||||
}
|
||||
)
|
||||
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
|
||||
if complete.status_code == 200:
|
||||
print(f'Задание по адресу {address} выполнено успешно!\n\n')
|
||||
else:
|
||||
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}\n\n')
|
||||
else:
|
||||
print(f"\n\n\nНесоответствие количества вопросов и фотографий по адресу {address}!!! \
|
||||
Необходимо проверить!!!\n\n\n")
|
||||
# print(len(quest)) 9 and 13
|
||||
|
||||
|
||||
def get_length_questions(quest):
|
||||
count = 0
|
||||
for main_chain in quest:
|
||||
for second_chain in main_chain['questions']:
|
||||
for third_chain in second_chain['question_components']:
|
||||
question_type = third_chain['type']
|
||||
if question_type == "gallery":
|
||||
count = count + 1
|
||||
return count
|
||||
|
||||
|
||||
def prepare_answer(quest, photos, session, task, headers):
|
||||
questions = []
|
||||
question_components= []
|
||||
question_chains = []
|
||||
for main_chain in quest:
|
||||
for second_chain in main_chain['questions']:
|
||||
for third_chain in second_chain['question_components']:
|
||||
question_type = third_chain['type']
|
||||
if question_type == 'list':
|
||||
data = {"id": third_chain['id'], "answer": 77, "answer_status": None, "start_time": int(time.time())}
|
||||
time.sleep(2)
|
||||
data.update({"end_time": int(time.time())})
|
||||
question_components.append(data)
|
||||
elif question_type == "geo":
|
||||
data = {"id": third_chain['id'], "answer": {"location": task['coord']}, "answer_status": None, \
|
||||
"start_time": int(time.time())}
|
||||
time.sleep(2)
|
||||
data.update({"end_time": int(time.time())})
|
||||
question_components.append(data)
|
||||
elif question_type == "gallery":
|
||||
img = send_image(session, headers, task['id'], photos.pop(0))#photos.pop(0))
|
||||
data = {"id": third_chain['id'], "answer": [img['id']], "answer_status": None, \
|
||||
"start_time": int(time.time())}
|
||||
time.sleep(2)
|
||||
data.update({"end_time": int(time.time())})
|
||||
question_components.append(data)
|
||||
if len(question_components) > 0:
|
||||
main_data = {
|
||||
"id": second_chain['id'],
|
||||
"question_components": question_components
|
||||
}
|
||||
questions.append(main_data)
|
||||
question_components = []
|
||||
if len(questions) > 0:
|
||||
q_dict = {
|
||||
"id": main_chain['id'],
|
||||
"questions" : questions
|
||||
}
|
||||
question_chains.append(q_dict)
|
||||
questions = []
|
||||
return question_chains
|
||||
|
||||
|
||||
def get_photo(address, email):
|
||||
photos = []
|
||||
month = datetime.datetime.now().month
|
||||
main_path = os.path.join(os.path.abspath('.'), 'data1', email, str(month), address)
|
||||
if not os.path.exists(main_path):
|
||||
return photos
|
||||
else:
|
||||
for images in os.listdir(main_path):
|
||||
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
|
||||
photos.append(main_path + '/' + images)
|
||||
return photos
|
||||
|
||||
|
||||
def get_questions(id_task, session, headers):
|
||||
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
|
||||
questions = session.get(url, headers=headers)
|
||||
json_quest = questions.json()
|
||||
return json_quest['selected_chains']
|
||||
|
||||
|
||||
def send_image(session, headers, url, photo):
|
||||
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
|
||||
files = {
|
||||
'image': (photo[-5:], open(photo, 'rb')),
|
||||
}
|
||||
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
|
||||
if img.status_code == 200:
|
||||
print(f"Фото {photo} успешно отправлено")
|
||||
return img.json()
|
||||
else:
|
||||
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
|
||||
second_img = send_image(session, headers, url, photo)
|
||||
return second_img
|
||||
27
classes/users_month.py
Normal file
27
classes/users_month.py
Normal file
@ -0,0 +1,27 @@
|
||||
import os
|
||||
|
||||
|
||||
class Users:
|
||||
def __init__(self):
|
||||
self.data = []
|
||||
self.path = os.path.join(os.path.abspath('.'), 'data1')
|
||||
|
||||
def get_users(self):
|
||||
self.logins = []
|
||||
main_dir = os.walk(self.path)
|
||||
for d, dirs, files in main_dir:
|
||||
self.logins.append(dirs)
|
||||
return self.logins[0]
|
||||
|
||||
def get_passwords(self):
|
||||
if not os.path.exists(self.path):
|
||||
return "Папка data не существует. Создайте папку с необходимыми параметрами и запустите программу снова!"
|
||||
self.emails = self.get_users()
|
||||
if len(self.emails) > 0:
|
||||
for user in self.emails:
|
||||
with open(os.path.join(self.path, user, 'pass.txt'), 'r') as f:
|
||||
log_pass = {'email': user, 'password': f.readline().split('\n')[0]}
|
||||
self.data.append(log_pass)
|
||||
else:
|
||||
return "Нет ни одного пользователя! Заполните папку и запустите программу снова!"
|
||||
return self.data
|
||||
@ -165,6 +165,7 @@ def get_task(session, headers):
|
||||
4 id_задания"""
|
||||
desinfection = 'Дезинфекция подъездов (МОП)'
|
||||
proverka = 'Систематическая проверка подъездов МКД'
|
||||
proverka_monthly = 'Ежемесячная проверка подъездов МКД'
|
||||
# Получаем адреса
|
||||
addresses = get_addresses(headers['uid'])
|
||||
# Если адреса получили
|
||||
@ -203,9 +204,9 @@ def get_task(session, headers):
|
||||
get_t = False
|
||||
# Если есть доступное задание с таким адресом
|
||||
exec_assigned = json_tasks['executions_assigned'] # Уже полученные задания
|
||||
print(exec_assigned)
|
||||
# print(exec_assigned)
|
||||
exec_available = json_tasks['executions_available'] # Еще не принятые задания
|
||||
print(exec_available)
|
||||
# print(exec_available)
|
||||
# print(address)
|
||||
if len(exec_assigned) > 0:
|
||||
for n in exec_assigned:
|
||||
@ -214,7 +215,8 @@ def get_task(session, headers):
|
||||
for execution in enterances:
|
||||
address_from_tasks = execution['dimensions'][0].get('entity_value_name')
|
||||
name_from_tasks = execution['name']
|
||||
if name_from_tasks == proverka:
|
||||
# print(name_from_tasks)
|
||||
if name_from_tasks == proverka or name_from_tasks == proverka_monthly:
|
||||
enterance = execution['dimensions'][2].get('entity_value_name')
|
||||
if address_from_tasks == 'Клин г, '+ addr.replace("_", "/")[:-4] and \
|
||||
enterance[-1] == address[-2]:
|
||||
@ -230,7 +232,7 @@ def get_task(session, headers):
|
||||
if name_from_tasks == desinfection:
|
||||
pass
|
||||
# des.assign_task(session, headers, task, address)
|
||||
elif name_from_tasks == proverka:
|
||||
elif name_from_tasks == proverka or name_from_tasks == proverka_monthly:
|
||||
prov.assign_task(session, headers, task, address)
|
||||
else:
|
||||
pass
|
||||
@ -262,7 +264,7 @@ def main():
|
||||
get_task(session, headers)
|
||||
else:
|
||||
print(f"Отказ в авторизации для пользователя {user['email']}!")
|
||||
time.sleep(1)
|
||||
time.sleep(20)
|
||||
else:
|
||||
print(users.get_passwords())
|
||||
|
||||
|
||||
282
knd_bot_monthly.py
Normal file
282
knd_bot_monthly.py
Normal file
@ -0,0 +1,282 @@
|
||||
import requests
|
||||
import random
|
||||
import string
|
||||
# import json
|
||||
import datetime
|
||||
import time
|
||||
import os
|
||||
# from classes.users import Users
|
||||
from classes.users_month import Users
|
||||
import classes.desinfection as des
|
||||
import classes.proverka as prov
|
||||
import classes.proverka_monthly as monthly_prov
|
||||
|
||||
|
||||
def get_questions(id_task, session, headers):
|
||||
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
|
||||
questions = session.get(url, headers=headers)
|
||||
json_quest = questions.json()
|
||||
return json_quest['selected_chains']
|
||||
|
||||
|
||||
def send_image(session, headers, url, photo):
|
||||
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
|
||||
files = {
|
||||
'image': (photo[-5:], open(photo, 'rb')),
|
||||
}
|
||||
# print(files)
|
||||
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
|
||||
if img.status_code == 200:
|
||||
print(f"Фото {photo} успешно отправлено")
|
||||
return img.json()
|
||||
else:
|
||||
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
|
||||
second_img = send_image(session, headers, url, photo)
|
||||
return second_img
|
||||
|
||||
|
||||
def complete_task(session, headers, task, address):
|
||||
photos = get_photo(address, headers['uid'])
|
||||
if len(photos) > 0:
|
||||
photos.sort()
|
||||
print(task['id'])
|
||||
id_task = task['id']
|
||||
questions = get_questions(id_task, session, headers)
|
||||
data = []
|
||||
for answers in questions:
|
||||
answer_chain = {
|
||||
'id': answers['id'],
|
||||
'questions': [] # answers['questions']
|
||||
}
|
||||
if answer_chain['id'] == 6146: # Цепочка без ответов
|
||||
continue
|
||||
for components in answers['questions']:
|
||||
comp = []
|
||||
q_c = {
|
||||
'id': components['id'],
|
||||
'question_components': []
|
||||
}
|
||||
if q_c['id'] == 6560: # Вопрос без ответа
|
||||
continue
|
||||
comp.append(q_c)
|
||||
answer_chain.update({'questions': comp})
|
||||
data.append(answer_chain)
|
||||
if len(data) == len(photos):
|
||||
for chain in data:
|
||||
for item in chain['questions']:
|
||||
if len(data) == len(photos):
|
||||
photo_from_photos = photos.pop(0)
|
||||
img = send_image(session, headers, task['id'], photo_from_photos) # photos.pop(0))
|
||||
# count_send_photo = 0
|
||||
# while img['id'] is None:
|
||||
# count_send_photo += 1
|
||||
# print("Попытка № " + str(count_send_photo) + "отправить фото" + str(photo_from_photos))
|
||||
# img = send_image(session, headers, task['id'], photo_from_photos)#photos.pop(0))
|
||||
first = {"id": 18850, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
|
||||
time.sleep(2)
|
||||
first.update({'end_time': int(time.time())})
|
||||
second = {"id": 18851, "answer": {"location": task['coord']}, 'answer_status': None, 'start_time': int(time.time())}
|
||||
time.sleep(2)
|
||||
second.update({'end_time': int(time.time())})
|
||||
item['question_components'].append(first)
|
||||
item['question_components'].append(second)
|
||||
else:
|
||||
#img = send_image(session, headers, task['id'], photos.pop(0))
|
||||
photo_from_photos = photos.pop(0)
|
||||
img = send_image(session, headers, task['id'], photo_from_photos)#photos.pop(0))
|
||||
# count_send_photo = 0
|
||||
# while img['id'] is None:
|
||||
# count_send_photo += 1
|
||||
# print("Попытка № " + str(count_send_photo) + " отправить фото" + str(photo_from_photos))
|
||||
# img = send_image(session, headers, task['id'], photo_from_photos)#photos.pop(0))
|
||||
first = {"id": 18856, "answer": 77, 'answer_status': None, 'start_time': int(time.time())}
|
||||
time.sleep(2)
|
||||
first.update({'end_time': int(time.time())})
|
||||
second = {"id": 18857, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
|
||||
time.sleep(2)
|
||||
second.update({'end_time': int(time.time())})
|
||||
item['question_components'].append(first)
|
||||
item['question_components'].append(second)
|
||||
ans = {"question_chains": data}
|
||||
# print(ans)
|
||||
session_t = session
|
||||
session_t.headers.update(
|
||||
{
|
||||
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
|
||||
'x-platform': 'wb',
|
||||
'accept': '*/*'
|
||||
}
|
||||
)
|
||||
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
|
||||
if complete.status_code == 200:
|
||||
print(f'Задание по адресу {address} выполнено успешно!')
|
||||
else:
|
||||
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}')
|
||||
else:
|
||||
print(f"Несоответствие количества вопросов и количества фотографий по адресу: {address}")
|
||||
# send_execution(task,session, headers)
|
||||
|
||||
|
||||
def get_photo(address, email):
|
||||
photos = []
|
||||
month = datetime.datetime.now().month
|
||||
main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month), address)
|
||||
if not os.path.exists(main_path):
|
||||
return photos
|
||||
else:
|
||||
for images in os.listdir(main_path):
|
||||
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
|
||||
photos.append(main_path + '/' + images)
|
||||
return photos
|
||||
|
||||
|
||||
def get_addresses(email):
|
||||
addresses = []
|
||||
month = datetime.datetime.now().month
|
||||
main_path = os.path.join(os.path.abspath('.'), 'data')
|
||||
path = os.walk(os.path.join(main_path, email, str(month)))
|
||||
if not os.path.exists(os.path.join(main_path, email, str(month))):
|
||||
return f"Не найдена папка с месяцем у пользователя {email}! Проверьте структуру каталога!"
|
||||
for d, dirs, files in path:
|
||||
addresses.append(dirs)
|
||||
if len(addresses[0]) > 0:
|
||||
return addresses[0]
|
||||
else:
|
||||
return f"Ни одного адреса для пользователя {email} не найдено! Добавьте фото и запустите программу снова!"
|
||||
|
||||
|
||||
# def assign_task(session, headers, task, address):
|
||||
# url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
|
||||
# task_assign = session.put(url, headers=headers)
|
||||
# if task_assign.status_code == 200:
|
||||
# print(f'Получили задани по адресу: {address}')
|
||||
# complete_task(session, headers, task, address)
|
||||
# else:
|
||||
# print(f"Не смогли получить задание {address} {task['id']}!")
|
||||
|
||||
|
||||
def get_task(session, headers):
|
||||
"""Получаем все доступные задания. Если в переменную search добавить адрес,
|
||||
то будет искать этот адрес. Он попадет в
|
||||
json_tasks['executions_available'],
|
||||
так что надо понять откуда берем задания. Отсюда можно возвращать
|
||||
все параметры задания:
|
||||
1 координаты
|
||||
2 адрес
|
||||
3 подъезд
|
||||
4 id_задания"""
|
||||
desinfection = 'Дезинфекция подъездов (МОП)'
|
||||
proverka = 'Систематическая проверка подъездов МКД'
|
||||
proverka_monthly = 'Ежемесячная проверка подъездов МКД'
|
||||
# Получаем адреса
|
||||
addresses = get_addresses(headers['uid'])
|
||||
# Если адреса получили
|
||||
# {"filters":[{"value":{"distance":"50000","lat":55.81999969482422,"lon":37.380001068115234},"filter_attribute":10,"id":6,"name":"Локация","type":"distance"}]}
|
||||
if isinstance(addresses, list):
|
||||
session_t = session
|
||||
session_t.headers.update(
|
||||
{'referer': 'https://knd.mosreg.ru/executions',
|
||||
'x-platform': 'android',
|
||||
'accept': '*/*'
|
||||
}
|
||||
)
|
||||
for address in addresses:
|
||||
# change '-' for '/'
|
||||
# need split enterance from address
|
||||
addr = address.replace("Чаиковского", "Чайковского")
|
||||
addr = address.replace("Маиданово", "Майданово")
|
||||
search = addr.replace("_", "/")[:-4]
|
||||
# print(search)
|
||||
# data = {'search': search,
|
||||
# 'filters': [{'value':{
|
||||
# 'distance': 25000,
|
||||
# 'lat': 55.81999969482422,
|
||||
# 'lon': 37.380001068115234
|
||||
# },
|
||||
# 'filter_attribute': 10,
|
||||
# 'id': 6,
|
||||
# 'name': 'Локация',
|
||||
# 'type': 'distance'}]}
|
||||
data = {'search': search}
|
||||
tasks = session_t.post('https://knd.mosreg.ru//api/v1/actor/executions',
|
||||
headers=headers,
|
||||
data=data
|
||||
)
|
||||
json_tasks = tasks.json()
|
||||
get_t = False
|
||||
# Если есть доступное задание с таким адресом
|
||||
exec_assigned = json_tasks['executions_assigned'] # Уже полученные задания
|
||||
# print(exec_assigned)
|
||||
exec_available = json_tasks['executions_available'] # Еще не принятые задания
|
||||
# print(exec_available)
|
||||
# print(address)
|
||||
if len(exec_assigned) > 0:
|
||||
for n in exec_assigned:
|
||||
coord = n['coord']
|
||||
enterances = n['tasks']
|
||||
for execution in enterances:
|
||||
address_from_tasks = execution['dimensions'][0].get('entity_value_name')
|
||||
name_from_tasks = execution['name']
|
||||
# print(name_from_tasks)
|
||||
if name_from_tasks == proverka_monthly:
|
||||
enterance = execution['dimensions'][2].get('entity_value_name')
|
||||
if address_from_tasks == 'Клин г, '+ addr.replace("_", "/")[:-4] and \
|
||||
enterance[-1] == address[-2]:
|
||||
print('\n')
|
||||
print(name_from_tasks)
|
||||
print('\n')
|
||||
task = {
|
||||
'id': execution['execution_id'],
|
||||
'address': execution['dimensions'][0].get('entity_value_name'),
|
||||
'enterance': execution['dimensions'][2].get('entity_value_name'),
|
||||
'coord': coord
|
||||
}
|
||||
if name_from_tasks == desinfection:
|
||||
pass
|
||||
# des.assign_task(session, headers, task, address)
|
||||
elif name_from_tasks == proverka_monthly:
|
||||
monthly_prov.assign_task(session, headers, task, address)
|
||||
else:
|
||||
pass
|
||||
else:
|
||||
print(f"Нет доступных заданий для пользователя {headers['uid']} по адресу: {address}")
|
||||
# Если адреса не получили выводим ошибку
|
||||
else:
|
||||
print(addresses)
|
||||
|
||||
|
||||
def main():
|
||||
users = Users()
|
||||
logins = users.get_passwords()
|
||||
if isinstance(logins, list):
|
||||
url = 'https://knd.mosreg.ru//api/v1/auth/sign_in'
|
||||
for user in logins:
|
||||
session = requests.Session()
|
||||
login = {
|
||||
'email': user['email'],
|
||||
'password': user['password']
|
||||
}
|
||||
response = session.post(url, data=login)
|
||||
headers = {
|
||||
'client': response.headers.get('client'),
|
||||
'Access-token': response.headers.get('Access-token'),
|
||||
'uid': response.headers.get('uid'),
|
||||
}
|
||||
if response.status_code == 200:
|
||||
get_task(session, headers)
|
||||
else:
|
||||
print(f"Отказ в авторизации для пользователя {user['email']}!")
|
||||
time.sleep(20)
|
||||
else:
|
||||
print(users.get_passwords())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
k = input("Press ENTER for exit")
|
||||
|
||||
|
||||
def random_string(stringLength):
|
||||
letters = string.ascii_letters
|
||||
digits = string.digits
|
||||
return ''.join(random.choice(letters+digits) for i in range(stringLength))
|
||||
Loading…
Reference in New Issue
Block a user