neop3 commited on
Commit
f00bd22
Β·
verified Β·
1 Parent(s): abcb0b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -253
app.py CHANGED
@@ -1,277 +1,59 @@
1
- # ═══════════════════════════════════════════════
2
- # STEP 0: Health check Γ–NCE başlasΔ±n
3
- # ═══════════════════════════════════════════════
4
  from http.server import HTTPServer, BaseHTTPRequestHandler
5
  import threading
6
  import logging
7
  import time
8
 
9
- logging.basicConfig(
10
- format="%(asctime)s - %(levelname)s - %(message)s",
11
- level=logging.INFO,
12
- )
13
  logger = logging.getLogger(__name__)
14
 
15
- class HealthHandler(BaseHTTPRequestHandler):
16
  def do_GET(self):
17
  self.send_response(200)
18
- self.send_header("Content-Type", "text/plain")
19
  self.end_headers()
20
  self.wfile.write(b"OK")
21
- def do_HEAD(self):
22
- self.send_response(200)
23
- self.end_headers()
24
- def log_message(self, *args):
25
- pass
26
-
27
- def _run_health():
28
- s = HTTPServer(("0.0.0.0", 7860), HealthHandler)
29
- s.serve_forever()
30
 
31
- # HEMEN başlat - başka hiçbir şeyden ânce
32
- _t = threading.Thread(target=_run_health, daemon=True)
33
- _t.start()
34
  time.sleep(0.5)
35
- logger.info("βœ… Health check server ready on 7860")
36
-
37
- # ═══════════════════════════════════════════════
38
- # STEP 1: Monkeypatch
39
- # ═══════════════════════════════════════════════
40
- import collections
41
- import collections.abc
42
- if not hasattr(collections, "Iterable"):
43
- collections.Iterable = collections.abc.Iterable
44
-
45
- # ═══════════════════════════════════════════════
46
- # STEP 2: Imports
47
- # ═══════════════════════════════════════════════
48
- import os
49
- import sys
50
- import tempfile
51
- import asyncio
52
- import traceback
53
- from datetime import datetime, timedelta
54
 
 
55
  try:
 
 
 
 
 
 
 
56
  from pySmartDL import SmartDL
 
 
 
57
  from pydrive2.auth import GoogleAuth
58
  from pydrive2.drive import GoogleDrive
