ulduldp commited on
Commit
7f1908c
Β·
verified Β·
1 Parent(s): 7c94ab6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -157
app.py CHANGED
@@ -1,125 +1,86 @@
 
 
 
 
 
 
1
  import json
2
- import os
3
  import time
4
  from datetime import datetime
5
- from telegram import (
6
- Update,
7
- InputFile,
8
- InlineKeyboardButton,
9
- InlineKeyboardMarkup
10
- )
11
  from telegram.ext import (
12
  ApplicationBuilder,
13
  MessageHandler,
14
  CommandHandler,
15
- CallbackQueryHandler,
16
  ContextTypes,
17
  filters
18
  )
19
 
20
- BOT_TOKEN = "6740023413:AAHZ5iEiXjkY7IGwljg37llFbekKLbIVkkw"
21
-
22
- # πŸ”΄ HARD CODED VALUES
23
- GROUP_ID = -1003799294466
24
-
25
 
26
  waiting_for_file = set()
27
 
28
 
29
- # πŸ“ JSON file name = userID.json
30
- def get_json_file(user_id):
31
- return f"{user_id}.json"
 
 
 
 
32
 
33
 
34
- # πŸ“₯ LOAD JSON (safe)
35
- def load_data(user_id):
36
- file = get_json_file(user_id)
37
 
38
- if os.path.exists(file):
39
- try:
40
- with open(file, "r") as f:
41
- data = json.load(f)
42
 
43
- if "files" not in data or not isinstance(data["files"], list):
44
- return {"files": []}
45
 
46
- return data
47
- except:
48
- return {"files": []}
49
-
50
- return {"files": []}
51
 
 
 
52
 
53
- # πŸ’Ύ SAVE JSON
54
- def save_data(user_id, data):
55
- with open(get_json_file(user_id), "w") as f:
56
- json.dump(data, f, indent=4)
57
 
58
 
59
- # πŸš€ START UI
60
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
61
- keyboard = [
62
- [InlineKeyboardButton("πŸ“€ Upload", callback_data="upload")],
63
- [InlineKeyboardButton("πŸ“‚ My Files", callback_data="files")],
64
- [InlineKeyboardButton("πŸ“Š Stats", callback_data="stats")]
65
- ]
66
 
67
- await update.message.reply_text(
68
- "πŸš€ Cloud Storage Bot",
69
- reply_markup=InlineKeyboardMarkup(keyboard)
 
 
70
  )
71
 
72
 
73
- # πŸ”˜ BUTTON HANDLER
74
- async def buttons(update: Update, context: ContextTypes.DEFAULT_TYPE):
75
- query = update.callback_query
76
- await query.answer()
77
-
78
- user_id = query.from_user.id
79
-
80
- if query.data == "upload":
81
- waiting_for_file.add(user_id)
82
- await query.message.reply_text("πŸ“ Send file(s)...")
83
-
84
- elif query.data == "files":
85
- data = load_data(user_id)
86
-
87
- if not data["files"]:
88
- await query.message.reply_text("❌ No files found")
89
- return
90
-
91
- msg = "πŸ“‚ Your Files:\n\n"
92
- for f in data["files"][-10:]:
93
- msg += f"β€’ {f['file_name']}\n"
94
-
95
- await query.message.reply_text(msg)
96
-
97
- elif query.data == "stats":
98
- data = load_data(user_id)
99
- await query.message.reply_text(f"πŸ“Š Total files: {len(data['files'])}")
100
-
101
-
102
  # 🟒 /save
103
  async def save_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
104
  waiting_for_file.add(update.effective_user.id)
105
  await update.message.reply_text("πŸ“ Send file to save")
106
 
107
 
108
- # πŸ“€ FILE HANDLER (MAIN LOGIC)
109
  async def handle_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
110
- user = update.effective_user
111
- user_id = user.id
112
 
113
  if user_id not in waiting_for_file:
114
  return
115
 
116
- document = update.message.document
117
- if not document:
118
  return
119
 
120
  try:
121
- # file info
122
- original_name = document.file_name
123
  ext = original_name.split('.')[-1] if '.' in original_name else "dat"
124
 
125
  timestamp = int(time.time())
@@ -130,56 +91,48 @@ async def handle_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
130
  # βœ… STEP 1: send file FIRST
131
  sent = await context.bot.send_document(
132
  chat_id=GROUP_ID,
133
- document=document.file_id,
134
  filename=new_name
135
  )
136
 
137
- # βœ… STEP 2: JSON update
138
- data = load_data(user_id)
139
 
140
  entry = {
141
  "file_name": new_name,
142
  "original_name": original_name,
143
  "file_id": sent.document.file_id,
144
- "file_size": document.file_size,
145
  "upload_date": upload_date,
146
  "timestamp": timestamp
147
  }
148
 
149
  data["files"].append(entry)
150
- save_data(user_id, data)
151
 
