Mafia2008 commited on
Commit
219e24c
Β·
verified Β·
1 Parent(s): b6a9b42

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +48 -32
main.py CHANGED
@@ -10,14 +10,22 @@ from fastapi import FastAPI, Request, HTTPException
10
  from fastapi.responses import StreamingResponse
11
  import uvicorn
12
 
 
 
 
 
 
13
  # --- CONFIGURATION ---
14
- API_ID = int(os.environ.get("API_ID"))
15
- API_HASH = os.environ.get("API_HASH")
16
- BOT_TOKEN = os.environ.get("BOT_TOKEN")
17
- STORAGE_CHANNEL = int(os.environ.get("STORAGE_CHANNEL"))
 
 
 
 
18
 
19
- # --- BOT CLIENT (FIXED) ---
20
- # Added 'ipv6=False' to force IPv4 connection (Fixes Timeout)
21
  client = Client(
22
  "worker_bot",
23
  api_id=API_ID,
@@ -25,23 +33,27 @@ client = Client(
25
  bot_token=BOT_TOKEN,
26
  in_memory=True,
27
  no_updates=True,
28
- ipv6=False # <--- THIS IS THE FIX
 
29
  )
30
 
31
  @asynccontextmanager
32
  async def lifespan(app: FastAPI):
33
- print("⏳ Connecting to Telegram...")
34
  try:
35
  await client.start()
36
- print("βœ… Worker Started & Connected!")
 
37
  except Exception as e:
38
- print(f"❌ Failed to connect: {e}")
 
39
 
40
  yield
41
 
42
  print("πŸ›‘ Stopping Worker...")
43
  try:
44
- await client.stop()
 
45
  except:
46
  pass
47
 
@@ -55,16 +67,21 @@ class ByteStreamer:
55
  async def yield_file(self, file_id, offset, first_part_cut, last_part_cut, part_count, chunk_size):
56
  client = self.client
57
 
58
- ms = client.media_sessions.get(file_id.dc_id)
59
- if not ms:
60
- if file_id.dc_id != await client.storage.dc_id():
61
- auth_key = await Auth(client, file_id.dc_id, await client.storage.test_mode()).create()
62
- ms = Session(client, file_id.dc_id, auth_key, await client.storage.test_mode(), is_media=True)
63
- await ms.start()
64
- else:
65
- ms = client.session
66
- client.media_sessions[file_id.dc_id] = ms
67
-
 
 
 
 
 
68
  loc = raw.types.InputDocumentFileLocation(
69
  id=file_id.media_id,
70
  access_hash=file_id.access_hash,
@@ -83,14 +100,10 @@ class ByteStreamer:
83
  chunk = r.bytes
84
  if not chunk: break
85
 
86
- if part_count == 1:
87
- yield chunk[first_part_cut:last_part_cut]
88
- elif curr == 1:
89
- yield chunk[first_part_cut:]
90
- elif curr == part_count:
91
- yield chunk[:last_part_cut]
92
- else:
93
- yield chunk
94
 
95
  curr += 1
96
  offset += chunk_size
@@ -101,12 +114,16 @@ class ByteStreamer:
101
 
102
  @app.get("/stream/{message_id}/{filename}")
103
  async def stream_handler(req: Request, message_id: int, filename: str):
 
 
 
 
 
104
  try:
105
  msg = await client.get_messages(STORAGE_CHANNEL, message_id)
106
  media = msg.document or msg.video or msg.audio
107
 
108
- if not media:
109
- raise HTTPException(404, "File not found in Storage Channel")
110
 
111
  file_id = FileId.decode(media.file_id)
112
  file_size = media.file_size
@@ -136,7 +153,6 @@ async def stream_handler(req: Request, message_id: int, filename: str):
136
  "Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}",
137
  "Content-Length": str(req_len),
138
  }
139
-
140
  return StreamingResponse(body, status_code=206 if range_header else 200, headers=headers)
141
 
142
  except Exception as e:
 
10
  from fastapi.responses import StreamingResponse
11
  import uvicorn
12
 
13
+ # --- 1. ENABLE DEBUG LOGGING ---
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger("pyrogram")
16
+ logger.setLevel(logging.WARNING) # Switch to INFO if you need deeper debug
17
+
18
  # --- CONFIGURATION ---
19
+ try:
20
+ API_ID = int(os.environ.get("API_ID"))
21
+ API_HASH = os.environ.get("API_HASH")
22
+ BOT_TOKEN = os.environ.get("BOT_TOKEN")
23
+ STORAGE_CHANNEL = int(os.environ.get("STORAGE_CHANNEL"))
24
+ except ValueError:
25
+ print("❌ ERROR: Env vars are missing or invalid! Check API_ID/STORAGE_CHANNEL.")
26
+ exit(1)
27
 
28
+ # --- BOT CLIENT (HARDENED) ---
 
29
  client = Client(
30
  "worker_bot",
31
  api_id=API_ID,
 
33
  bot_token=BOT_TOKEN,
34
  in_memory=True,
35
  no_updates=True,
36
+ ipv6=False, # FORCE IPv4
37
+ workdir="/tmp" # FORCE WRITABLE DIR
38
  )
39
 
40
  @asynccontextmanager
41
  async def lifespan(app: FastAPI):
42
+ print(f"⏳ Connecting to Telegram with API_ID: {API_ID}...")
43
  try:
44
  await client.start()
45
+ me = await client.get_me()
46
+ print(f"βœ… Worker Started as: {me.first_name} (@{me.username})")
47
  except Exception as e:
48
+ print(f"❌ CRITICAL CONNECTION ERROR: {e}")
49
+ # We don't exit here so the web server keeps running to show logs
50
 
51
  yield
52
 
53
  print("πŸ›‘ Stopping Worker...")
54
  try:
55
+ if client.is_connected:
56
+ await client.stop()
57
  except:
58
  pass
59
 
 
67
  async def yield_file(self, file_id, offset, first_part_cut, last_part_cut, part_count, chunk_size):
68
  client = self.client
69
 
70
+ # Safe Session Getting
71
+ try:
72
+ ms = client.media_sessions.get(file_id.dc_id)
73
+ if not ms:
74
+ if file_id.dc_id != await client.storage.dc_id():
75
+ auth_key = await Auth(client, file_id.dc_id, await client.storage.test_mode()).create()
76
+ ms = Session(client, file_id.dc_id, auth_key, await client.storage.test_mode(), is_media=True)
77
+ await ms.start()
78
+ else:
79
+ ms = client.session
80
+ client.media_sessions[file_id.dc_id] = ms
81
+ except Exception as e:
82
+ print(f"Session Error: {e}")
83
+ return
84
+
85
  loc = raw.types.InputDocumentFileLocation(
86
  id=file_id.media_id,
87
  access_hash=file_id.access_hash,
 
100
  chunk = r.bytes
101
  if not chunk: break
102
 
103
+ if part_count == 1: yield chunk[first_part_cut:last_part_cut]
104
+ elif curr == 1: yield chunk[first_part_cut:]
105
+ elif curr == part_count: yield chunk[:last_part_cut]
106
+ else: yield chunk
 
 
 
 
107
 
108
  curr += 1
109
  offset += chunk_size
 
114
 
115
  @app.get("/stream/{message_id}/{filename}")
116
  async def stream_handler(req: Request, message_id: int, filename: str):
117
+ if not client.is_connected:
118
+ # Try to reconnect if startup failed
119
+ try: await client.start()
120
+ except: raise HTTPException(500, "Bot failed to connect to Telegram.")
121
+
122
  try:
123
  msg = await client.get_messages(STORAGE_CHANNEL, message_id)
124
  media = msg.document or msg.video or msg.audio
125
 
126
+ if not media: raise HTTPException(404, "File not found")
 
127
 
128
  file_id = FileId.decode(media.file_id)
129
  file_size = media.file_size
 
153
  "Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}",
154
  "Content-Length": str(req_len),
155
  }
 
156
  return StreamingResponse(body, status_code=206 if range_header else 200, headers=headers)
157
 
158
  except Exception as e: