nikhilyadavtemp1 commited on
Commit
4b4c033
Β·
1 Parent(s): dac072a

refactor: remove pyromod and use lifespan for better loop management

Browse files
Files changed (3) hide show
  1. app.py +21 -15
  2. bot.py +13 -28
  3. requirements.txt +0 -1
app.py CHANGED
@@ -2,8 +2,8 @@ import os
2
  import shutil
3
  import time
4
  import uuid
5
- import threading
6
  import asyncio
 
7
  from typing import List, Optional
8
  from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request
9
  from fastapi.responses import FileResponse
@@ -11,13 +11,10 @@ from fastapi.staticfiles import StaticFiles
11
  from config import UPLOAD_DIR, BASE_URL
12
  from bot import bot as telegram_bot
13
 
14
- app = FastAPI(title="NexusShare Web API")
15
-
16
- @app.on_event("startup")
17
- async def startup_event():
18
- # Start Cleanup Task
19
- def cleanup_old_files():
20
- while True:
21
  now = time.time()
22
  if os.path.exists(UPLOAD_DIR):
23
  for filename in os.listdir(UPLOAD_DIR):
@@ -27,20 +24,29 @@ async def startup_event():
27
  try:
28
  os.remove(file_path)
29
  except: pass
30
- time.sleep(3600)
31
-
32
- threading.Thread(target=cleanup_old_files, daemon=True).start()
 
 
 
 
 
33
 
34
- # Start Telegram Bot
35
  try:
36
  await telegram_bot.start()
37
  print("πŸš€ Telegram Bot started successfully!")
38
  except Exception as e:
39
  print(f"❌ Failed to start Telegram Bot: {e}")
40
-
41
- @app.on_event("shutdown")
42
- async def shutdown_event():
 
 
43
  await telegram_bot.stop()
 
 
 
44
 
45
  app.mount("/static", StaticFiles(directory="static"), name="static")
46
 
 
2
  import shutil
3
  import time
4
  import uuid
 
5
  import asyncio
6
+ from contextlib import asynccontextmanager
7
  from typing import List, Optional
8
  from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request
9
  from fastapi.responses import FileResponse
 
11
  from config import UPLOAD_DIR, BASE_URL
12
  from bot import bot as telegram_bot
13
 
14
+ # --- CLEANUP TASK ---
15
+ async def cleanup_old_files():
16
+ while True:
17
+ try:
 
 
 
18
  now = time.time()
19
  if os.path.exists(UPLOAD_DIR):
20
  for filename in os.listdir(UPLOAD_DIR):
 
24
  try:
25
  os.remove(file_path)
26
  except: pass
27
+ except Exception as e:
28
+ print(f"Cleanup error: {e}")
29
+ await asyncio.sleep(3600)
30
+
31
+ @asynccontextmanager
32
+ async def lifespan(app: FastAPI):
33
+ # Startup: Start Cleanup Task and Telegram Bot
34
+ cleanup_task = asyncio.create_task(cleanup_old_files())
35
 
 
36
  try:
37
  await telegram_bot.start()
38
  print("πŸš€ Telegram Bot started successfully!")
39
  except Exception as e:
40
  print(f"❌ Failed to start Telegram Bot: {e}")
41
+
42
+ yield
43
+
44
+ # Shutdown: Stop Cleanup Task and Telegram Bot
45
+ cleanup_task.cancel()
46
  await telegram_bot.stop()
47
+ print("πŸ‘‹ Bot and cleanup task stopped.")
48
+
49
+ app = FastAPI(title="NexusShare Web API", lifespan=lifespan)
50
 
51
  app.mount("/static", StaticFiles(directory="static"), name="static")
52
 
bot.py CHANGED
@@ -2,31 +2,23 @@ import os
2
  import time
3
  import uuid
4
  import asyncio
5
- import pyromod
6
- from pyrogram import Client, filters, idle
7
  from pyrogram.types import Message
8
  from config import API_ID, API_HASH, BOT_TOKEN, UPLOAD_DIR, BASE_URL
9
 