152
- # βœ… STEP 3: send JSON with correct filename
153
- await context.bot.send_document(
154
- chat_id=GROUP_ID,
155
- document=InputFile(
156
- get_json_file(user_id),
157
- filename=f"{user_id}.json"
158
- ),
159
- caption=f"πŸ“ Index of {user_id}"
160
- )
161
 
162
- await update.message.reply_text("βœ… File saved successfully!")
163
 
164
  except Exception as e:
165
- print("ERROR:", e)
166
  await update.message.reply_text(f"❌ Error: {e}")
167
 
168
  waiting_for_file.discard(user_id)
169
 
170
 
171
- # πŸ“‹ /myfiles
172
  async def myfiles(update: Update, context: ContextTypes.DEFAULT_TYPE):
173
  user_id = update.effective_user.id
174
- data = load_data(user_id)
175
 
176
  if not data["files"]:
177
- await update.message.reply_text("❌ No files found")
178
  return
179
 
180
- msg = "πŸ“‚ Your Files:\n\n"
181
  for f in data["files"]:
182
- msg += f"β€’ {f['file_name']} ({f['upload_date']})\n"
183
 
184
  await update.message.reply_text(msg)
185
 
@@ -187,7 +140,7 @@ async def myfiles(update: Update, context: ContextTypes.DEFAULT_TYPE):
187
  # πŸ“₯ /get
188
  async def get_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
189
  user_id = update.effective_user.id
190
- data = load_data(user_id)
191
 
192
  if not context.args:
193
  await update.message.reply_text("Usage: /get filename")
@@ -203,60 +156,13 @@ async def get_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
203
  )
204
  return
205
 
206
- await update.message.reply_text("❌ File not found")
207
-
208
-
209
- # πŸ—‘οΈ /delete
210
- async def delete_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
211
- user_id = update.effective_user.id
212
- data = load_data(user_id)
213
-
214
- if not context.args:
215
- await update.message.reply_text("Usage: /delete filename")
216
- return
217
-
218
- filename = context.args[0]
219
-
220
- new_files = [f for f in data["files"] if f["file_name"] != filename]
221
-
222
- if len(new_files) == len(data["files"]):
223
- await update.message.reply_text("❌ File not found")
224
- return
225
-
226
- data["files"] = new_files
227
- save_data(user_id, data)
228
-
229
- await update.message.reply_text("πŸ—‘οΈ File deleted")
230
-
231
-
232
- # πŸ”Ž /search
233
- async def search(update: Update, context: ContextTypes.DEFAULT_TYPE):
234
- user_id = update.effective_user.id
235
- data = load_data(user_id)
236
-
237
- if not context.args:
238
- await update.message.reply_text("Usage: /search keyword")
239
- return
240
-
241
- keyword = context.args[0].lower()
242
-
243
- results = [f for f in data["files"] if keyword in f["file_name"].lower()]
244
-
245
- if not results:
246
- await update.message.reply_text("❌ No results")
247
- return
248
-
249
- msg = "πŸ”Ž Results:\n\n"
250
- for f in results:
251
- msg += f"β€’ {f['file_name']}\n"
252
-
253
- await update.message.reply_text(msg)
254
 
255
 
256
  # πŸ“Š /stats
257
  async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
258
  user_id = update.effective_user.id
259
- data = load_data(user_id)
260
 
261
  total = len(data["files"])
262
  total_size = sum(f["file_size"] for f in data["files"])
@@ -266,19 +172,15 @@ async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
266
  )
267
 
268
 
269
- # πŸš€ RUN BOT
270
  app = ApplicationBuilder().token(BOT_TOKEN).build()
271
 
272
- app.add_handler(CommandHandler("start", start))
273
  app.add_handler(CommandHandler("save", save_command))
274
  app.add_handler(CommandHandler("myfiles", myfiles))
275
  app.add_handler(CommandHandler("get", get_file))
276
- app.add_handler(CommandHandler("delete", delete_file))
277
- app.add_handler(CommandHandler("search", search))
278
  app.add_handler(CommandHandler("stats", stats))
279
 
280
- app.add_handler(CallbackQueryHandler(buttons))
281
  app.add_handler(MessageHandler(filters.Document.ALL, handle_file))
282
 
283
- print("πŸ”₯ FINAL BOT RUNNING...")
284
  app.run_polling()
 
1
+
2
+ BOT_TOKEN = "6740023413:AAHZ5iEiXjkY7IGwljg37llFbekKLbIVkkw"
3
+
4
+ # πŸ”΄ HARD CODED VALUES
5
+ GROUP_ID = -1003799294466
6
+
7
  import json
 
8
  import time
9
  from datetime import datetime
10
+ from telegram import Update, InputFile
 
 
 
 
 
11
  from telegram.ext import (
12
  ApplicationBuilder,
13
  MessageHandler,
14
  CommandHandler,
 
15
  ContextTypes,
16
  filters
17
  )
18
 
 
 
 
 
 
19
 
20
  waiting_for_file = set()
21
 
22
 
