gopallikehack commited on
Commit
2f527b0
Β·
verified Β·
1 Parent(s): 029eff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -241
app.py CHANGED
@@ -1,255 +1,43 @@
1
- import os
2
- import json
3
- import sqlite3
4
- import asyncio
5
- from datetime import datetime
6
- from fastapi import FastAPI, Query
7
- from fastapi.responses import JSONResponse
8
- import uvicorn
9
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
10
- from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes
11
  import aiohttp
12
- import threading
13
-
14
- # ========== FASTAPI APP ==========
15
- app = FastAPI(title="Telegram Search API + Bot", developer="Gopal Parmar")
16
-
17
- # ========== BOT CONFIG ==========
18
- BOT_TOKEN = "8902956864:AAH0eFvFemPm9inl5JiMLmu3aZ7ZT6hBFLs"
19
- OWNER_ID = 8501984482
20
- FILE_PATH = "/data/Telegram_70M.json" # Mounted bucket path
21
-
22
- # ========== DATABASE ==========
23
- def init_db():
24
- conn = sqlite3.connect('bot_data.db')
25
- c = conn.cursor()
26
- c.execute('''CREATE TABLE IF NOT EXISTS users (
27
- user_id INTEGER PRIMARY KEY,
28
- username TEXT,
29
- first_name TEXT,
30
- registered_at TIMESTAMP,
31
- last_active TIMESTAMP,
32
- total_searches INTEGER DEFAULT 0,
33
- coins INTEGER DEFAULT 0
34
- )''')
35
- conn.commit()
36
- conn.close()
37
-
38
- def save_user(user_id, username, first_name):
39
- conn = sqlite3.connect('bot_data.db')
40
- c = conn.cursor()
41
- c.execute('INSERT OR IGNORE INTO users (user_id, username, first_name, registered_at, last_active) VALUES (?, ?, ?, ?, ?)',
42
- (user_id, username, first_name, datetime.now(), datetime.now()))
43
- c.execute('UPDATE users SET last_active = ? WHERE user_id = ?', (datetime.now(), user_id))
44
- conn.commit()
45
- conn.close()
46
-
47
- def add_coins(user_id, amount):
48
- conn = sqlite3.connect('bot_data.db')
49
- c = conn.cursor()
50
- c.execute('UPDATE users SET coins = coins + ? WHERE user_id = ?', (amount, user_id))
51
- conn.commit()
52
- conn.close()
53
-
54
- def get_leaderboard(limit=10):
55
- conn = sqlite3.connect('bot_data.db')
56
- c = conn.cursor()
57
- c.execute('SELECT user_id, first_name, coins FROM users ORDER BY coins DESC LIMIT ?', (limit,))
58
- rows = c.fetchall()
59
- conn.close()
60
- return rows
61
-
62
- # ========== EMOJIS ==========
63
- E = {
64
- "premium": "πŸ‘‘πŸ’Ž",
65
- "search": "πŸ”βœ¨",
66
- "coin": "πŸͺ™βœ¨",
67
- "leader": "πŸ†πŸ…",
68
- "refer": "πŸ”—πŸŽ",
69
- "loading": "β³πŸŒ€",
70
- "error": "βŒπŸ’”",
71
- "success": "βœ…πŸŽ‰",
72
- "dev": "πŸ‘¨β€πŸ’»β€οΈ",
73
- "menu": "πŸ“‹πŸ“Œ"
74
- }
75
-
76
- # ========== KEYBOARDS ==========
77
- def main_menu():
78
- keyboard = [
79
- [InlineKeyboardButton(f"{E['search']} Search", callback_data="menu_search")],
80
- [InlineKeyboardButton(f"{E['coin']} Coins", callback_data="menu_coins")],
81
- [InlineKeyboardButton(f"{E['leader']} Leaderboard", callback_data="menu_leader")],
82
- [InlineKeyboardButton(f"{E['refer']} Refer", callback_data="menu_refer")],
83
- [InlineKeyboardButton(f"{E['dev']} About", callback_data="menu_about")]
84
- ]
85
- return InlineKeyboardMarkup(keyboard)
86
-
87
- def search_menu():
88
- keyboard = [
89
- [InlineKeyboardButton("πŸ” By Phone", callback_data="search_phone")],
90
- [InlineKeyboardButton("πŸ‘€ By Username", callback_data="search_username")],
91
- [InlineKeyboardButton("πŸ”™ Back", callback_data="menu_back")]
92
- ]
93
- return InlineKeyboardMarkup(keyboard)
94
-
95
- # ========== API SEARCH ==========
96
- @app.get("/")
97
- async def root():
98
- return {
99
- "message": "πŸ” Telegram 70M Search API + Bot",
100
- "developer": "Gopal Parmar",
101
- "file_exists": os.path.exists(FILE_PATH),
102
- "endpoints": {
103
- "/search?q=79254677980": "Search by phone/username",
104
- "/stats": "Database statistics"
105
- }
106
- }
107
-
108
- @app.get("/stats")
109
- async def stats():
110
- if not os.path.exists(FILE_PATH):
111
- return {"error": "File not mounted", "developer": "Gopal Parmar"}
112
- size_gb = os.path.getsize(FILE_PATH) / (1024**3)
113
- return {"developer": "Gopal Parmar", "file": "Telegram_70M.json", "size_gb": round(size_gb, 2), "status": "ready"}
114
 
