iSoFe commited on
Commit
64ced8b
·
verified ·
1 Parent(s): 99bf172

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +58 -52
bot.py CHANGED
@@ -17,75 +17,81 @@ BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
17
  # Initialize Bot
18
  app = Client("nekoo_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
19
 
20
- async def progress(current, total, status_msg, action):
21
- """Update progress every 5 seconds"""
22
- try:
23
- percentage = current * 100 / total
24
- if current % (5 * 1024 * 1024) == 0: # Update every 5MB roughly
25
- await status_msg.edit(f"{action}: {percentage:.1f}%")
26
- except Exception:
27
- pass
28
 
 
29
  @app.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.voice | filters.photo))
30
  async def handle_file(client: Client, message: Message):
31
- # Send status message
32
  status_msg = await message.reply_text("⏳ جاري المعالجة...")
33
 
34
  try:
35
- # Get file attributes
36
  media = getattr(message, message.media.value)
37
  file_name = getattr(media, "file_name", "file")
38
- if not file_name:
39
- if message.photo: file_name = "photo.jpg"
40
- elif message.voice: file_name = "voice.ogg"
41
- elif message.video: file_name = "video.mp4"
42
- elif message.audio: file_name = "audio.mp3"
43
-
44
  file_size = getattr(media, "file_size", 0)
 
 
 
 
 
 
 
 
45
 
46
- # 1. Download stream generator
47
  async def file_generator():
48
  async for chunk in client.stream_media(message, limit=0):
49
  yield chunk
50
 
51
- # 2. Upload to Nekoo using aiohttp with stream
52
- # Note: We need to construct multipart manually or use a library that supports async generators in multipart
53
- # aiohttp supports passing a generator as data, but for multipart it's trickier.
54
- # Let's use a simpler approach: Download to disk if < 500MB, otherwise stream if possible.
55
- # But for "Excellence", true streaming is best.
56
-
57
- # Simple approach for now to ensure reliability on free tier (disk space might be low):
58
- # We will use Pyrogram's download to disk, then upload.
59
- # Render free tier has ephemeral disk, enough for reasonable files.
60
- # If user wants 2GB, we really should stream.
61
-
62
- # Let's try direct streaming pipe
63
- form = aiohttp.FormData()
64
- form.add_field('reqtype', 'fileupload')
65
- form.add_field('fileToUpload', file_generator(), filename=file_name)
66
-
67
  async with aiohttp.ClientSession() as session:
68
- await status_msg.edit("🚀 جاري الرفع إلى Catbox...")
69
- async with session.post("https://catbox.moe/user/api.php", data=form) as response:
70
- if response.status == 200:
71
- url = await response.text() # Catbox يرجع الرابط كنص مباشر
72
- if url.startswith("http"):
73
- await status_msg.edit(
74
- f"✅ **تم الرفع!**\n\n"
75
- f"📄 **الملف:** `{file_name}`\n"
76
- f"📦 **الحجم:** `{file_size / 1024 / 1024:.2f} MB`\n\n"
77
- f"🔗 **الرابط:** {url}",
78
- disable_web_page_preview=True
79
- )
80
- else:
81
- await status_msg.edit(f"❌ خطأ من Nekoo: {data}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  else:
83
- text = await response.text()
84
- await status_msg.edit(f"❌ فشل الرفع: {response.status} - {text}")
85
 
86
  except Exception as e:
87
  logger.error(f"Error: {e}")
88
- await status_msg.edit(f"❌ حدث خطأ: {str(e)}")
89
 
90
- print("Bot Started!")
91
- app.run()
 
17
  # Initialize Bot
18
  app = Client("nekoo_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
19
 
20
+ # دالة الاستجابة لأمر /start
21
+ @app.on_message(filters.command("start") & filters.private)
22
+ async def start_command(client: Client, message: Message):
23
+ await message.reply_text(
24
+ "أهلاً بك! 🚀\n"
25
+ "أنا بوت الرفع المباشر.\n"
26
+ "فقط أرسل لي أي (صورة، فيديو، ملف، أو صوت) وسأقوم برفعه لك فوراً على سيرفرات Gofile وإعطائك الرابط."
27
+ )
28
 
29
+ # دالة استلام الملفات ورفعها
30
  @app.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.voice | filters.photo))
31
  async def handle_file(client: Client, message: Message):
32
+ # إرسال رسالة الحالة
33
  status_msg = await message.reply_text("⏳ جاري المعالجة...")
34
 
35
  try:
36
+ # الحصول على خصائص الملف
37
  media = getattr(message, message.media.value)
38
  file_name = getattr(media, "file_name", "file")
 
 
 
 
 
 
39
  file_size = getattr(media, "file_size", 0)
40
+
41
+ # معالجة الصور التي لا تحتوي على اسم افتراضي
42
+ if message.photo:
43
+ file_name = "photo.jpg"
44
+ file_size = message.photo.file_size
45
+
46
+ if not file_name:
47
+ file_name = "unknown_file"
48
 
49
+ # دالة لتوليد تدفق الملف (Stream) من تيليجرام لتجنب استهلاك الرام
50
  async def file_generator():
51
  async for chunk in client.stream_media(message, limit=0):
52
  yield chunk
53
 
54
+ # بداية الاتصال بسيرفرات الرفع
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  async with aiohttp.ClientSession() as session:
56
+
57
+ # الخطوة الأولى: البحث عن أفضل وأسرع سيرفر متاح
58
+ await status_msg.edit("🔍 جاري الاتصال بسيرفرات Gofile...")
59
+ async with session.get("https://api.gofile.io/servers") as server_resp:
60
+ server_data = await server_resp.json()
61
+
62
+ if server_data.get("status") == "ok":
63
+ server_name = server_data["data"]["servers"][0]["name"]
64
+ upload_url = f"https://{server_name}.gofile.io/contents/upload"
65
+
66
+ # تجهيز الملف للرفع (بدون توكن ليكو�� الرفع كضيف)
67
+ form = aiohttp.FormData()
68
+ form.add_field('file', file_generator(), filename=file_name)
69
+
70
+ # الخطوة الثانية: الرفع إلى السيرفر المختار
71
+ await status_msg.edit(f"🚀 جاري الرفع إلى Gofile ({server_name})...")
72
+ async with session.post(upload_url, data=form) as response:
73
+ if response.status == 200:
74
+ data = await response.json()
75
+ if data.get("status") == "ok":
76
+ url = data["data"]["downloadPage"]
77
+ await status_msg.edit(
78
+ f"✅ **تم الرفع بنجاح!**\n\n"
79
+ f"📄 **الملف:** `{file_name}`\n"
80
+ f"📦 **الحجم:** `{file_size / 1024 / 1024:.2f} MB`\n\n"
81
+ f"🔗 **الرابط:** {url}",
82
+ disable_web_page_preview=True
83
+ )
84
+ else:
85
+ await status_msg.edit(f"❌ خطأ من Gofile: {data.get('status')}")
86
+ else:
87
+ text = await response.text()
88
+ await status_msg.edit(f"❌ فشل الرفع: {response.status} - {text}")
89
  else:
90
+ await status_msg.edit("❌ فشل الاتصال بخوادم Gofile.")
 
91
 
92
  except Exception as e:
93
  logger.error(f"Error: {e}")
94
+ await status_msg.edit(f"❌ حدث خطأ أثناء المعالجة: {e}")
95
 
96
+ if __name__ == "__main__":
97
+ app.run()