23
+ # πŸ” FIND USER JSON FILE FROM GROUP
24
+ async def find_user_json(context, user_id):
25
+ async for msg in context.bot.get_chat_history(GROUP_ID, limit=100):
26
+ if msg.document:
27
+ if msg.document.file_name == f"{user_id}.json":
28
+ return msg.document.file_id
29
+ return None
30
 
31
 
32
+ # πŸ“₯ LOAD JSON FROM TELEGRAM (NO LOCAL FILE)
33
+ async def load_data(context, user_id):
34
+ file_id = await find_user_json(context, user_id)
35
 
36
+ if not file_id:
37
+ return {"files": []}
 
 
38
 
39
+ file = await context.bot.get_file(file_id)
40
+ content = await file.download_as_bytearray()
41
 
42
+ try:
43
+ data = json.loads(content.decode("utf-8"))
 
 
 
44
 
45
+ if "files" not in data:
46
+ return {"files": []}
47
 
48
+ return data
49
+ except:
50
+ return {"files": []}
 
51
 
52
 
53
+ # πŸ“€ SAVE JSON BACK TO GROUP
54
+ async def save_data(context, user_id, data):
55
+ json_bytes = json.dumps(data, indent=4).encode("utf-8")
 
 
 
 
56
 
57
+ await context.bot.send_document(
58
+ chat_id=GROUP_ID,
59
+ document=json_bytes,
60
+ filename=f"{user_id}.json",
61
+ caption=f"πŸ“ Updated Index {user_id}"
62
  )
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # 🟒 /save
66
  async def save_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
67
  waiting_for_file.add(update.effective_user.id)
68
  await update.message.reply_text("πŸ“ Send file to save")
69
 
70
 
71
+ # πŸ“€ FILE HANDLER
72
  async def handle_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
73
+ user_id = update.effective_user.id
 
74
 
75
  if user_id not in waiting_for_file:
76
  return
77
 
78
+ doc = update.message.document
79
+ if not doc:
80
  return
81
 
82
  try:
83
+ original_name = doc.file_name
 
84
  ext = original_name.split('.')[-1] if '.' in original_name else "dat"
85
 
86
  timestamp = int(time.time())
 
91
  # βœ… STEP 1: send file FIRST
92
  sent = await context.bot.send_document(
93
  chat_id=GROUP_ID,
94
+ document=doc.file_id,
95
  filename=new_name
96
  )
97
 
98
+ # βœ… STEP 2: load JSON from group
99
+ data = await load_data(context, user_id)
100
 
101
  entry = {
102
  "file_name": new_name,
103
  "original_name": original_name,
104
  "file_id": sent.document.file_id,
105
+ "file_size": doc.file_size,
106
  "upload_date": upload_date,
107
  "timestamp": timestamp
108
  }
109
 
110
  data["files"].append(entry)
 
111
 
112
+ # βœ… STEP 3: save JSON BACK to group
113
+ await save_data(context, user_id, data)
 
 
 
 
 
 
 
114
 
115
+ await update.message.reply_text("βœ… File saved (cloud mode ON ☁️)")
116
 
117
  except Exception as e:
118
+ print(e)
119
  await update.message.reply_text(f"❌ Error: {e}")
120
 
121
  waiting_for_file.discard(user_id)
122
 
123
 
124
+ # πŸ“‚ /myfiles
125
  async def myfiles(update: Update, context: ContextTypes.DEFAULT_TYPE):
126
  user_id = update.effective_user.id
127
+ data = await load_data(context, user_id)
128
 
129
  if not data["files"]:
130
+ await update.message.reply_text("❌ No files")
131
  return
132
 
133
+ msg = "πŸ“‚ Files:\n\n"
134
  for f in data["files"]:
135
+ msg += f"β€’ {f['file_name']}\n"
136
 
137
  await update.message.reply_text(msg)
138
 
 
140
  # πŸ“₯ /get
141
  async def get_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
142
  user_id = update.effective_user.id
143
+ data = await load_data(context, user_id)
144
 
145
  if not context.args:
146
  await update.message.reply_text("Usage: /get filename")
 
156
  )
157
  return
158
 
159
+ await update.message.reply_text("❌ Not found")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
 
162
  # πŸ“Š /stats
163
  async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
164
  user_id = update.effective_user.id
165
+ data = await load_data(context, user_id)
166
 
167
  total = len(data["files"])
168
  total_size = sum(f["file_size"] for f in data["files"])
 
172
  )
173
 
174
 
175
+ # πŸš€ RUN
176
  app = ApplicationBuilder().token(BOT_TOKEN).build()
177
 
 
178
  app.add_handler(CommandHandler("save", save_command))
179
  app.add_handler(CommandHandler("myfiles", myfiles))
180
  app.add_handler(CommandHandler("get", get_file))
 
 
181
  app.add_handler(CommandHandler("stats", stats))
182
 
 
183
  app.add_handler(MessageHandler(filters.Document.ALL, handle_file))
184
 
185
+ print("πŸ”₯ CLOUD MODE BOT RUNNING...")
186
  app.run_polling()