115
- @app.get("/search")
116
- async def search(q: str = Query(..., min_length=2), limit: int = 10):
117
- if not os.path.exists(FILE_PATH):
118
- return {"error": "File not mounted", "developer": "Gopal Parmar"}
119
-
120
- results = []
121
- try:
122
- with open(FILE_PATH, 'r', encoding='utf-8', errors='ignore') as f:
123
- for line in f:
124
- if q in line:
125
- try:
126
- results.append(json.loads(line))
127
- except:
128
- results.append({"raw": line.strip()})
129
- if len(results) >= limit:
130
- break
131
- except Exception as e:
132
- return {"error": str(e), "developer": "Gopal Parmar"}
133
-
134
- return {"developer": "Gopal Parmar", "query": q, "count": len(results), "results": results}
135
 
136
- # ========== BOT HANDLERS ==========
137
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
138
- user = update.effective_user
139
- save_user(user.id, user.username, user.first_name)
140
- await update.message.reply_text(
141
- f"{E['premium']} *ULTRA PREMIUM BOT* {E['premium']}\n\n"
142
- f"Welcome {user.first_name}!\n\nπŸ” Search 70M+ users\nπŸ’° Earn coins\n🎁 Refer & earn\nπŸ† Leaderboard\n\nπŸ‘‡ *Select:*",
143
- parse_mode='Markdown',
144
- reply_markup=main_menu()
145
- )
146
 
147
- async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
148
- query = update.callback_query
149
- await query.answer()
150
- data = query.data
151
- user_id = query.from_user.id
152
- save_user(user_id, query.from_user.username, query.from_user.first_name)
153
-
154
- if data == "menu_back":
155
- await query.message.edit_text("πŸ“‹ *Main Menu*", parse_mode='Markdown', reply_markup=main_menu())
156
-
157
- elif data == "menu_search":
158
- await query.message.edit_text("πŸ” *Search Options*", parse_mode='Markdown', reply_markup=search_menu())
159
-
160
- elif data == "menu_coins":
161
- conn = sqlite3.connect('bot_data.db')
162
- c = conn.cursor()
163
- c.execute('SELECT coins FROM users WHERE user_id = ?', (user_id,))
164
- row = c.fetchone()
165
- conn.close()
166
- coins = row[0] if row else 0
167
- await query.message.edit_text(
168
- f"{E['coin']} *Your Coins*\n\nπŸͺ™ Total: `{coins}`\n\nEarn by searching!",
169
- parse_mode='Markdown',
170
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("πŸ”™ Back", callback_data="menu_back")]])
171
- )
172
-
173
- elif data == "menu_leader":
174
- leaders = get_leaderboard(10)
175
- text = f"{E['leader']} *LEADERBOARD*\n\n"
176
- for idx, (uid, name, coins) in enumerate(leaders, 1):
177
- medal = "πŸ₯‡" if idx == 1 else "πŸ₯ˆ" if idx == 2 else "πŸ₯‰" if idx == 3 else f"{idx}."
178
- text += f"{medal} `{name[:15]}` β€” πŸͺ™ {coins}\n"
179
- await query.message.edit_text(
180
- text,
181
- parse_mode='Markdown',
182
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("πŸ”™ Back", callback_data="menu_back")]])
183
- )
184
 
185
- elif data == "menu_refer":
186
- bot_username = (await context.bot.get_me()).username
187
- ref_link = f"https://t.me/{bot_username}?start={user_id}"
188
- await query.message.edit_text(
189
- f"{E['refer']} *Refer & Earn*\n\nShare:\n`{ref_link}`\n\nYou get 10 coins per referral!",
190
- parse_mode='Markdown',
191
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("πŸ”™ Back", callback_data="menu_back")]])
192
- )
193
 
194
- elif data == "menu_about":
195
- await query.message.edit_text(
196
- f"{E['dev']} *About Bot*\n\nπŸ‘¨β€πŸ’» Developer: Gopal Parmar\nπŸ“Š Database: 70M+\nπŸ†˜ Support: @Kingx18rcb",
197
- parse_mode='Markdown',
198
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("πŸ”™ Back", callback_data="menu_back")]])
199
- )
200
 
