Cxops commited on
Commit
4c0e136
·
verified ·
1 Parent(s): d042035

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -150
app.py CHANGED
@@ -1,200 +1,250 @@
1
  import os
2
- import uuid
3
- import logging
4
- from contextlib import asynccontextmanager
5
- from pathlib import Path
6
-
7
- import aiohttp
8
- from fastapi import FastAPI, Request, Response
9
- import uvicorn
10
  from pyrogram import Client, filters
11
- from pyrogram.types import (
12
- InlineKeyboardMarkup,
13
- InlineKeyboardButton,
14
- CallbackQuery,
15
- Message,
16
- Update,
17
- )
18
  from huggingface_hub import HfApi, hf_hub_download
19
 
20
- # ---------- CONFIG ----------
21
- TOKEN = os.environ["BOT_TOKEN"]
22
- HF_TOKEN = os.environ["HF_TOKEN"]
 
23
  API_ID = int(os.environ["API_ID"])
24
  API_HASH = os.environ["API_HASH"]
25
- DATASET_REPO = "Cxops/Bzxv"
26
- WEBHOOK_URL = "https://Cxops-Push.hf.space"
27
- WEBHOOK_PATH = f"/{TOKEN}"
28
 
29
- TEMP_DIR = Path("/tmp/telegram_bot_files")
30
- TEMP_DIR.mkdir(exist_ok=True)
31
 
32
- hf_api = HfApi(token=HF_TOKEN)
 
 
33
 
34
- # ---------- LOGGING ----------
35
- logging.basicConfig(level=logging.INFO)
36
- logger = logging.getLogger(__name__)
37
 
38
- # ---------- PYROGRAM CLIENT ----------
39
- app = Client(
40
- name="my_bot",
41
- api_id=API_ID,
42
- api_hash=API_HASH,
43
- bot_token=TOKEN,
44
- workdir="/tmp",
45
- sleep_threshold=0,
46
- )
47
 
 
 
48
 
49
- # ---------- LIFESPAN (manual webhook via aiohttp) ----------
50
- @asynccontextmanager
51
- async def lifespan(fastapi_app: FastAPI):
52
- # Start Pyrogram client (required for dispatcher)
53
- await app.start()
54
- logger.info("Pyrogram client started")
55
 
56
- # Set webhook using Telegram Bot API directly
57
- webhook_url = f"{WEBHOOK_URL}{WEBHOOK_PATH}"
58
- async with aiohttp.ClientSession() as session:
59
- async with session.get(
60
- f"https://api.telegram.org/bot{TOKEN}/setWebhook",
61
- params={"url": webhook_url},
62
- ) as resp:
63
- data = await resp.json()
64
- logger.info(f"Webhook set: {data}")
65
 
66
- yield
 
 
67
 
68
- # Clean shutdown
69
- async with aiohttp.ClientSession() as session:
70
- async with session.get(
71
- f"https://api.telegram.org/bot{TOKEN}/deleteWebhook"
72
- ) as resp:
73
- logger.info("Webhook deleted")
74
- await app.stop()
75
 
 
 
 
76
 
77
- fastapi_app = FastAPI(lifespan=lifespan)
 
 
 
 
 
 
 
78
 
 
 
 
79
 
80
- # ---------- BOT HANDLERS ----------
81
  @app.on_message(filters.command("start"))
82
- async def start_command(client: Client, message: Message):
83
  await message.reply_text(
84
- "Send me any file and I'll store it in your personal dataset folder.\n"
85
- "Use /files to see your uploaded files and download them again."
86
- )
87
-
88
-
89
- @app.on_message(filters.document | filters.photo)
90
- async def handle_file(client: Client, message: Message):
91
- user_id = message.from_user.id
92
- file = message.document or (message.photo[-1] if message.photo else None)
93
- if not file:
94
- await message.reply_text("Please send a file or photo.")
95
- return
96
-
97
- original_name = getattr(file, "file_name", None) or f"{file.file_unique_id}.file"
98
- local_path = TEMP_DIR / f"{uuid.uuid4()}_{original_name}"
99
- await message.download(file_id=file.file_id, file_name=str(local_path))
100
-
101
- remote_path = f"user_{user_id}/{local_path.name}"
102
- logger.info(f"Uploading {local_path} to {DATASET_REPO}/{remote_path}")
103
- hf_api.upload_file(
104
- path_or_fileobj=str(local_path),
105
- path_in_repo=remote_path,
106
- repo_id=DATASET_REPO,
107
- repo_type="dataset",
108
  )
109
 
110
- os.remove(local_path)
111
- await message.reply_text(
112
- f"✅ File saved as `{original_name}`\nUse /files to list your uploads."
113
- )
114
-
115
-
116
  @app.on_message(filters.command("files"))
117
- async def list_files(client: Client, message: Message):
118
- user_id = message.from_user.id
119
- folder = f"user_{user_id}"
120
 
121
  try:
122
- repo_tree = hf_api.list_repo_tree(DATASET_REPO, path=folder, repo_type="dataset")
123
- file_paths = [f.path for f in repo_tree if f.type != "directory"]
124
- except Exception as e:
125
- logger.error(f"list_repo_tree failed: {e}")
126
- file_paths = []
127
-
128
- if not file_paths:
129
- await message.reply_text("You haven't uploaded any files yet.")
130
- return
131
 
132
- keyboard = []
133
- for path in file_paths:
134
- display_name = path.rsplit("/", 1)[-1]
135
- keyboard.append([InlineKeyboardButton(display_name, callback_data=path)])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- await message.reply_text(
138
- "📁 Your uploaded files (tap to download):",
139
- reply_markup=InlineKeyboardMarkup(keyboard),
140
- )
141
 
 
 
 
142
 
143
- @app.on_callback_query()
144
- async def download_file_callback(client: Client, callback_query: CallbackQuery):
145
- user_id = callback_query.from_user.id
146
- file_path = callback_query.data
147
 
148
- if not file_path.startswith(f"user_{user_id}/"):
149
- await callback_query.answer("⛔ You can only download your own files.", show_alert=True)
150
- return
151
 
152
- await callback_query.answer("Downloading...")
153
- real_path = None
154
  try:
155
- downloaded_path = hf_hub_download(
 
 
 
 
156
  repo_id=DATASET_REPO,
157
- filename=file_path,
158
  repo_type="dataset",
 
159
  token=HF_TOKEN,
160
- local_dir=TEMP_DIR,
161
- local_dir_use_symlinks=False,
162
  )
163
- real_path = Path(downloaded_path)
164
 
165
- await client.send_document(
166
- chat_id=user_id,
167
- document=str(real_path),
168
- file_name=real_path.name,
169
  )
 
 
 
 
 
 
170
  except Exception as e:
171
- logger.error(f"Download failed: {e}")
172
- await callback_query.edit_message_text("❌ Failed to download the file. It may have been removed.")
173
- return
 
174
  finally:
175
- if real_path and real_path.exists():
176
- os.remove(real_path)
 
 
 
177
 
178
- await callback_query.edit_message_text(f"📥 Sent: {real_path.name}")
 
 
 
 
 
 
179
 
 
180
 
181
- # ---------- WEBHOOK ENDPOINT ----------
182
- @fastapi_app.post(WEBHOOK_PATH)
183
- async def telegram_webhook(request: Request):
184
  try:
185
- data = await request.json()
186
- update_obj = Update(**data)
187
- await app.dispatcher.process_update(update_obj)
188
- except Exception as e:
189
- logger.error(f"Error processing update: {e}")
190
- return Response(status_code=200)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
 
 
 
 
 
 
 
192
 
193
- @fastapi_app.get("/health")
194
- async def health():
195
- return {"status": "ok"}
 
 
 
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
- # ---------- MAIN ----------
199
  if __name__ == "__main__":
200
- uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import tempfile
3
+ import shutil
4
+ import threading
5
+
6
+ from flask import Flask
7
+
 
 
8
  from pyrogram import Client, filters
9
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
10
+
 
 
 
 
 
11
  from huggingface_hub import HfApi, hf_hub_download
12
 
13
+ # =========================
14
+ # CONFIG
15
+ # =========================
16
+
17
  API_ID = int(os.environ["API_ID"])
18
  API_HASH = os.environ["API_HASH"]
19
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
20
+ HF_TOKEN = os.environ["HF_TOKEN"]
 
21
 
22
+ DATASET_REPO = "Cxops/Bzxv"
 
23
 
24
+ # =========================
25
+ # FLASK HEALTH SERVER
26
+ # =========================
27
 
28
+ web = Flask(__name__)
 
 
29
 
30
+ @web.route("/")
31
+ def home():
32
+ return "Telegram HF Storage Bot Running"
 
 
 
 
 
 
33
 
34
+ def run_web():
35
+ web.run(host="0.0.0.0", port=7860)
36
 
37
+ # =========================
38
+ # HUGGINGFACE
39
+ # =========================
 
 
 
40
 
41
+ hf = HfApi(token=HF_TOKEN)
 
 
 
 
 
 
 
 
42
 
43
+ # =========================
44
+ # PYROGRAM
45
+ # =========================
46
 
47
+ app = Client(
48
+ "storage_bot",
49
+ api_id=API_ID,
50
+ api_hash=API_HASH,
51
+ bot_token=BOT_TOKEN
52
+ )
 
53
 
54
+ # =========================
55
+ # HELPERS
56
+ # =========================
57
 
58
+ def cleanup(path):
59
+ try:
60
+ if os.path.isdir(path):
61
+ shutil.rmtree(path, ignore_errors=True)
62
+ elif os.path.isfile(path):
63
+ os.remove(path)
64
+ except Exception:
65
+ pass
66
 
67
+ # =========================
68
+ # COMMANDS
69
+ # =========================
70
 
 
71
  @app.on_message(filters.command("start"))