59
- from oauth2client.service_account import ServiceAccountCredentials
60
- from telegram import Update
61
- from telegram.ext import (
62
- ApplicationBuilder,
63
- CommandHandler,
64
- MessageHandler,
65
- filters,
66
- ContextTypes,
67
- )
68
- from apscheduler.schedulers.asyncio import AsyncIOScheduler
69
- logger.info("βœ… All imports OK")
70
- except Exception as e:
71
- logger.error(f"❌ Import failed: {e}")
72
- traceback.print_exc()
73
- # Γ–lme, health check Γ§alışmaya devam etsin
74
- while True:
75
- time.sleep(3600)
76
-
77
- # ═══════════════════════════════════════════════
78
- # STEP 3: Config
79
- # ═══════════════════════════════════════════════
80
- BOT_TOKEN = os.getenv("BOT_TOKEN")
81
- GDRIVE_SERVICE_ACCOUNT_JSON = os.getenv("GDRIVE_SERVICE_ACCOUNT_JSON")
82
- GDRIVE_FOLDER_ID = os.getenv("GDRIVE_FOLDER_ID")
83
- AUTHORIZED_USER_ID = os.getenv("AUTHORIZED_USER_ID")
84
-
85
- if AUTHORIZED_USER_ID:
86
- try:
87
- AUTHORIZED_USER_ID = int(AUTHORIZED_USER_ID)
88
- except ValueError:
89
- AUTHORIZED_USER_ID = None
90
-
91
- logger.info(f"BOT_TOKEN exists: {bool(BOT_TOKEN)}")
92
- logger.info(f"GDRIVE_JSON exists: {bool(GDRIVE_SERVICE_ACCOUNT_JSON)}")
93
- logger.info(f"FOLDER_ID exists: {bool(GDRIVE_FOLDER_ID)}")
94
- logger.info(f"AUTH_USER: {AUTHORIZED_USER_ID}")
95
-
96
- if not BOT_TOKEN:
97
- logger.error("❌ BOT_TOKEN missing!")
98
- while True:
99
- time.sleep(3600)
100
-
101
- # ═══════════════════════════════════════════════
102
- # STEP 4: Google Drive
103
- # ═══════════════════════════════════════════════
104
- drive_client = None
105
-
106
- def get_drive():
107
- global drive_client
108
- if not GDRIVE_SERVICE_ACCOUNT_JSON:
109
- logger.warning("No GDRIVE_SERVICE_ACCOUNT_JSON")
110
- return None
111
- try:
112
- with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".json") as f:
113
- f.write(GDRIVE_SERVICE_ACCOUNT_JSON)
114
- path = f.name
115
- gauth = GoogleAuth()
116
- gauth.auth_method = "service"
117
- gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
118
- path, ["https://www.googleapis.com/auth/drive"]
119
- )
120
- drive_client = GoogleDrive(gauth)
121
- os.unlink(path)
122
- logger.info("βœ… Google Drive OK")
123
- return drive_client
124
- except Exception as e:
125
- logger.error(f"Drive auth error: {e}")
126
- return None
127
-
128
- get_drive()
129
-
130
- # ═══════════════════════════════════════════════
131
- # STEP 5: Helpers
132
- # ═══════════════════════════════════════════════
133
- def do_download(url, dest_dir):
134
- os.makedirs(dest_dir, exist_ok=True)
135
- obj = SmartDL(url, dest_dir, progress_bar=False, timeout=120)
136
- obj.start()
137
- return obj
138
-
139
- def do_upload(filepath, filename):
140
- global drive_client
141
- if not drive_client:
142
- get_drive()
143
- if not drive_client:
144
- raise RuntimeError("No Drive client")
145
- meta = {"title": filename}
146
- if GDRIVE_FOLDER_ID:
147
- meta["parents"] = [{"id": GDRIVE_FOLDER_ID}]
148
- gf = drive_client.CreateFile(meta)
149
- gf.SetContentFile(filepath)
150
- gf.Upload()
151
- return gf
152
-
153
- async def auto_delete(file_id):
154
- try:
155
- global drive_client
156
- if not drive_client:
157
- await asyncio.to_thread(get_drive)
158
- if drive_client:
159
- gf = await asyncio.to_thread(drive_client.CreateFile, {"id": file_id})
160
- await asyncio.to_thread(gf.Delete)
161
- logger.info(f"πŸ—‘ Deleted {file_id}")
162
- except Exception as e:
163
- logger.error(f"Delete error: {e}")
164
 
165
- # ═══════════════════════════════════════════════
166
- # STEP 6: Bot Handlers
167
- # ═══════════════════════════════════════════════
168
- lock = None
169
- sched = None
170
-
171
- async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
172
- if AUTHORIZED_USER_ID and update.effective_user.id != AUTHORIZED_USER_ID:
173
- return
174
- await update.message.reply_text("Merhaba! Link gΓΆnder, Drive'a yΓΌkleyeyim. πŸš€")
175
-
176
- async def on_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
177
- global lock, sched
178
-
179
- if AUTHORIZED_USER_ID and update.effective_user.id != AUTHORIZED_USER_ID:
180
- return
181
-
182
- url = update.message.text.strip()
183
- if not url.startswith(("http://", "https://")):
184
- await update.message.reply_text("β›” GeΓ§ersiz link.")
185
- return
186
-
187
- async with lock:
188
- msg = await update.message.reply_text("⏳ Başlıyor...")
189
- fp = None
190
- try:
191
- dest = os.path.join(os.getcwd(), "downloads")
192
- await msg.edit_text("πŸ“₯ Δ°ndiriliyor...")
193
- obj = await asyncio.to_thread(do_download, url, dest)
194
-
195
- if not obj.isSuccessful():
196
- await msg.edit_text("❌ İndirme başarısız.")
197
- return
198
-
199
- fp = obj.get_dest()
200
- fn = os.path.basename(fp)
201
- sz = os.path.getsize(fp)
202
-
203
- if sz > 5 * 1024**3:
204
- await msg.edit_text(f"⚠️ Γ‡ok bΓΌyΓΌk: {sz/1024**3:.1f}GB. Max 5GB.")
205
- os.remove(fp); fp = None
206
- return
207
-
208
- size_str = f"{sz/1024**2:.1f} MB" if sz > 1024**2 else f"{sz/1024:.1f} KB"
209
- await msg.edit_text(f"βœ… Δ°ndirildi: `{fn}` ({size_str})\nπŸ“€ YΓΌkleniyor...", parse_mode="Markdown")
210
-
211
- gf = await asyncio.to_thread(do_upload, fp, fn)
212
- fid = gf["id"]
213
- link = gf.get("alternateLink", f"https://drive.google.com/file/d/{fid}/view")
214
-
215
- await msg.edit_text(
216
- f"πŸš€ Tamam!\nπŸ“ `{fn}`\nπŸ“¦ {size_str}\nπŸ”— {link}\n⏱ 2 saat sonra silinecek.",
217
- parse_mode="Markdown",
218
- )
219
-
220
- if fp and os.path.exists(fp):
221
- os.remove(fp); fp = None
222
-
223
- sched.add_job(auto_delete, "date",
224
- run_date=datetime.now() + timedelta(hours=2),
225
- args=[fid])
226
-
227
- except Exception as e:
228
- logger.error(f"Error: {e}", exc_info=True)
229
- try:
230
- await msg.edit_text(f"❌ Hata: `{e}`", parse_mode="Markdown")
231
- except:
232
- pass
233
- finally:
234
- if fp and os.path.exists(fp):
235
- try: os.remove(fp)
236
- except: pass
237
-
238
- # ═══════════════════════════════════════════════
239
- # STEP 7: Main
240
- # ═══════════════════════════════════════════════
241
- def main():
242
- global lock, sched
243
-
244
- app = (
245
- ApplicationBuilder()
246
- .token(BOT_TOKEN)
247
- .connect_timeout(30)
248
- .read_timeout(30)
249
- .write_timeout(30)
250
- .build()
251
- )
252
 
