Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,40 @@
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
import random
|
|
|
|
|
|
|
| 4 |
from playwright.sync_api import sync_playwright
|
| 5 |
from groq import Groq
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 13 |
-
KIMI_MODEL = "moonshotai/kimi-k2.6"
|
| 14 |
|
| 15 |
def get_ai_response(user_message):
|
| 16 |
-
"""Fetches a clear response from Kimi K2.6 without internal thinking text"""
|
| 17 |
try:
|
| 18 |
completion = groq_client.chat.completions.create(
|
| 19 |
model=KIMI_MODEL,
|
| 20 |
messages=[
|
| 21 |
-
{"role": "system", "content": "You are a helpful Instagram DM automation assistant. Give direct, crisp, and concise replies under 3 sentences. No internal reasoning
|
| 22 |
{"role": "user", "content": user_message}
|
| 23 |
]
|
| 24 |
)
|
|
@@ -28,25 +44,21 @@ def get_ai_response(user_message):
|
|
| 28 |
return "Hey! I'm processing your request. Give me just a moment."
|
| 29 |
|
| 30 |
def human_type(element, text):
|
| 31 |
-
"""Types out text with random variations in keystroke speed to bypass bot detection"""
|
| 32 |
for char in text:
|
| 33 |
element.type(char)
|
| 34 |
time.sleep(random.uniform(0.05, 0.15))
|
| 35 |
|
| 36 |
def run_bot():
|
| 37 |
with sync_playwright() as p:
|
| 38 |
-
# CRITICAL: headless=False makes the browser render visually inside Xvfb
|
| 39 |
print("Launching visible Chromium browser instance...")
|
| 40 |
browser = p.chromium.launch(
|
| 41 |
headless=False,
|
| 42 |
args=["--no-sandbox", "--disable-setuid-sandbox"]
|
| 43 |
)
|
| 44 |
|
| 45 |
-
# Emulate a standard laptop screen resolution
|
| 46 |
context = browser.new_context(viewport={"width": 1366, "height": 768})
|
| 47 |
page = context.new_page()
|
| 48 |
|
| 49 |
-
# --- LOGIN PHASE ---
|
| 50 |
print("Navigating to Instagram...")
|
| 51 |
page.goto("https://www.instagram.com/accounts/login/", wait_until="networkidle")
|
| 52 |
|
|
@@ -57,30 +69,23 @@ def run_bot():
|
|
| 57 |
time.sleep(random.uniform(1, 2))
|
| 58 |
|
| 59 |
page.click("button[type='submit']")
|
| 60 |
-
print("Login credentials submitted.
|
| 61 |
|
| 62 |
-
# Wait for security checkpoints / main feed to load
|
| 63 |
page.wait_for_url("**/instagram.com/**", timeout=60000)
|
| 64 |
time.sleep(5)
|
| 65 |
|
| 66 |
-
# --- DM CHECK LOOP ---
|
| 67 |
print("Navigating to Inbox...")
|
| 68 |
page.goto("https://www.instagram.com/direct/inbox/", wait_until="networkidle")
|
| 69 |
|
| 70 |
while True:
|
| 71 |
try:
|
| 72 |
-
# Look for unread chat rows in the sidebar list layout
|
| 73 |
-
# Instagram dynamically updates class strings, but unread items usually feature bold text styles
|
| 74 |
unread_chats = page.query_selector_all("div[style*='font-weight: 600']")
|
| 75 |
-
|
| 76 |
if unread_chats:
|
| 77 |
print(f"Found {len(unread_chats)} unread conversation thread(s)!")
|
| 78 |
-
|
| 79 |
for chat in unread_chats:
|
| 80 |
chat.click()
|
| 81 |
time.sleep(2)
|
| 82 |
|
| 83 |
-
# Grab the last message bubble text incoming from the user
|
| 84 |
message_bubbles = page.query_selector_all("div[role='row'] >> span")
|
| 85 |
if not message_bubbles:
|
| 86 |
continue
|
|
@@ -88,11 +93,9 @@ def run_bot():
|
|
| 88 |
last_message_text = message_bubbles[-1].inner_text()
|
| 89 |
print(f"Received Message: {last_message_text}")
|
| 90 |
|
| 91 |
-
# Get response from Kimi K2.6
|
| 92 |
ai_reply = get_ai_response(last_message_text)
|
| 93 |
print(f"Kimi K2.6 Reply: {ai_reply}")
|
| 94 |
|
| 95 |
-
# Locate text box and type reply
|
| 96 |
message_input = page.wait_for_selector("div[role='textbox'][aria-label*='Message']")
|
| 97 |
message_input.click()
|
| 98 |
human_type(message_input, ai_reply)
|
|
@@ -100,17 +103,19 @@ def run_bot():
|
|
| 100 |
time.sleep(1)
|
| 101 |
page.keyboard.press("Enter")
|
| 102 |
print("Reply successfully dispatched.")
|
| 103 |
-
|
| 104 |
time.sleep(random.uniform(2, 4))
|
| 105 |
-
|
| 106 |
except Exception as loop_error:
|
| 107 |
print(f"Error checking messages: {loop_error}")
|
| 108 |
|
| 109 |
-
# Idle delay before checking for new messages again
|
| 110 |
time.sleep(30)
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
| 113 |
if not os.getenv("IG_USERNAME") or not os.getenv("IG_PASSWORD"):
|
| 114 |
print("Missing environment configurations! Set IG_USERNAME and IG_PASSWORD.")
|
| 115 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
run_bot()
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
import random
|
| 4 |
+
import threading
|
| 5 |
+
from http.server import SimpleHTTPRequestHandler, HTTPServer
|
| 6 |
from playwright.sync_api import sync_playwright
|
| 7 |
from groq import Groq
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
|
| 10 |
load_dotenv()
|
| 11 |
|
| 12 |
+
# --- HUGGING FACE PORT BIND FIX ---
|
| 13 |
+
def run_health_server():
|
| 14 |
+
"""Starts a lightweight server on port 7860 so HF knows the Space is alive"""
|
| 15 |
+
class HealthHandler(SimpleHTTPRequestHandler):
|
| 16 |
+
def do_GET(self):
|
| 17 |
+
self.send_response(200)
|
| 18 |
+
self.send_header("Content-type", "text/html")
|
| 19 |
+
self.end_headers()
|
| 20 |
+
self.wfile.write(b"Bot is running actively in the background!")
|
| 21 |
+
|
| 22 |
+
# Hugging Face automatically assigns port 7860
|
| 23 |
+
port = int(os.environ.get("PORT", 7860))
|
| 24 |
+
server = HTTPServer(("0.0.0.0", port), HealthHandler)
|
| 25 |
+
print(f"Health check server listening on port {port}...")
|
| 26 |
+
server.serve_forever()
|
| 27 |
+
|
| 28 |
+
# Initialize Groq client
|
| 29 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 30 |
+
KIMI_MODEL = "moonshotai/kimi-k2.6"
|
| 31 |
|
| 32 |
def get_ai_response(user_message):
|
|
|
|
| 33 |
try:
|
| 34 |
completion = groq_client.chat.completions.create(
|
| 35 |
model=KIMI_MODEL,
|
| 36 |
messages=[
|
| 37 |
+
{"role": "system", "content": "You are a helpful Instagram DM automation assistant. Give direct, crisp, and concise replies under 3 sentences. No internal reasoning."},
|
| 38 |
{"role": "user", "content": user_message}
|
| 39 |
]
|
| 40 |
)
|
|
|
|
| 44 |
return "Hey! I'm processing your request. Give me just a moment."
|
| 45 |
|
| 46 |
def human_type(element, text):
|
|
|
|
| 47 |
for char in text:
|
| 48 |
element.type(char)
|
| 49 |
time.sleep(random.uniform(0.05, 0.15))
|
| 50 |
|
| 51 |
def run_bot():
|
| 52 |
with sync_playwright() as p:
|
|
|
|
| 53 |
print("Launching visible Chromium browser instance...")
|
| 54 |
browser = p.chromium.launch(
|
| 55 |
headless=False,
|
| 56 |
args=["--no-sandbox", "--disable-setuid-sandbox"]
|
| 57 |
)
|
| 58 |
|
|
|
|
| 59 |
context = browser.new_context(viewport={"width": 1366, "height": 768})
|
| 60 |
page = context.new_page()
|
| 61 |
|
|
|
|
| 62 |
print("Navigating to Instagram...")
|
| 63 |
page.goto("https://www.instagram.com/accounts/login/", wait_until="networkidle")
|
| 64 |
|
|
|
|
| 69 |
time.sleep(random.uniform(1, 2))
|
| 70 |
|
| 71 |
page.click("button[type='submit']")
|
| 72 |
+
print("Login credentials submitted.")
|
| 73 |
|
|
|
|
| 74 |
page.wait_for_url("**/instagram.com/**", timeout=60000)
|
| 75 |
time.sleep(5)
|
| 76 |
|
|
|
|
| 77 |
print("Navigating to Inbox...")
|
| 78 |
page.goto("https://www.instagram.com/direct/inbox/", wait_until="networkidle")
|
| 79 |
|
| 80 |
while True:
|
| 81 |
try:
|
|
|
|
|
|
|
| 82 |
unread_chats = page.query_selector_all("div[style*='font-weight: 600']")
|
|
|
|
| 83 |
if unread_chats:
|
| 84 |
print(f"Found {len(unread_chats)} unread conversation thread(s)!")
|
|
|
|
| 85 |
for chat in unread_chats:
|
| 86 |
chat.click()
|
| 87 |
time.sleep(2)
|
| 88 |
|
|
|
|
| 89 |
message_bubbles = page.query_selector_all("div[role='row'] >> span")
|
| 90 |
if not message_bubbles:
|
| 91 |
continue
|
|
|
|
| 93 |
last_message_text = message_bubbles[-1].inner_text()
|
| 94 |
print(f"Received Message: {last_message_text}")
|
| 95 |
|
|
|
|
| 96 |
ai_reply = get_ai_response(last_message_text)
|
| 97 |
print(f"Kimi K2.6 Reply: {ai_reply}")
|
| 98 |
|
|
|
|
| 99 |
message_input = page.wait_for_selector("div[role='textbox'][aria-label*='Message']")
|
| 100 |
message_input.click()
|
| 101 |
human_type(message_input, ai_reply)
|
|
|
|
| 103 |
time.sleep(1)
|
| 104 |
page.keyboard.press("Enter")
|
| 105 |
print("Reply successfully dispatched.")
|
|
|
|
| 106 |
time.sleep(random.uniform(2, 4))
|
|
|
|
| 107 |
except Exception as loop_error:
|
| 108 |
print(f"Error checking messages: {loop_error}")
|
| 109 |
|
|
|
|
| 110 |
time.sleep(30)
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
| 113 |
if not os.getenv("IG_USERNAME") or not os.getenv("IG_PASSWORD"):
|
| 114 |
print("Missing environment configurations! Set IG_USERNAME and IG_PASSWORD.")
|
| 115 |
else:
|
| 116 |
+
# Start the health check server in a background thread
|
| 117 |
+
health_thread = threading.Thread(target=run_health_server, daemon=True)
|
| 118 |
+
health_thread.start()
|
| 119 |
+
|
| 120 |
+
# Now run your main bot script
|
| 121 |
run_bot()
|