1234ty's picture
Update main.py
f63165e verified
Raw
History Blame Contribute Delete
7.66 kB
import asyncio
import random
import logging
import requests
import sys
from playwright.async_api import async_playwright
from playwright_stealth import stealth_async
# --- CONFIGURATION ---
TARGET_URL = "https://yourwebsite.com" # ใส่เว็บที่ต้องการดัน SEO
MAX_BOTS = 2 # จำนวนบอท (แนะนำ 2 สำหรับ HF Free)
MIN_STAY = 60 # อยู่ในเว็บขั้นต่ำ (วินาที)
MAX_STAY = 150 # อยู่ในเว็บสูงสุด (วินาที)
# แหล่งดึง Proxy ฟรี
PROXY_API_URL = "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all"
# ตั้งค่า Logging ให้แสดงผลออกแบบ Real-time เข้า Stream โดยตรง
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)s | %(message)s',
datefmt='%H:%M:%S',
handlers=[logging.StreamHandler(sys.stdout)]
)
def fetch_free_proxies():
"""ดึง Proxy ฟรีจาก API อัตโนมัติ"""
try:
logging.info("🌐 [SYSTEM] กำลังดึงรายชื่อ Proxy ใหม่ล่าสุด...")
response = requests.get(PROXY_API_URL, timeout=15)
if response.status_code == 200:
proxies = response.text.splitlines()
active_proxies = [f"http://{p.strip()}" for p in proxies if p.strip()]
logging.info(f"✅ [SYSTEM] ดึงสำเร็จ! พบ Proxy ทั้งหมด {len(active_proxies)} ตัว")
return active_proxies
except Exception as e:
logging.error(f"❌ [SYSTEM] ดึง Proxy ไม่สำเร็จ: {e}")
return []
async def simulate_human_behavior(page, bot_id):
"""จำลองการอ่านเว็บแบบละเอียด"""
try:
action = random.choice(["SCROLL", "MOUSE_MOVE", "WAIT"])
if action == "SCROLL":
pix = random.randint(300, 900)
await page.mouse.wheel(0, pix)
logging.info(f"🖱️ [BOT-{bot_id}] Action: เลื่อนหน้าจอลง {pix} px")
elif action == "MOUSE_MOVE":
x, y = random.randint(100, 1000), random.randint(100, 800)
await page.mouse.move(x, y)
logging.info(f"📍 [BOT-{bot_id}] Action: ขยับเมาส์ไปที่ ({x}, {y})")
# โอกาสคลิก Link ภายใน
if random.random() < 0.3:
links = await page.query_selector_all("a")
internal = []
for l in links:
href = await l.get_attribute("href")
if href and (href.startswith("/") or TARGET_URL in href):
internal.append(l)
if internal:
target = random.choice(internal)
target_href = await target.get_attribute("href")
logging.info(f"🔗 [BOT-{bot_id}] กำลังคลิก Link ภายใน: {target_href}")
await target.click()
await page.wait_for_load_state("networkidle")
logging.info(f"📄 [BOT-{bot_id}] โหลดหน้าใหม่สำเร็จ")
except Exception as e:
logging.debug(f"⚠️ [BOT-{bot_id}] พฤติกรรมจำลองติดขัดเล็กน้อย")
async def run_bot(bot_id, proxy_list):
"""ฟังก์ชันหลักของบอทแต่ละตัว"""
logging.info(f"🚀 [BOT-{bot_id}] เริ่มต้นการทำงาน...")
while True:
proxy_url = random.choice(proxy_list) if proxy_list else None
async with async_playwright() as p:
browser_args = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-blink-features=AutomationControlled"
]
launch_options = {"headless": True, "args": browser_args}
if proxy_url:
launch_options["proxy"] = {"server": proxy_url}
try:
logging.info(f"🛰️ [BOT-{bot_id}] พยายามเชื่อมต่อผ่าน IP: {proxy_url if proxy_url else 'DIRECT'}")
browser = await p.chromium.launch(**launch_options)
context = await browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0",
viewport={'width': 1366, 'height': 768}
)
page = await context.new_page()
await stealth_async(page)
# เข้าเว็บเป้าหมาย
stay_duration = random.randint(MIN_STAY, MAX_STAY)
logging.info(f"🌍 [BOT-{bot_id}] กำลังเข้าเว็บ: {TARGET_URL}")
response = await page.goto(TARGET_URL, wait_until="domcontentloaded", timeout=60000)
if response and response.status == 200:
logging.info(f"✅ [BOT-{bot_id}] เข้าเว็บสำเร็จ (Status: 200). จะแช่อยู่ {stay_duration} วินาที")
# ทำพฤติกรรมสุ่มจนครบเวลา
start_time = asyncio.get_event_loop().time()
while asyncio.get_event_loop().time() - start_time < stay_duration:
await simulate_human_behavior(page, bot_id)
await asyncio.sleep(random.randint(5, 12))
logging.info(f"🏆 [BOT-{bot_id}] ภารกิจเสร็จสิ้น (Session Completed)")
else:
status = response.status if response else "No Response"
logging.warning(f"⚠️ [BOT-{bot_id}] เว็บตอบกลับด้วยสถานะ: {status}")
await browser.close()
except Exception as e:
logging.error(f"💢 [BOT-{bot_id}] เกิดข้อผิดพลาด/Proxy ตาย: {str(e)[:100]}...")
# พักก่อนเริ่มรอบใหม่
wait_next = random.randint(30, 60)
logging.info(f"💤 [BOT-{bot_id}] พักเครื่อง {wait_next} วินาที ก่อนเริ่มรอบถัดไป...")
await asyncio.sleep(wait_next)
async def main():
logging.info("🔥 [SYSTEM] เริ่มการทำงานระบบ SEO Booster (Real-time Log Mode)")
# 1. ดึง Proxy มาก่อน
proxy_list = fetch_free_proxies()
if not proxy_list:
logging.warning("⚠️ [SYSTEM] ไม่พบ Proxy ระบบจะทำงานด้วย IP ตรง (เสี่ยงโดนแบน)")
# 2. เริ่มรันบอท
tasks = [run_bot(i+1, proxy_list) for i in range(MAX_BOTS)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info("🛑 [SYSTEM] หยุดการทำงานโดยผู้ใช้")