Bjo53 commited on
Commit
af28d9f
Β·
verified Β·
1 Parent(s): 1c8494e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +31 -25
main.py CHANGED
@@ -17,51 +17,54 @@ from aiogram.client.telegram import TelegramAPIServer
17
  from apscheduler.schedulers.asyncio import AsyncIOScheduler
18
 
19
  # ╔═══════════════════════════════════════════════════════════════════╗
20
- # β•‘ πŸŒ‰ THE CURL BRIDGE (HF PORT 7860 FIX) β•‘
21
  # β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
22
 
23
- # ⚠️ CRITICAL: Must be 7860 for Hugging Face to keep it alive
24
  BRIDGE_PORT = 7860
25
-
26
  PROXY_TARGET = "https://lucky-hat-e0d0.brukg9419.workers.dev"
27
  CLOUDFLARE_IP = "104.21.28.169"
28
 
29
  app = Flask(__name__)
30
 
31
- # ⚠️ CRITICAL: Health Check so HF sees we are online
32
  @app.route('/')
33
  def health_check():
34
- return "βœ… PEKKA Bridge is Running on Port 7860!", 200
35
 
36
  def run_curl(method, url, data=None):
37
  parsed = urlparse(url)
38
  domain = parsed.hostname
39
 
 
40
  cmd = [
41
  "curl",
42
  "-X", method, url,
43
- # ⚠️ IP Resolve Trick (Your Secret Sauce)
44
  "--resolve", f"{domain}:443:{CLOUDFLARE_IP}",
45
- # ⚠️ User-Agent (Cloudflare blocks without this)
46
  "-H", "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
 
47
  "-k", "-s", "--max-time", "30"
48
  ]
49
 
50
- cmd.extend(["-H", "Content-Type: application/json"])
51
-
52
  if data:
53
- cmd.extend(["-d", json.dumps(data)])
 
 
 
54
 
55
  try:
56
- # Debug Print: See exactly what we are sending
57
- # print(f"➑️ Curl sending to {method} {url}")
58
-
59
  result = subprocess.run(
60
- cmd, capture_output=True, text=True, timeout=35
 
 
 
 
61
  )
62
 
63
  if not result.stdout:
64
- print(f"❌ [BRIDGE ERROR] Empty response! Stderr: {result.stderr}")
65
  return json.dumps({"ok": False, "description": "Empty Curl Response", "error_code": 500})
66
 
67
  return result.stdout
@@ -73,15 +76,20 @@ def run_curl(method, url, data=None):
73
  @app.route('/bot<token>/<method>', methods=['POST', 'GET'])
74
  def proxy(token, method):
75
  real_url = f"{PROXY_TARGET}/bot{token}/{method}"
76
- data = request.json if request.is_json else request.args.to_dict()
77
 
78
- # Run the Curl Command
79
- response_text = run_curl(request.method, real_url, data)
 
 
 
80
 
 
 
 
 
81
  return Response(response_text, mimetype='application/json')
82
 
83
  def start_bridge():
84
- # ⚠️ CRITICAL: Host must be 0.0.0.0 (Public) not 127.0.0.1
85
  print(f"πŸš€ Starting Bridge on 0.0.0.0:{BRIDGE_PORT}")
86
  app.run(host="0.0.0.0", port=BRIDGE_PORT, threaded=True)
87
 
@@ -94,7 +102,6 @@ time.sleep(3)
94
 
95
  TELEGRAM_TOKEN = "8484056866:AAFdmEZCmedznAA2DWRkyFLjS6uTirVFMEQ"
96
 
97
- # Connect Bot to Localhost:7860
98
  session = AiohttpSession(
99
  api=TelegramAPIServer.from_base(f"http://127.0.0.1:{BRIDGE_PORT}")
100
  )
@@ -104,14 +111,13 @@ scheduler = AsyncIOScheduler()
104
 
105
  @dp.message(CommandStart())
106
  async def handle_start(message: types.Message):
107
- print("πŸ“© Received /start command!")
108
  try:
109
- await message.answer("βœ… PEKKA is Online (Port 7860 Fixed)!")
110
- print("πŸ“€ Reply Sent Successfully!")
111
  except Exception as e:
112
  print(f"❌ Send Failed: {e}")
113
 
114
- # ── STARTUP ──
115
  async def on_startup():
116
  print("πŸ€– PEKKA AGENT IS STARTING...")
117
  scheduler.start()
@@ -121,7 +127,7 @@ async def main():
121
  try:
122
  await bot.delete_webhook(drop_pending_updates=True)
123
  except Exception as e:
124
- print(f"⚠️ Webhook warning: {e}")
125
 
126
  await dp.start_polling(bot)
127
 
 
17
  from apscheduler.schedulers.asyncio import AsyncIOScheduler
18
 
19
  # ╔═══════════════════════════════════════════════════════════════════╗
20
+ # β•‘ πŸŒ‰ THE CURL BRIDGE (BODY-LOSS FIX) β•‘
21
  # β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
22
 
 
23
  BRIDGE_PORT = 7860
 
24
  PROXY_TARGET = "https://lucky-hat-e0d0.brukg9419.workers.dev"
25
  CLOUDFLARE_IP = "104.21.28.169"
26
 
27
  app = Flask(__name__)
28
 
29
+ # Health Check
30
  @app.route('/')
31
  def health_check():
32
+ return "βœ… PEKKA Bridge is Running!", 200
33
 
34
  def run_curl(method, url, data=None):
35
  parsed = urlparse(url)
36
  domain = parsed.hostname
37
 
38
+ # 1. Prepare Command
39
  cmd = [
40
  "curl",
41
  "-X", method, url,
 
42
  "--resolve", f"{domain}:443:{CLOUDFLARE_IP}",
 
43
  "-H", "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
44
+ "-H", "Content-Type: application/json",
45
  "-k", "-s", "--max-time", "30"
46
  ]
47
 
48
+ # 2. Prepare Data (The Fix: Use stdin)
49
+ input_str = None
50
  if data:
51
+ # Tell curl to read from stdin
52
+ cmd.append("--data-binary")
53
+ cmd.append("@-")
54
+ input_str = json.dumps(data)
55
 
56
  try:
57
+ # 3. Execute with Input Piped
 
 
58
  result = subprocess.run(
59
+ cmd,
60
+ input=input_str, # Pass JSON string here
61
+ capture_output=True,
62
+ text=True,
63
+ timeout=35
64
  )
65
 
66
  if not result.stdout:
67
+ print(f"❌ [BRIDGE ERROR] Empty Curl Output. Stderr: {result.stderr}")
68
  return json.dumps({"ok": False, "description": "Empty Curl Response", "error_code": 500})
69
 
70
  return result.stdout
 
76
  @app.route('/bot<token>/<method>', methods=['POST', 'GET'])
77
  def proxy(token, method):
78
  real_url = f"{PROXY_TARGET}/bot{token}/{method}"
 
79
 
80
+ # ⚠️ CRITICAL FIX: Force parse JSON even if header is slightly different
81
+ data = request.get_json(force=True, silent=True)
82
+ if not data:
83
+ # Fallback: check form data or args if JSON failed
84
+ data = request.form.to_dict() or request.args.to_dict()
85
 
86
+ # Debug: Print first 50 chars of data to prove we have it
87
+ # print(f"πŸ”„ Proxying {method} | Data size: {len(str(data))}")
88
+
89
+ response_text = run_curl(request.method, real_url, data)
90
  return Response(response_text, mimetype='application/json')
91
 
92
  def start_bridge():
 
93
  print(f"πŸš€ Starting Bridge on 0.0.0.0:{BRIDGE_PORT}")
94
  app.run(host="0.0.0.0", port=BRIDGE_PORT, threaded=True)
95
 
 
102
 
103
  TELEGRAM_TOKEN = "8484056866:AAFdmEZCmedznAA2DWRkyFLjS6uTirVFMEQ"
104
 
 
105
  session = AiohttpSession(
106
  api=TelegramAPIServer.from_base(f"http://127.0.0.1:{BRIDGE_PORT}")
107
  )
 
111
 
112
  @dp.message(CommandStart())
113
  async def handle_start(message: types.Message):
114
+ print(f"πŸ“© Received /start from {message.from_user.id}")
115
  try:
116
+ await message.answer("βœ… PEKKA is Online (Body-Loss Fixed)!")
117
+ print("πŸ“€ Reply Sent!")
118
  except Exception as e:
119
  print(f"❌ Send Failed: {e}")
120
 
 
121
  async def on_startup():
122
  print("πŸ€– PEKKA AGENT IS STARTING...")
123
  scheduler.start()
 
127
  try:
128
  await bot.delete_webhook(drop_pending_updates=True)
129
  except Exception as e:
130
+ print(f"⚠️ Webhook warning (safe): {e}")
131
 
132
  await dp.start_polling(bot)
133