10
- print("--- Starting Bot Initialization ---")
11
-
12
- if not API_ID:
13
- print("ERROR: API_ID is missing!")
14
- if not API_HASH:
15
- print("ERROR: API_HASH is missing!")
16
- if not BOT_TOKEN:
17
- print("ERROR: BOT_TOKEN/TELEGRAM_TOKEN is missing!")
18
 
19
  if not all([API_ID, API_HASH, BOT_TOKEN]):
20
- print("Bot configuration incomplete. Exiting...")
21
- exit(1)
22
-
23
- print(f"Config loaded: API_ID={API_ID}, API_HASH={API_HASH[:4]}..., BOT_TOKEN={BOT_TOKEN[:4]}...")
24
 
25
  bot = Client(
26
  "nexus_bot",
27
- api_id=int(API_ID),
28
- api_hash=API_HASH,
29
- bot_token=BOT_TOKEN,
30
  in_memory=True
31
  )
32
 
@@ -52,11 +44,13 @@ async def id_cmd(client, message: Message):
52
  @bot.on_message(filters.command("files") & filters.private)
53
  async def list_tg_files(client, message: Message):
54
  user_id = f"tg{message.from_user.id}"
 
 
 
55
  files_list = []
56
  for filename in os.listdir(UPLOAD_DIR):
57
  if filename.startswith(f"{user_id}_"):
58
- parts = filename.split("_")
59
- display_name = "_".join(parts[2:])
60
  files_list.append(f"β€’ `{display_name}`\n β”” {BASE_URL}/download/{filename}")
61
 
62
  if not files_list:
@@ -108,12 +102,3 @@ async def handle_uploads(client, message: Message):
108
  )
109
  except Exception as e:
110
  await status.edit_text(f"❌ **Upload Failed:** {str(e)}")
111
-
112
- async def main():
113
- await bot.start()
114
- print("πŸš€ High-Speed Telegram Bot Started!")
115
- await idle()
116
- await bot.stop()
117
-
118
- if __name__ == "__main__":
119
- asyncio.run(main())
 
2
  import time
3
  import uuid
4
  import asyncio
5
+ from pyrogram import Client, filters
 
6
  from pyrogram.types import Message
7
  from config import API_ID, API_HASH, BOT_TOKEN, UPLOAD_DIR, BASE_URL
8
 
9
+ print("--- Initializing Telegram Bot ---")
 
 
 
 
 
 
 
10
 
11
  if not all([API_ID, API_HASH, BOT_TOKEN]):
12
+ print("CRITICAL: Missing API_ID, API_HASH, or BOT_TOKEN!")
13
+ # We don't exit here so the Web server can still run and show logs
14
+ else:
15
+ print(f"Bot Config: API_ID={API_ID}, API_HASH={API_HASH[:4]}..., BOT_TOKEN={BOT_TOKEN[:4]}...")
16
 
17
  bot = Client(
18
  "nexus_bot",
19
+ api_id=int(API_ID) if API_ID else 0,
20
+ api_hash=API_HASH or "",
21
+ bot_token=BOT_TOKEN or "",
22
  in_memory=True
23
  )
24
 
 
44
  @bot.on_message(filters.command("files") & filters.private)
45
  async def list_tg_files(client, message: Message):
46
  user_id = f"tg{message.from_user.id}"
47
+ if not os.path.exists(UPLOAD_DIR):
48
+ return await message.reply_text("No files found.")
49
+
50
  files_list = []
51
  for filename in os.listdir(UPLOAD_DIR):
52
  if filename.startswith(f"{user_id}_"):
53
+ display_name = "_".join(filename.split("_")[2:])
 
54
  files_list.append(f"β€’ `{display_name}`\n β”” {BASE_URL}/download/{filename}")
55
 
56
  if not files_list:
 
102
  )
103
  except Exception as e:
104
  await status.edit_text(f"❌ **Upload Failed:** {str(e)}")
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -4,5 +4,4 @@ python-multipart
4
  aiofiles
5
  pyrofork
6
  tgcrypto
7
- pyromod
8
  aiohttp
 
4
  aiofiles
5
  pyrofork
6
  tgcrypto
 
7
  aiohttp