Opera8 commited on
Commit
12449e0
·
verified ·
1 Parent(s): 9b101f3

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +132 -56
main.py CHANGED
@@ -1,73 +1,149 @@
1
- import os, asyncio, aiohttp, threading, uuid, base64, time, builtins
 
 
 
 
 
 
 
2
  from flask import Flask
 
 
3
  from rubpy import Client, filters
4
 
 
 
 
5
  app = Flask(__name__)
6
- @app.route('/')
7
- def home(): return "🚀 ربات در حال اجراست. بخش Logs را چک کنید."
8
 
9
- def run_flask(): app.run(host="0.0.0.0", port=7860)
 
 
10
 
11
- # ترفند دور زدن ورودی کیبورد
12
- def mock_input(prompt):
13
- p = prompt.lower()
14
- if "phone" in p or "شماره" in p:
15
- return os.environ.get("phone", "989120132730")
16
- if "code" in p or "کد" in p:
17
- # اگر کد در سکرت‌ها نبود، اینجا گیر می‌کنه تا تو بری سکرت رو آپدیت کنی
18
- while True:
19
- c = os.environ.get("code", "")
20
- if len(c) > 4: return c
21
- time.sleep(2)
22
- return "y"
23
 
24
- builtins.input = mock_input
 
 
 
 
25
 
26
- async def start_bot():
27
- session_file = "my_userbot.sqlite"
28
-
29
- # اول چک می‌کنیم سشن نهایی داریم یا نه
30
- s_string = os.environ.get("SESSION_STRING", "")
31
- if s_string:
32
  with open(session_file, "wb") as f:
33
- f.write(base64.b64decode(s_string))
34
- print("✅ سشن نهایی بارگذاری شد.")
35
-
36
- bot = Client("my_userbot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # شروع فرآیند لاگین (اگر سشن نباشد شماره و کد را از سکرت‌ها می‌گیرد)
39
- await bot.start()
 
 
40
 
41
- # اگر تازه لاگین شده، کد سشن رو چاپ می‌کنه
42
- if not s_string:
43
- with open(session_file, "rb") as f:
44
- encoded = base64.b64encode(f.read()).decode('utf-8')
45
- print("\n" + "⭐"*20)
46
- print("✅ لاگین موفق! این کد SESSION_STRING شماست:\n")
47
- print(encoded)
48
- print("\n" + "⭐"*20)
49
-
50
- @bot.on_message_updates(filters.private)
51
- async def main_handler(client, update):
52
- msg = update.message if hasattr(update, 'message') else update
53
- if msg.text and msg.text.startswith("http"):
54
- asyncio.create_task(process_upload(client, msg.object_guid, msg.message_id, msg.text))
55
 
56
- async def process_upload(client, chat_id, message_id, url):
57
- path = f"dl_{uuid.uuid4().hex[:6]}.dat"
58
  try:
59
- s = await client.send_message(chat_id, "⏳ در حال دانلود و آپلود (تا ۲ گیگ)...")
60
- async with aiohttp.ClientSession() as sess:
61
- async with sess.get(url, timeout=0) as r:
62
- with open(path, 'wb') as f:
63
- async for c in r.content.iter_chunked(2*1024*1024): f.write(c)
64
- await client.send_document(chat_id, path, caption=f"✅ فایل آماده شد:\n{url}")
65
- await client.delete_messages(chat_id, [s.message_id])
 
 
 
 
 
 
 
66
  except Exception as e:
67
- await client.send_message(chat_id, f"❌ خطا: {str(e)[:100]}")
68
- finally:
69
- if os.path.exists(path): os.remove(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  if __name__ == "__main__":
 
72
  threading.Thread(target=run_flask, daemon=True).start()
73
- asyncio.run(start_bot())
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ import aiohttp
4
+ import threading
5
+ import uuid
6
+ import urllib.parse
7
+ import traceback
8
+ import base64
9
  from flask import Flask
10
+
11
+ # نصب کتابخانه rubpy==6.9.9 الزامی است
12
  from rubpy import Client, filters
13
 
14
+ # ==============================================================================
15
+ # 🟢 تنظیمات وب‌سرور برای زنده نگه داشتن اسپیس
16
+ # ==============================================================================
17
  app = Flask(__name__)
 
 
18
 
19
+ @app.route('/')
20
+ def home():
21
+ return "🚀 سلف‌بات آپلودر ۲ گیگابایتی فعال است! لینک‌ها را در پیام‌های ذخیره شده بفرستید."
22
 
23
+ def run_flask():
24
+ # پورت ۷۸۶۰ مخصوص هاگینگ فیس است
25
+ app.run(host="0.0.0.0", port=7860, threaded=True)
 
 
 
 
 
 
 
 
 
26
 
27
+ # ==============================================================================
28
+ # 🟢 استخراج فایل سشن از متغیر SESSION_STRING
29
+ # ==============================================================================
30
+ session_string = os.environ.get("SESSION_STRING", "")
31
+ session_file = "my_userbot.rp"
32
 
33
+ if session_string:
34
+ try:
 
 
 
 
35
  with open(session_file, "wb") as f:
36
+ f.write(base64.b64decode(session_string))
37
+ print("✅ فایل سشن با موفقیت از متغیر مخفی بازسازی شد.")
38
+ except Exception as e:
39
+ print(f"❌ خطا در بازسازی سشن: {e}")
40
+ else:
41
+ print("⚠️ ارور: SESSION_STRING یافت نشد! ربات نمی‌تواند آنلاین شود.")
42
+
43
+ # ساخت کلاینت سلف‌بات (اکانت شخصی)
44
+ bot = Client("my_userbot")
45
+
46
+ # ==============================================================================
47
+ # 🟢 تابع دانلود فایل از لینک
48
+ # ==============================================================================
49
+ async def download_file(url, chat_id, message_id, client):
50
+ # اصلاح لینک‌های دراپ‌باکس برای دانلود مستقیم
51
+ if "dropbox.com" in url:
52
+ url = url.replace("dl=0", "dl=1") if "dl=0" in url else (url + "&dl=1" if "?" in url else url + "?dl=1")
53
+
54
+ temp_dir = "/app/downloads"
55
+ os.makedirs(temp_dir, exist_ok=True)
56
 
57
+ # استخراج نام فایل از لینک یا ساخت نام تصادفی
58
+ parsed_url = urllib.parse.urlparse(url)
59
+ filename = os.path.basename(parsed_url.path) or f"file_{uuid.uuid4().hex[:6]}.dat"
60
+ file_path = os.path.join(temp_dir, f"{uuid.uuid4().hex[:4]}_{filename}")
61
 
62
+ status_msg_id = None
63
+ try:
64
+ # ارسال پیام وضعیت
65
+ status_msg = await client.send_message(chat_id, "📥 شروع دانلود از سرور اصلی...\n(حجم مجاز: تا 2 گیگابایت)", reply_to_message_id=message_id)
66
+ status_msg_id = status_msg.message_id
67
+ except: pass
 
 
 
 
 
 
 
 
68
 
 
 
69
  try:
70
+ # استفاده از aiohttp برای دانلود تکه‌ای (Chunked) جهت مدیریت رم
71
+ async with aiohttp.ClientSession() as session:
72
+ async with session.get(url, timeout=None) as response:
73
+ if response.status != 200:
74
+ if status_msg_id: await client.edit_message_text(chat_id, status_msg_id, f"❌ خطا در دانلود! کد وضعیت: {response.status}")
75
+ return None, status_msg_id
76
+
77
+ with open(file_path, 'wb') as f:
78
+ async for chunk in response.content.iter_chunked(1024 * 1024 * 2): # تکه‌های ۲ مگابایتی
79
+ if chunk:
80
+ f.write(chunk)
81
+
82
+ if status_msg_id: await client.edit_message_text(chat_id, status_msg_id, "✅ دانلود کامل شد. در حال آپلود در روبیکا...")
83
+ return file_path, status_msg_id
84
  except Exception as e:
85
+ if status_msg_id: await client.edit_message_text(chat_id, status_msg_id, f"❌ خطای شبکه در دانلود: {str(e)[:100]}")
86
+ return None, status_msg_id
87
+
88
+ # ==============================================================================
89
+ # 🟢 پردازش و آپلود نهایی
90
+ # ==============================================================================
91
+ async def process_and_upload(client, chat_id, message_id, url):
92
+ file_path, status_id = await download_file(url, chat_id, message_id, client)
93
+
94
+ if file_path and os.path.exists(file_path):
95
+ try:
96
+ # ارسال فایل به صورت مستند (Document)
97
+ # در سلف‌بات محدودیت حجم بسیار بیشتر از ربات‌های معمولی است
98
+ await client.send_document(
99
+ chat_id,
100
+ file_path,
101
+ caption=f"✅ فایل با موفقیت منتقل شد.\n🔗 لینک منبع:\n{url}",
102
+ reply_to_message_id=message_id
103
+ )
104
+
105
+ # حذف پیام وضعیت برای تمیز ماندن چت
106
+ if status_id:
107
+ try: await client.delete_messages(chat_id, [status_id])
108
+ except: pass
109
+
110
+ except Exception as e:
111
+ error_msg = f"❌ خطا در آپلود روبیکا:\n{str(e)[:150]}"
112
+ if status_id: await client.edit_message_text(chat_id, status_id, error_msg)
113
+ else: await client.send_message(chat_id, error_msg)
114
+ finally:
115
+ # حذف فایل از روی هارد سرور برای جلوگیری از پر شدن فضا
116
+ if os.path.exists(file_path):
117
+ os.remove(file_path)
118
 
119
+ # ==============================================================================
120
+ # 🟢 هندلر پیام‌های دریافتی (فقط در پی‌وی و پیام‌های ذخیره شده)
121
+ # ==============================================================================
122
+ @bot.on_message_updates(filters.private)
123
+ async def message_handler(client, update):
124
+ try:
125
+ # گرفتن متن پیام
126
+ message = update.message if hasattr(update, 'message') else update
127
+ text = str(message.text or "").strip()
128
+
129
+ # اگر متن با http شروع شده بود، یعنی لینک دانلود است
130
+ if text.startswith("http"):
131
+ # اجرای عملیات در پس‌زمینه برای اینکه ربات متوقف نشود
132
+ asyncio.create_task(process_and_upload(client, message.object_guid, message.message_id, text))
133
+
134
+ elif text == "سلام":
135
+ await client.send_message(message.object_guid, "سلام حامد جان! لینک فایل (حتی ۲ گیگابایتی) رو بفرست تا مستقیم برات آپلودش کنم.")
136
+
137
+ except Exception:
138
+ traceback.print_exc()
139
+
140
+ # ==============================================================================
141
+ # 🟢 اجرای همزمان وب‌سرور و ربات
142
+ # ==============================================================================
143
  if __name__ == "__main__":
144
+ # اجرای وب‌سرور در یک ترد جداگانه
145
  threading.Thread(target=run_flask, daemon=True).start()
146
+
147
+ print("🚀 سلف‌بات در حال تلاش برای اتصال به روبیکا...")
148
+ # اجرای ربات
149
+ bot.run()