253
- app.add_handler(CommandHandler("start", cmd_start))
254
- app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_message))
 
 
255
 
256
- async def post_init(_):
257
- global lock, sched
258
- lock = asyncio.Lock()
259
- sched = AsyncIOScheduler()
260
- sched.start()
261
- logger.info("βœ… Bot fully ready")
262
 
263
- app.post_init = post_init
264
 
265
- logger.info("πŸ€– Polling starting...")
266
- app.run_polling(
267
- allowed_updates=Update.ALL_TYPES,
268
- drop_pending_updates=True,
269
- )
270
 
271
- if __name__ == "__main__":
272
- try:
273
- main()
274
- except Exception as e:
275
- logger.error(f"πŸ’€ Fatal: {e}", exc_info=True)
276
- while True:
277
- time.sleep(3600)
 
 
 
 
1
  from http.server import HTTPServer, BaseHTTPRequestHandler
2
  import threading
3
  import logging
4
  import time
5
 
6
+ logging.basicConfig(level=logging.INFO)
 
 
 
7
  logger = logging.getLogger(__name__)
8
 
9
+ class H(BaseHTTPRequestHandler):
10
  def do_GET(self):
11
  self.send_response(200)
 
12
  self.end_headers()
13
  self.wfile.write(b"OK")
14
+ def log_message(self, *a): pass
 
 
 
 
 
 
 
 
15
 
16
+ threading.Thread(target=lambda: HTTPServer(("0.0.0.0", 7860), H).serve_forever(), daemon=True).start()
 
 
17
  time.sleep(0.5)
18
+ logger.info("HEALTH OK")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # === TEST: Import'larΔ± tek tek dene ===
21
  try:
22
+ logger.info("importing collections...")
23
+ import collections, collections.abc
24
+ if not hasattr(collections, "Iterable"):
25
+ collections.Iterable = collections.abc.Iterable
26
+ logger.info("OK collections")
27
+
28
+ logger.info("importing pySmartDL...")
29
  from pySmartDL import SmartDL
30
+ logger.info("OK pySmartDL")
31
+
32
+ logger.info("importing pydrive2...")
33
  from pydrive2.auth import GoogleAuth
34
  from pydrive2.drive import GoogleDrive
35
+ logger.info("OK pydrive2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ logger.info("importing oauth2client...")
38
+ from oauth2client.service_account import ServiceAccountCredentials
39
+ logger.info("OK oauth2client")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ logger.info("importing telegram...")
42
+ from telegram import Update
43
+ from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
44
+ logger.info("OK telegram")
45
 
46
+ logger.info("importing apscheduler...")
47
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
48
+ logger.info("OK apscheduler")
 
 
 
49
 
50
+ logger.info("βœ… ALL IMPORTS DONE")
51
 
52
+ except Exception as e:
53
+ logger.error(f"❌ IMPORT FAILED: {e}")
54
+ import traceback
55
+ traceback.print_exc()
 
56
 
57
+ # Γ–lme, health check yaşasΔ±n
58
+ while True:
59
+ time.sleep(3600)