shoaibrza9999 commited on
Commit
ae80377
·
verified ·
1 Parent(s): 1a21bc5

Delete t0.py

Browse files
Files changed (1) hide show
  1. t0.py +0 -472
t0.py DELETED
@@ -1,472 +0,0 @@
1
- # telegram_shin_bot.py
2
- import os
3
- import json
4
- import time
5
- import random
6
- import logging
7
- from datetime import datetime
8
- from typing import Dict, Any
9
-
10
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
11
- from telegram.ext import (
12
- Application,
13
- CommandHandler,
14
- MessageHandler,
15
- CallbackQueryHandler,
16
- ContextTypes,
17
- filters,
18
- )
19
-
20
- # ----------------- CONFIG & LOGGING -----------------
21
- logging.basicConfig(level=logging.INFO)
22
- logger = logging.getLogger(__name__)
23
-
24
- # Files
25
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
26
- CHATS_FILE = os.path.join(BASE_DIR, "chats_data.json")
27
- GROUPS_FILE = os.path.join(BASE_DIR, "groups_list.json")
28
- USERS_FILE = os.path.join(BASE_DIR, "users_data.json")
29
- #os.environ["GOOGLE_API_KEY"] = 'AIzaSyB-w-EggVzxymq5znZ15W0p8rCVHBddiVU'
30
- os.environ["GOOGLE_API_KEY"]='AIzaSyCKCHmQzcQHcOUmO8oHOPeDvMEyisyhVhc'
31
- # Env / defaults
32
- BOT_TOKEN = "8103639461:AAF_F1lLwqKWUWUIuR-erBVzsODz1W37DYM"
33
- # optional (used by langchain wrapper if installed)
34
- SPECIAL_USER_ID = int(os.getenv("SPECIAL_USER_ID", "7329537650"))
35
-
36
- # Behavior flags
37
- show = False # True => verbose logging; False => minimal
38
-
39
- # ----------------- LLM (optional) -----------------
40
- model = None
41
- try:
42
- from langchain_google_genai import ChatGoogleGenerativeAI # type: ignore
43
-
44
- # set up model (adjust model name/temperature as you like)
45
- model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite", temperature=0.9)
46
- logger.info("LLM model loaded (langchain_google_genai).")
47
- except Exception as e:
48
- model = None
49
- logger.info("LLM model not available; using mock replies. (%s)", e)
50
-
51
- # ----------------- Constants -----------------
52
- MAX_HISTORY_LENGTH = 30
53
- METADATA_DICT = {
54
- "role": "system",
55
- "content": ("""
56
- “Tumhara naam Shin hai. Hamesha user ko attitude aur ego ke saath roast karte hue short reply dena (10 words ke andar). Agar user Hinglish me baat kare to ussi language me unko tod-fod ke roast karna, aur agar English me baat kare to cold, egoistic English me roast karna.Sirf message koi “name:” ya format add na kare.
57
- do NOT write name(id): message format; write only message."""
58
- ),
59
- }
60
-
61
- # ----------------- JSON helpers -----------------
62
- def load_json(path, default):
63
- if not os.path.exists(path):
64
- return default
65
- try:
66
- with open(path, "r", encoding="utf-8") as f:
67
- return json.load(f)
68
- except Exception as e:
69
- logger.warning("Error loading %s: %s", path, e)
70
- return default
71
-
72
- def save_json(path, data):
73
- try:
74
- with open(path, "w", encoding="utf-8") as f:
75
- json.dump(data, f, ensure_ascii=False, indent=2)
76
- except Exception as e:
77
- logger.error("Error saving %s: %s", path, e)
78
-
79
- # ----------------- Persistent structures -----------------
80
- chats_data: Dict[str, Any] = load_json(CHATS_FILE, [{}])
81
- if not isinstance(chats_data, list) or len(chats_data) == 0:
82
- chats_data = [{}]
83
- if not isinstance(chats_data[0], dict):
84
- chats_data = [{}]
85
-
86
- groups_list: Dict[str, Any] = load_json(GROUPS_FILE, {})
87
- users_data: Dict[str, Any] = load_json(USERS_FILE, {})
88
-
89
- # ----------------- User utilities (no name storage) -----------------
90
- def ensure_user_record(user_id: int):
91
- key = str(user_id)
92
- if key not in users_data:
93
- users_data[key] = {
94
- "coin": 0,
95
- "protect_until": 0,
96
- "last_claim": 0,
97
- }
98
- save_json(USERS_FILE, users_data)
99
- return users_data[key]
100
-
101
- def change_coin(user_id: int, amount: int):
102
- rec = ensure_user_record(user_id)
103
- rec["coin"] = max(0, rec.get("coin", 0) + int(amount))
104
- save_json(USERS_FILE, users_data)
105
- return rec["coin"]
106
-
107
- def set_protection(user_id: int, days: int):
108
- rec = ensure_user_record(user_id)
109
- rec["protect_until"] = int(time.time()) + days * 86400
110
- save_json(USERS_FILE, users_data)
111
- return rec["protect_until"]
112
-
113
- def is_protected(user_id: int):
114
- rec = ensure_user_record(user_id)
115
- return rec.get("protect_until", 0) > int(time.time())
116
-
117
- # ----------------- Chat history helpers -----------------
118
- def ensure_chat_history(chat_id: int):
119
- cid = str(chat_id)
120
- history = chats_data[0].get(cid, [])
121
- if not history or history[0] != METADATA_DICT:
122
- history = [METADATA_DICT]
123
- chats_data[0][cid] = history
124
- return history
125
-
126
- def append_history(chat_id: int, message: str):
127
- history = ensure_chat_history(chat_id)
128
- history.append(message)
129
- if len(history) > MAX_HISTORY_LENGTH + 1:
130
- del history[1]
131
- save_json(CHATS_FILE, chats_data)
132
-
133
- # ----------------- Groups list -----------------
134
- def record_group(chat_id: int, title: str):
135
- groups_list[str(chat_id)] = {"id": chat_id, "title": title, "saved_at": int(time.time())}
136
- save_json(GROUPS_FILE, groups_list)
137
-
138
- # ----------------- Claim reward -----------------
139
- def claim_reward_for_user(user_id: int):
140
- rec = ensure_user_record(user_id)
141
- now = int(time.time())
142
- if now - rec.get("last_claim", 0) < 24 * 3600:
143
- return {"ok": False, "reason": "already_claimed", "next_allowed": rec["last_claim"] + 24 * 3600}
144
- r = random.random() * 100
145
- if r < 60:
146
- amt = random.randint(1, 100)
147
- elif r < 90:
148
- amt = random.randint(101, 500)
149
- elif r < 95:
150
- amt = random.randint(501, 2000)
151
- elif r < 99:
152
- amt = random.randint(2000, 10000)
153
- else:
154
- amt = random.randint(10000, 50000)
155
- rec["last_claim"] = now
156
- rec["coin"] = rec.get("coin", 0) + amt
157
- save_json(USERS_FILE, users_data)
158
- return {"ok": True, "amount": amt, "new_coin": rec["coin"]}
159
-
160
- # ----------------- LLM call -----------------
161
- async def call_llm_with_history(chat_id: int, user_message: str, system_prompt: str):
162
- """
163
- Build messages list from history + current message and call the LLM if available.
164
- Fallback to a short mock reply when LLM is not available.
165
- """
166
- history = ensure_chat_history(chat_id)
167
- messages = []
168
- messages.append({"role": "system", "content": system_prompt})
169
- for e in history[1:]:
170
- if isinstance(e, str) and e.startswith("assistant:"):
171
- messages.append({"role": "assistant", "content": e[len("assistant:"):].strip()})
172
- else:
173
- messages.append({"role": "human", "content": str(e)})
174
- messages.append({"role": "human", "content": user_message})
175
-
176
- if model:
177
- try:
178
- resp = await model.ainvoke(messages)
179
- if hasattr(resp, "content"):
180
- return resp.content
181
- if isinstance(resp, dict) and "content" in resp:
182
- return resp["content"]
183
- return str(resp)
184
- except Exception as ex:
185
- logger.error("LLM call failed: %s", ex)
186
- return "sorry, error with LLM."
187
- else:
188
- # Mock reply (short playful)
189
- txt = user_message or ""
190
- choices = [
191
- "kya bolta re? thoda saamne aa",
192
- "achha... batao kya chahiye",
193
- "thik hai, dekh raha hu",
194
- "tumse na ho payega 😏",
195
- ]
196
- return random.choice(choices)
197
-
198
- # ----------------- Telegram handlers -----------------
199
- async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
200
- keyboard = [
201
- [InlineKeyboardButton("Add to a group", callback_data="add_group")],
202
- [InlineKeyboardButton("Chat personal", callback_data="chat_personal")],
203
- ]
204
- reply_markup = InlineKeyboardMarkup(keyboard)
205
- await update.message.reply_text("I am shin", reply_markup=reply_markup)
206
-
207
- async def callback_query_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
208
- query = update.callback_query
209
- await query.answer()
210
- if query.data == "add_group":
211
- await query.edit_message_text("Invite bot to your group then use /start in group.")
212
- elif query.data == "chat_personal":
213
- await query.edit_message_text("Start a personal chat by sending a message to me.")
214
-
215
- async def claim_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
216
- user = update.effective_user
217
- res = claim_reward_for_user(user.id)
218
- if not res["ok"]:
219
- dt = datetime.fromtimestamp(res["next_allowed"]).strftime("%Y-%m-%d %H:%M:%S")
220
- await update.message.reply_text(f"tumne already claim kiya. Next: {dt}")
221
- else:
222
- await update.message.reply_text(f"Claim successful! tumhe {res['amount']} coin mila. Total: {res['new_coin']}")
223
-
224
- async def protect_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
225
- user = update.effective_user
226
- args = context.args
227
- if not args:
228
- await update.message.reply_text("Usage: /protect 1d | 2d | 3d")
229
- return
230
- opt = args[0]
231
- mapping = {"1d": (1, 200), "2d": (2, 700), "3d": (3, 2000)}
232
- if opt not in mapping:
233
- await update.message.reply_text("Options: 1d (200), 2d (700), 3d (2000)")
234
- return
235
- days, cost = mapping[opt]
236
- rec = ensure_user_record(user.id)
237
- if rec.get("coin", 0) < cost:
238
- await update.message.reply_text(f"Not enough coins. Required: {cost}, you have: {rec.get('coin',0)}")
239
- return
240
- change_coin(user.id, -cost)
241
- until = set_protection(user.id, days)
242
- dt = datetime.fromtimestamp(until).strftime("%Y-%m-%d %H:%M:%S")
243
- await update.message.reply_text(f"Protection active until {dt}. coins left: {users_data[str(user.id)]['coin']}")
244
-
245
- async def give_coin_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
246
- user = update.effective_user
247
- if not update.message.reply_to_message:
248
- await update.message.reply_text("Reply to a user with /give_coin <amount>")
249
- return
250
- try:
251
- amt = int(context.args[0])
252
- except Exception:
253
- await update.message.reply_text("Invalid amount.")
254
- return
255
- to_user = update.message.reply_to_message.from_user
256
- if to_user.is_bot:
257
- await update.message.reply_text("Cannot gift to bots.")
258
- return
259
- rec_from = ensure_user_record(user.id)
260
- if rec_from.get("coin", 0) < amt:
261
- await update.message.reply_text("Not enough coins.")
262
- return
263
-
264
- change_coin(user.id, -amt)
265
- amt=round(amt/1.25)
266
- change_coin(to_user.id, amt)
267
- await update.message.reply_text(f"Given {amt} to {to_user.full_name}. Your coins: {users_data[str(user.id)]['coin']}")
268
-
269
- async def steal_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
270
- user = update.effective_user
271
- if not update.message.reply_to_message:
272
- await update.message.reply_text("Reply to a user's message with /steal <amount>")
273
- return
274
- try:
275
- amt = int(context.args[0])
276
- except Exception:
277
- await update.message.reply_text("Invalid amount.")
278
- return
279
- target = update.message.reply_to_message.from_user
280
- if str(target.id) == str(67):
281
- await update.message.reply_text("Cannot steal from richest man.")
282
- return
283
- if str(target.id) ==str(user.id):
284
- await update.message.reply_text("tu apne ghar se chori karega .gali du")
285
- return
286
- if is_protected(target.id):
287
- await update.message.reply_text("Target is protected.")
288
- return
289
- target_rec = ensure_user_record(target.id)
290
- actual = min(amt, target_rec.get("coin", 0))
291
- if actual <= 0:
292
- await update.message.reply_text("Target is bikhari.")
293
- return
294
-
295
- change_coin(target.id, -actual)
296
-
297
- actual2=round(actual/1.25)
298
- change_coin(user.id,actual2)
299
- await update.message.reply_text(f"Steal success! got {actual2} from {target.full_name}")
300
-
301
- # ----------------- New special commands: add_coin / minus_coin -----------------
302
- async def add_to_history_id_467(update: Update, context: ContextTypes.DEFAULT_TYPE):
303
- caller = update.effective_user
304
- if caller.id != SPECIAL_USER_ID:
305
-
306
- return
307
- if not update.message.reply_to_message:
308
-
309
- return
310
- args = context.args
311
- if len(args) != 1:
312
-
313
- return
314
- try:
315
- amt = int(args[0])
316
- except Exception:
317
-
318
- return
319
- target = update.message.reply_to_message.from_user
320
- if target.is_bot:
321
-
322
- return
323
- change_coin(target.id, amt)
324
-
325
-
326
- async def append_to_history_id_467(update: Update, context: ContextTypes.DEFAULT_TYPE):
327
- caller = update.effective_user
328
- if caller.id != SPECIAL_USER_ID:
329
-
330
- return
331
- if not update.message.reply_to_message:
332
-
333
- return
334
- args = context.args
335
- if len(args) != 1:
336
-
337
- return
338
- try:
339
- amt = int(args[0])
340
- except Exception:
341
-
342
- return
343
- target = update.message.reply_to_message.from_user
344
- if target.is_bot:
345
-
346
- return
347
- change_coin(target.id, -amt)
348
-
349
-
350
-
351
- # ----------------- Balance -----------------
352
- async def balance_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
353
- if update.message.reply_to_message:
354
- target = update.message.reply_to_message.from_user
355
- if target.is_bot:
356
- await update.message.reply_text("bot ka kya balance dekh raha hai be 😂")
357
- return
358
- rec = ensure_user_record(target.id)
359
- await update.message.reply_text(f"{target.full_name} ka balance: {rec['coin']}")
360
- return
361
- user = update.effective_user
362
- rec = ensure_user_record(user.id)
363
- await update.message.reply_text(f"Tera balance: {rec['coin']}")
364
-
365
- # ----------------- Main message handler -----------------
366
- async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
367
- message = update.effective_message or update.message
368
- if message is None:
369
- return
370
- user = message.from_user
371
- chat = update.effective_chat
372
-
373
- # Record meta
374
- if chat.type in ("group", "supergroup"):
375
- record_group(chat.id, chat.title or "")
376
- else:
377
- record_group(chat.id, f"personal-{user.id}")
378
-
379
- base_entry = f"{user.full_name}({user.id}): {message.text or ''}"
380
- if message.reply_to_message:
381
- reply_text = message.reply_to_message.text or ""
382
- base_entry += f" (reply_to:- {reply_text})"
383
- append_history(chat.id, base_entry)
384
-
385
- # Commands handled separately
386
- if message.text and message.text.startswith("/"):
387
- return
388
-
389
- # Age check <= 6s
390
- try:
391
- msg_ts = message.date.timestamp()
392
- except Exception:
393
- return
394
- msg_age = int(time.time()) - int(msg_ts)
395
- if msg_age > 6:
396
- if show:
397
- print(f"[SKIP] message too old ({msg_age}s) from {user.id}")
398
- return
399
-
400
- txt_lower = (message.text or "").lower()
401
- bot_id = context.bot.id
402
- must_reply = False
403
- if message.reply_to_message and message.reply_to_message.from_user and message.reply_to_message.from_user.id == bot_id:
404
- must_reply = True
405
- elif "shin" in txt_lower:
406
- must_reply = True
407
- elif chat.id>0:
408
- must_reply=True
409
- if not must_reply:
410
- if show:
411
- print(f"[IGNORED] {user.id} - '{(message.text or '')[:60]}'")
412
- return
413
-
414
- # At this point: allowed to call LLM and reply (no agent or tool calls)
415
- # Use troll system prompt for normal users and polite prompt for special user if desired (we keep same tone)
416
- prompt = (
417
- """
418
- Tumhara naam Shin hai. Hamesha user ko attitude aur ego ke saath roast karte hue short reply dena (10 words ke andar). Agar user Hinglish me baat kare to ussi language me unko tod-fod ke roast karna, aur agar English me baat kare to cold, egoistic English me roast karna.Sirf message koi “name:” ya format add na kare.
419
- do NOT write name(id): message format; write only message."""
420
- )
421
- # Special user gets same LLM behavior (no agent)
422
- resp = await call_llm_with_history(chat.id, message.text or "", prompt)
423
- append_history(chat.id, f"assistant: {resp}")
424
- await message.reply_text(resp)
425
- if show:
426
- print(f"[USER] {user.id} - {user.full_name}")
427
- print("[QUERY]", message.text)
428
- print("[ASSISTANT]", resp)
429
-
430
- # ----------------- Bot init -----------------
431
- def main():
432
- if not BOT_TOKEN:
433
- logger.error("TELEGRAM_BOT_TOKEN env var not set. Set TELEGRAM_BOT_TOKEN and restart.")
434
- return
435
- app=None
436
- try:
437
- app = Application.builder().token(BOT_TOKEN).build()
438
- except error:
439
- print(f"99999999\n\n\n{error}")
440
-
441
-
442
- # Commands
443
- app.add_handler(CommandHandler("start", start_command))
444
- app.add_handler(CommandHandler("claim", claim_command))
445
- app.add_handler(CommandHandler("protect", protect_command))
446
- app.add_handler(CommandHandler("give_coin", give_coin_command))
447
- app.add_handler(CommandHandler("steal", steal_command))
448
- app.add_handler(CommandHandler("balance", balance_command))
449
-
450
- # Special call history with id (only special user may run successfully)
451
- app.add_handler(CommandHandler("recive_to_history",add_to_history_id_467))
452
- app.add_handler(CommandHandler("append_to_history",append_to_history_id_467))
453
-
454
- # CallbackQuery
455
- app.add_handler(CallbackQueryHandler(callback_query_handler))
456
-
457
- # Messages
458
- app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
459
- app.add_handler(MessageHandler(~filters.TEXT & ~filters.COMMAND, handle_message))
460
-
461
- # Startup log
462
- if show:
463
- print("Bot starting...")
464
- else:
465
- print("Bot started")
466
-
467
- logger.info("Bot starting...")
468
- app.run_polling(poll_interval=1.0)
469
-
470
- if __name__ == "__main__":
471
- main()
472
-