Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
6.2 kB
0
Indexable
Never
import asyncio
import os
import zeep
import secrets
import json


from pymongo import MongoClient
from motor.motor_asyncio import AsyncIOMotorClient
from loguru import logger
import time


credentials = ("школа", "Parsec", "123456")
client = zeep.Client("http://172.16.16.5:10101/IntegrationService/IntegrationService.asmx?WSDL")
session = client.service.OpenSession(*credentials)
sessionId = session.Value.SessionID

# Создайте подключение к MongoDB
mongo_client = MongoClient('mongodb://localhost:27017/')
db = mongo_client['mydatabase']
collection = db['users']
collection2 = db['event']



clear2 = lambda: os.system('cls')

red = "\u001b[31;1m"
gr = "\u001b[32m"
ye = "\u001b[33;1m"

guests = []


async def update():
    print('Обновление базы данных ')

    people = client.service.GetOrgUnitsHierarhyWithPersons(sessionId)

    for i in range(len(people)):
        people2 = (people[i])
        try:
            if people2['FIRST_NAME']:
                pattern = {
                    'lastname': people2['LAST_NAME'],
                    'firstname': people2['FIRST_NAME'],
                    'middlename': people2['MIDDLE_NAME'],
                    'id': people2['ID'],
                    'parent_id': ''
                }

                is_exists = collection.count_documents({'id': people2['ID']})
                if not is_exists:
                    collection.insert_one(pattern)
                else:
                    continue
                # print(people2['LAST_NAME'], "|", people2['FIRST_NAME'], "|", people2['MIDDLE_NAME'], "|", people2['ID'])
            else:
                continue
        except:
            continue


# Предположим, что у вас есть словарь вида:
# user_dict = {'firstname': 'Имя', 'lastname': 'Фамилия', 'user_id': 'ID пользователя'}
# print(user_dict)
async def update_parent_id(user_id, user_dict, message):
    # Получить всех пользователей из MongoDB
    all_users = collection.find()

    found = False

    for user in all_users:
        # Сравнить каждого пользователя с данными в словаре
        if user['firstname'] == user_dict['firstname'] and user['lastname'] == user_dict['lastname']:
            # Если совпадение найдено, обновить parent_id этого пользователя
            collection.update_one({'id': user['id']}, {'$set': {'parent_id': user_id}})
            await message.answer(f"❖   ✔️ Вы успешно зарегистрировались")
            found = True
            break

    if not found:
        await message.answer(f"❖   ✖️ Нет такого ученика")


async def input_user(lastname, firstname):
    data = {
        'lastname': lastname,
        'firstname': firstname
    }


async def update_user(user_id: int, data: dict):
    await db.users.update_one({"_id": user_id}, {"$set": data})


async def updatebot():
    while True:
        data = (client.service.GetHardwareEventsResolved(sessionId, 0))

        for i in range(len(data)):
            data2 = (data[i])
            data3 = json.loads(data2)
            if data3['User']['Raw'] == "00000000-0000-0000-0000-000000000000":
                continue
            if data3['User']['Resolved']:
                if (data3['Component']['Raw'] == "7d41863e-1836-4319-9439-7fca7dae24f7" or
                        data3['Component']['Raw'] == "6f5a2a3e-e802-4048-90de-fd6829b7f177" or
                        data3['Component']['Raw'] == "c2b73d4f-c793-4dc4-b2e5-e6ffe506edc1" or
                        data3['Component']['Raw'] == "955cf25f-8119-4a75-a6f7-2317ac868faa"):
                    # print(data3['Date'], "|", data3['User']['Resolved'], "|", data3['Component']['Resolved'])

                    if data3['User']['Resolved']:
                        data4 = (
                        data3['Date'], data3['User']['Resolved'], data3['Component']['Resolved'], data3['User']['Raw'])
                        guests.append(data4)
                        guests.insert(0, data4)
                        timeb = time.time() + 28800
                        pattern = {'data': data3['Date'],
                                   'name': data3['User']['Resolved'],
                                   'place': data3['Component']['Resolved'],
                                   'id': data3['User']['Raw'],
                                   'bool': '',
                                   'time': timeb
                        }

                        is_exists = collection2.count_documents({'id': data3['User']['Raw']})
                        if not is_exists:

                            collection2.insert_one(pattern)
                        else:

                            continue

        print()
        print()
        for i in range(5):
            guests2 = (guests[i])
            logger.info(f'{gr}{guests2[0]} {red}{guests2[1]} {gr}{guests2[2]}')

        await asyncio.sleep(5)
        clear2()

async def updateevent():
    while True:
        for i in collection2.find():
            dataup = i['data'].split('T')[1]
            dataup2 = dataup.split(':')[0]
            dataup2 = int(dataup2) + 4
            dataup3 = str(dataup2) + ':' + dataup.split(':')[1] + ':' + dataup.split(':')[2]
            # print(dataup3)
            # print(i['data'].split('T')[1], i['name'])

            if not i['bool']:
                for e in collection.find({'id': i['id']}):
                    if e['parent_id']:
                        try:
                            print(dataup3, "|", e['lastname'], e['firstname'], "| В школе")
                            
                            collection2.update_one({"id": i['id']}, {"$set": {"bool": '1'}})
                            print("Отправил")

                        except:
                            print("Не отправил сообщение")
                            continue
        await asyncio.sleep(10)
async def updateevent2():
    v=0
    while True:
        v += 1
        print(v)
        await asyncio.sleep(1)
Leave a Comment