201
- elif data.startswith("search_"):
202
- context.user_data['search_type'] = data.replace("search_", "")
203
- await query.message.edit_text(
204
- f"Send *{data.replace('search_', '').upper()}* to search.\nExample: `79254677980`",
205
- parse_mode='Markdown'
206
- )
207
 
208
- async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
209
- user_id = update.effective_user.id
210
- save_user(user_id, update.effective_user.username, update.effective_user.first_name)
 
211
 
212
- query_text = update.message.text.strip()
213
- await update.message.reply_text(f"{E['loading']} Searching...")
214
 
215
- async with aiohttp.ClientSession() as session:
216
- async with session.get(f"https://gopallikehack-Tgjson123.hf.space/search?q={query_text}&limit=10") as resp:
217
- data = await resp.json()
218
-
219
- add_coins(user_id, 1)
220
-
221
- if data.get("count", 0) == 0:
222
- await update.message.reply_text(f"{E['error']} No results")
223
  return
224
 
225
- text = f"{E['premium']} *RESULTS*\nπŸ” `{query_text}`\nβœ… Found: `{data['count']}`\nπŸͺ™ +1 coin\n\n"
226
- for idx, rec in enumerate(data.get("results", [])[:5], 1):
227
- text += f"*πŸ“Œ Result {idx}*\n"
228
- text += f"πŸ†” `{rec.get('account_id') or rec.get('user_id') or 'N/A'}`\n"
229
- text += f"πŸ“ž `{rec.get('phone') or 'N/A'}`\n"
230
- text += f"πŸ‘€ @{rec.get('username') or 'N/A'}\n"
231
- text += f"πŸ“ {rec.get('first_name') or ''} {rec.get('last_name') or ''}\n\n"
232
-
233
- text += f"\nπŸ‘¨β€πŸ’» Gopal Parmar"
234
- await update.message.reply_text(text, parse_mode='Markdown')
235
 
236
- # ========== RUN BOT IN BACKGROUND ==========
237
- def run_bot():
238
- init_db()
239
- bot_app = Application.builder().token(BOT_TOKEN).build()
240
- bot_app.add_handler(CommandHandler("start", start))
241
- bot_app.add_handler(CallbackQueryHandler(button_handler))
242
- bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
243
- print("πŸ€– Bot running...")
244
- bot_app.run_polling()
245
-
246
- # ========== MAIN ==========
247
  if __name__ == "__main__":
248
- # Start bot in background thread
249
- bot_thread = threading.Thread(target=run_bot, daemon=True)
250
- bot_thread.start()
251
-
252
- # Run FastAPI
253
- print("πŸš€ API running on http://0.0.0.0:7860")
254
- uvicorn.run(app, host="0.0.0.0", port=7860)
255
-
 
 
 
 
 
 
 
 
 
 
 
1
  import aiohttp
2
+ import asyncio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ API_URL = "https://gopallikehack-Tgjson123.hf.space/search?q="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ async def search_user(query):
7
+ async with aiohttp.ClientSession() as session:
8
+ async with session.get(f"{API_URL}{query}&limit=5") as resp:
9
+ data = await resp.json()
10
+ return data
 
 
 
 
 
11
 
12
+ def format_result(data):
13
+ if data.get("count", 0) == 0:
14
+ return "❌ No results found"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ text = f"πŸ” *Results for* `{data['query']}`\nβœ… Found: `{data['count']}`\n\n"
 
 
 
 
 
 
 
17
 
18
+ for idx, rec in enumerate(data.get("results", [])[:5], 1):
19
+ text += f"*πŸ“Œ Result {idx}*\n"
20
+ text += f"πŸ†” ID: `{rec.get('account_id') or rec.get('user_id') or 'N/A'}`\n"
21
+ text += f"πŸ“ž Phone: `{rec.get('phone') or 'N/A'}`\n"
22
+ text += f"πŸ‘€ Username: @{rec.get('username') or 'N/A'}\n"
23
+ text += f"πŸ“ Name: {rec.get('first_name') or ''} {rec.get('last_name') or ''}\n\n"
24
 
25
+ return text
 
 
 
 
 
26
 
27
+ async def main():
28
+ print("=" * 40)
29
+ print("πŸ” SEARCH BY USER ID OR USERNAME")
30
+ print("=" * 40)
31
 
32
+ query = input("Enter User ID or Username: ").strip()
 
33
 
34
+ if not query:
35
+ print("❌ Please enter something")
 
 
 
 
 
 
36
  return
37
 
38
+ print(f"\n⏳ Searching for `{query}`...\n")
39
+ result = await search_user(query)
40
+ print(format_result(result))
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
42
  if __name__ == "__main__":
43
+ asyncio.run(main())