import mysql.connector import requests import json import time from dotenv import load_dotenv import os # Загрузка переменных окружения из файла .env load_dotenv() # Получение значений переменных окружения db_host = os.getenv('DB_HOST') db_user = os.getenv('USERS') db_password = os.getenv('PASSW') db_name = os.getenv('DATABASE') api_key = os.getenv('TGAPI_KEY') chat = os.getenv('TGCHAT_ID') token_key =os.getenv('KEYCRM_API') # Подключение к базе данных # Подключение к базе данных db = mysql.connector.connect( host= db_host, user= db_user, password= db_password, database= db_name ) # Путь к файлу JSON file_path = './data.json' # Функция для загрузки данных из JSON файла def load_data_from_json(file_path): try: with open(file_path, 'r') as file: data = json.load(file) return data except FileNotFoundError: return [] # Функция для сохранения данных в JSON файл def save_data_to_json(file_path, data): # Сохраняем данные в файл JSON with open(file_path, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) # Функция для проверки наличия элемента в списке def is_item_in_list(item, item_list): for existing_item in item_list: if existing_item == item: return True return False # Функция создания нового пользователя в key_crm def new_customer(full_name, groops, email, phone): headers = { 'accept': 'application/json', 'Authorization': f'Bearer {token_key}', 'Content-Type': 'application/json', } json_data = { 'full_name': full_name, 'email': [ email ], 'phone': [ phone ], # 'note': 'Примітка', # 'company_id': 112, 'manager_id': 4, # 'shipping': [ # { # 'address': 'string', # 'additional_address': 'string', # 'city': 'Kyiv', # 'region': 'Kyivska', # 'zip_code': '50000', # 'country': 'Ukraine', # 'recipient_full_name': 'Ann Doe', # 'recipient_phone': '+1 555-234-7777', # 'warehouse_ref': '1ec09d2e-e1c2-11e3-8c4a-0050568002cf', # }, # ], 'custom_fields': [ { 'uuid': 'CT_1007', 'value': groops, }, ], } response = requests.post('https://openapi.keycrm.app/v1/buyer', headers=headers, json=json_data) otv = (response.json()) ids_con = otv['id'] print(ids_con) return ids_con # Функция создания новой карты в key_crm def new_voronka(ids, full_name, groops, email, phone, ids_cust): headers = { 'accept': 'application/json', 'Authorization': f'Bearer {token_key}', } json_data = { 'title': f'Новий клиент с Lugi.com.ua с {ids}', 'source_id': 3, 'manager_comment': f'Гурт: {groops}', 'manager_id': 4, 'pipeline_id': 1, 'contact': { 'full_name': full_name, 'email': email, 'phone': phone, 'client_id': ids_cust, }, } response = requests.post('https://openapi.keycrm.app/v1/pipelines/cards', headers=headers, json=json_data) print(response.json()) def prov(email): headers = { 'accept': 'application/json', 'Authorization': f'Bearer {token_key}', } params = { 'limit': '15', 'page': '1', 'include': 'custom_fields', 'filter[buyer_email]': email, } response = requests.get('https://openapi.keycrm.app/v1/buyer', params=params, headers=headers) dt = response.json() return dt['data'] def con(): cursor = db.cursor() query = "SELECT * FROM oc_customer" cursor.execute(query) rows = cursor.fetchall() for row in rows: # if row[1] == target_model: ids = row[0] groop = row[1] firstname = row[4] lastname = row[5] email = row[6] phone = row[7] # Загрузка данных из файла (если файл существует) data = load_data_from_json(file_path) new_item = {'id': ids, 'groop': groop, 'firstname': firstname, 'lastname': lastname, 'email': email, 'phone': phone} if not is_item_in_list(new_item, data): data.append(new_item) save_data_to_json(file_path, data) print(f"Элемент {new_item} успешно добавлен.") if prov(email) == []: print(f'{ids} {phone} {groop} {email} {lastname}') if groop == 2: groops = 'Гуртовий' elif groop == 3: groops = 'Дропшипер' elif groop == 4: groops = 'Крупно гуртовий' else: groops = '' full_name = f'{firstname} {lastname}' ids_cust = new_customer(full_name, groops, email, phone) new_voronka(ids, full_name, groops, email, phone, ids_cust) else: print('YES') else: print(f"Элемент {new_item} уже существует в данных.") # print(f'{ids} {phone} {groop} {email} {lastname}') # if prov(email) == []: # print(f'{ids} {phone} {groop} {email} {lastname}') # else: # print('YES') """ Groop OC 2 mopt key_crm [{'id': 7, 'uuid': 'CT_1007', 'name': 'Тип покупця', 'type': 'select', 'value': ['Гуртовий']}]} OC 3 dprop key_crm[{'id': 7, 'uuid': 'CT_1007', 'name': 'Тип покупця', 'type': 'select', 'value': ['Дропшипер']}] OC 4 kopt key_crm [{'id': 7, 'uuid': 'CT_1007', 'name': 'Тип покупця', 'type': 'select', 'value': ['Крупно гуртовий']}]}""" def new_customer1(): headers = { 'accept': 'application/json', 'Authorization': f'Bearer {token_key}', 'Content-Type': 'application/json', } json_data = { 'full_name': "aa aa", 'email': [ 'tesn@jj.com' ], 'phone': [ '0668561234' ], # 'note': 'Примітка', # 'company_id': 112, 'manager_id': 4, # 'shipping': [ # { # 'address': 'string', # 'additional_address': 'string', # 'city': 'Kyiv', # 'region': 'Kyivska', # 'zip_code': '50000', # 'country': 'Ukraine', # 'recipient_full_name': 'Ann Doe', # 'recipient_phone': '+1 555-234-7777', # 'warehouse_ref': '1ec09d2e-e1c2-11e3-8c4a-0050568002cf', # }, # ], 'custom_fields': [ { 'uuid': 'CT_1007', 'value': 'Дропшипер', }, ], } response = requests.post('https://openapi.keycrm.app/v1/buyer', headers=headers, json=json_data) otv = (response.json()) ids_con = otv['id'] print(ids_con) if __name__ == '__main__': # a = requests.get('https://api.telegram.org/bot{}/sendMessage'.format(api_key), params=dict( # chat_id=chat, # text= '=> 🤙 Обмен Keycrm and opencart контактов работает)' )) # print(a) while True: try: con() # Вызываем вашу функцию print('Pause') time.sleep(600) except Exception: print("ERROR") a = requests.get('https://api.telegram.org/bot{}/sendMessage'.format(api_key), params=dict( chat_id=chat, text= '=> Народ 🥺 упал обмен с контактами не забудь поднять' )) time.sleep(60) print(a)