72
+ async def start(_, message):
73
  await message.reply_text(
74
+ "Send me a file.\n\n"
75
+ "/files - List uploaded files"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  )
77
 
 
 
 
 
 
 
78
  @app.on_message(filters.command("files"))
79
+ async def files(_, message):
80
+ user_id = str(message.from_user.id)
 
81
 
82
  try:
83
+ repo_files = hf.list_repo_files(
84
+ repo_id=DATASET_REPO,
85
+ repo_type="dataset"
86
+ )
 
 
 
 
 
87
 
88
+ user_files = [
89
+ f for f in repo_files
90
+ if f.startswith(f"{user_id}/")
91
+ ]
92
+
93
+ if not user_files:
94
+ return await message.reply_text(
95
+ "You have no uploaded files."
96
+ )
97
+
98
+ buttons = []
99
+
100
+ for path in user_files:
101
+ filename = os.path.basename(path)
102
+
103
+ buttons.append(
104
+ [
105
+ InlineKeyboardButton(
106
+ filename[:60],
107
+ callback_data=f"get:{path}"
108
+ )
109
+ ]
110
+ )
111
+
112
+ await message.reply_text(
113
+ "Your uploaded files:",
114
+ reply_markup=InlineKeyboardMarkup(buttons)
115
+ )
116
 
117
+ except Exception as e:
118
+ await message.reply_text(f"Error:\n{e}")
 
 
119
 
120
+ # =========================
121
+ # DOWNLOAD FROM HF
122
+ # =========================
123
 
124
+ @app.on_callback_query(filters.regex("^get:"))
125
+ async def get_file(_, query):
126
+ path = query.data.replace("get:", "")
 
127
 
128
+ temp_dir = tempfile.mkdtemp()
 
 
129
 
 
 
130
  try:
131
+ await query.message.edit_text(
132
+ "Downloading from dataset..."
133
+ )
134
+
135
+ local_file = hf_hub_download(
136
  repo_id=DATASET_REPO,
 
137
  repo_type="dataset",
138
+ filename=path,
139
  token=HF_TOKEN,
140
+ local_dir=temp_dir
 
141
  )
 
142
 
143
+ await query.message.reply_document(
144
+ local_file,
145
+ caption=os.path.basename(path)
 
146
  )
147
+
148
+ try:
149
+ await query.message.delete()
150
+ except Exception:
151
+ pass
152
+
153
  except Exception as e:
154
+ await query.message.reply_text(
155
+ f"Error:\n{e}"
156
+ )
157
+
158
  finally:
159
+ cleanup(temp_dir)
160
+
161
+ # =========================
162
+ # RECEIVE FILES
163
+ # =========================
164
 
165
+ @app.on_message(
166
+ filters.document |
167
+ filters.video |
168
+ filters.audio |
169
+ filters.photo
170
+ )
171
+ async def upload_file(_, message):
172
 
173
+ temp_dir = tempfile.mkdtemp()
174
 
 
 
 
175
  try:
176
+ status = await message.reply_text(
177
+ "Downloading file..."
178
+ )
179
+
180
+ if message.document:
181
+ media = message.document
182
+ filename = media.file_name
183
+
184
+ elif message.video:
185
+ media = message.video
186
+ filename = (
187
+ media.file_name
188
+ or f"{media.file_unique_id}.mp4"
189
+ )
190
+
191
+ elif message.audio:
192
+ media = message.audio
193
+ filename = (
194
+ media.file_name
195
+ or f"{media.file_unique_id}.mp3"
196
+ )
197
+
198
+ else:
199
+ media = message.photo[-1]
200
+ filename = f"{media.file_unique_id}.jpg"
201
+
202
+ local_path = await message.download(
203
+ file_name=os.path.join(
204
+ temp_dir,
205
+ filename
206
+ )
207
+ )
208
 
209
+ await status.edit_text(
210
+ "Uploading to Hugging Face..."
211
+ )
212
+
213
+ repo_path = (
214
+ f"{message.from_user.id}/{filename}"
215
+ )
216
 
217
+ hf.upload_file(
218
+ path_or_fileobj=local_path,
219
+ path_in_repo=repo_path,
220
+ repo_id=DATASET_REPO,
221
+ repo_type="dataset"
222
+ )
223
 
224
+ await status.edit_text(
225
+ f"Uploaded successfully.\n\n{filename}"
226
+ )
227
+
228
+ except Exception as e:
229
+ await message.reply_text(
230
+ f"Upload failed:\n{e}"
231
+ )
232
+
233
+ finally:
234
+ cleanup(temp_dir)
235
+
236
+ # =========================
237
+ # MAIN
238
+ # =========================
239
 
 
240
  if __name__ == "__main__":
241
+ print("Starting Flask health server...")
242
+
243
+ threading.Thread(
244
+ target=run_web,
245
+ daemon=True
246
+ ).start()
247
+
248
+ print("Starting Telegram bot...")
249
+
250
+ app.run()