điểm danh nuôi gà
@echo off
title System Data Sync Service
cd /d "%~dp0"
:loop
echo [%time%] Starting Data Synchronization Process...
python auto_farm.py
echo [%time%] Process finished. Entering idle state for 3600s...
timeout /t 86400 /nobreak >nul
goto loop



import asyncio
import os
import re
from playwright.async_api import async_playwright

# -------------------------------------------------------------
# CẤU HÌNH CÀI ĐẶT
# -------------------------------------------------------------
TOTAL_CAGES = 3

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ACCOUNTS_FILE = os.path.join(BASE_DIR, "accounts.txt")
# -------------------------------------------------------------

def load_accounts(file_path):
accounts = []
if not os.path.exists(file_path):
print(f"[-] File {file_path} không tồn tại!")
return accounts

with open(file_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if "|" in line and not line.startswith("#"):
user, pwd = line.split("|", 1)
accounts.append((user.strip(), pwd.strip()))
return accounts

async def safe_goto(page, url, retries=3):
for attempt in range(1, retries + 1):
try:
await page.goto(url, wait_until="domcontentloaded", timeout=60000)
return True
except Exception as e:
print(f" [!] Lỗi tải trang ({attempt}/{retries}): {e}")
if attempt < retries:
await asyncio.sleep(2)
else:
raise e

async def run_automation():
accounts = load_accounts(ACCOUNTS_FILE)
if not accounts:
print("[-] Danh sách tài khoản trống!")
return

async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)

for username, password in accounts:
print("\n==========================================")
print(f"[*] Đang xử lý tài khoản: {username}")

context = await browser.new_context()
page = await context.new_page()

# Tự động bấm "OK" cho các hộp thoại xác nhận (Confirm/Alert) Bán vật nuôi
page.on("dialog", lambda dialog: dialog.accept())

page.set_default_timeout(60000)
page.set_default_navigation_timeout(60000)

try:
# 1. ĐĂNG NHẬP
print("[1] Mở trang đăng nhập...")
await safe_goto(page, "https://1900.fun/login.php")
await page.fill("input[name='username']", username)
await page.fill("input[name='password']", password)

async with page.expect_navigation(wait_until="domcontentloaded"):
await page.click("button[type='submit']")
await page.wait_for_timeout(1500)

# 2. ĐIỂM DANH
print("[2] Kiểm tra điểm danh hàng ngày...")
await safe_goto(page, "https://1900.fun/profile.php")
await page.wait_for_timeout(1000)

checkin_button = page.locator("button[name='checkin']")
if await checkin_button.count() > 0 and not await checkin_button.is_disabled():
print(" -> Tiến hành điểm danh...")
await checkin_button.click()
await page.wait_for_timeout(1500)

# 3. BÁN TẤT CẢ CÁC CHUỒNG HIỆN CÓ
print("[3] BÁN VẬT NUÔI: Đang thực hiện bán cho từng chuồng...")
for cage_idx in range(TOTAL_CAGES): # 0, 1, 2
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

sell_btn = page.locator(f"a[href='?harvest={cage_idx}']")
if await sell_btn.count() > 0:
async with page.expect_navigation(wait_until="domcontentloaded"):
await sell_btn.click()
print(f" -> Đã bán thành công vật nuôi ở Chuồng {cage_idx + 1}")
await page.wait_for_timeout(1500)
else:
print(f" -> Chuồng {cage_idx + 1} không có vật nuôi để bán hoặc đã trống.")

# 4. PHÂN TÍCH DỮ LIỆU ĐỂ CHỌN VẬT NUÔI CẤP CAO NHẤT
print("[4] Đang tính toán chọn vật nuôi tối ưu theo Cấp độ & Số xu...")
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

# Lấy dữ liệu cấu hình từ JavaScript trên trang web
animal_data = await page.evaluate("""() => {
return {
animals: typeof animals !== 'undefined' ? animals : [],
userLevel: typeof userLevel !== 'undefined' ? userLevel : 1,
userMoney: typeof userMoney !== 'undefined' ? userMoney : 0
};
}""")

animals = animal_data.get("animals", [])
user_level = animal_data.get("userLevel", 1)
user_money = animal_data.get("userMoney", 0)

print(f" -> Cấp trại: {user_level} | Số xu hiện có: {user_money:,} xu")

# Lọc danh sách vật nuôi thỏa mãn điều kiện cấp độ và số xu
affordable_animals = [
a for a in animals
if user_level >= a.get("level_required", 1) and user_money >= a.get("price", 0)
]

if not affordable_animals:
print(" -> [!] Không đủ tiền hoặc cấp độ không đủ để mua bất kỳ vật nuôi nào!")
selected_animal_id = None
else:
# Sắp xếp theo level_required giảm dần (chọn con cấp cao nhất)
best_animal = max(affordable_animals, key=lambda x: (x.get("level_required", 1), x.get("price", 0)))
selected_animal_id = str(best_animal.get("id"))
print(f" -> [Chốt] Mua loại cao nhất: {best_animal.get('name')} (ID: {selected_animal_id}) | Giá: {best_animal.get('price'):,} xu | Yêu cầu cấp: {best_animal.get('level_required')}")

# 5. THỰC HIỆN MUA VẬT NUÔI CHO TỪNG CHUỒNG (0, 1, 2)
if selected_animal_id:
print("[5] MUA VẬT NUÔI: Tiến hành thả nuôi...")
for cage_idx in range(TOTAL_CAGES):
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

if await page.locator("#buyForm").count() > 0:
await page.evaluate(f"""() => {{
document.getElementById('buyCageIndex').value = '{cage_idx}';
document.getElementById('buyAnimalId').value = '{selected_animal_id}';
}}""")

async with page.expect_navigation(wait_until="domcontentloaded"):
await page.eval_on_selector("#buyForm", "form => form.submit()")

print(f" -> Đã mua thành công cho Chuồng {cage_idx + 1}")
await page.wait_for_timeout(1500)

# 6. ĐĂNG XUẤT
print("[6] Đăng xuất...")
await safe_goto(page, "https://1900.fun/logout.php")
await page.wait_for_timeout(1500)

print(f"[+] Hoàn tất cho: {username}")

except Exception as e:
print(f"[-] Có lỗi xảy ra đối với {username}: {e}")

finally:
await context.close()
await asyncio.sleep(2)

await browser.close()

if __name__ == "__main__":
asyncio.run(run_automation())