ysn-rfd commited on
Commit
86fc9d0
·
verified ·
1 Parent(s): e4074ad

Upload 36 files

Browse files
BOT/2/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # render2_bot
BOT/2/STORED.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py - اصلاح تابع retrieve_context
2
+
3
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
4
+ """بازیابی هوشمند context مرتبط با query"""
5
+
6
+ if max_tokens is None:
7
+ max_tokens = self.max_context_tokens
8
+
9
+ start_time = datetime.now()
10
+
11
+ # 1. دریافت embedding برای query
12
+ query_embedding = self.embedding_manager.get_embedding(query)
13
+
14
+ # 2. بازیابی از لایه‌های مختلف حافظه
15
+ retrieved_memories = []
16
+
17
+ # از حافظه فعال (همیشه)
18
+ retrieved_memories.extend(self._retrieve_from_working_memory())
19
+
20
+ # از حافظه اخیر (بر اساس شباهت)
21
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
22
+ retrieved_memories.extend(recent_memories)
23
+
24
+ # از حافظه بلندمدت (اطلاعات مهم)
25
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
26
+ retrieved_memories.extend(long_term_memories)
27
+
28
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
29
+ core_memories = self._retrieve_core_memories(query)
30
+ retrieved_memories.extend(core_memories)
31
+
32
+ # 3. حذف تکراری‌ها و مرتب‌سازی
33
+ unique_memories = self._deduplicate_memories(retrieved_memories)
34
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
35
+
36
+ # 4. انتخاب تا سقف توکن
37
+ final_context = []
38
+ total_tokens = 0
39
+
40
+ for memory in prioritized_memories:
41
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
42
+
43
+ if total_tokens + memory_tokens <= max_tokens:
44
+ final_context.append(memory)
45
+ total_tokens += memory_tokens
46
+ else:
47
+ break
48
+
49
+ # 5. به‌روزرسانی آمار
50
+ self.stats['retrieved_memories'] += len(final_context)
51
+
52
+ retrieval_time = (datetime.now() - start_time).total_seconds()
53
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
54
+
55
+ return final_context
56
+
57
+ # اصلاح تابع get_context_for_api
58
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
59
+ """تهیه context برای ارسال به API"""
60
+
61
+ # اگر query داریم، context هوشمند بازیابی کن
62
+ if query:
63
+ retrieved = await self.retrieve_context(query)
64
+
65
+ # تبدیل به فرمت API
66
+ api_messages = []
67
+
68
+ # ابتدا اطلاعات پروفایل کاربر
69
+ api_messages.append({
70
+ 'role': 'system',
71
+ 'content': f"User profile: {self._format_user_profile()}"
72
+ })
73
+
74
+ # سپس حافظه‌های بازیابی شده
75
+ for memory in retrieved:
76
+ node = memory['node']
77
+ api_messages.append({
78
+ 'role': node.role,
79
+ 'content': node.content
80
+ })
81
+
82
+ return api_messages
83
+
84
+ else:
85
+ # حالت ساده: فقط حافظه فعال
86
+ api_messages = []
87
+
88
+ for node in list(self.memory_layers['working'])[-6:]:
89
+ api_messages.append({
90
+ 'role': node.role,
91
+ 'content': node.content
92
+ })
93
+
94
+ return api_messages
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ # main.py - اصلاح تابع _process_user_request
114
+
115
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
116
+ chat_id = update.effective_chat.id
117
+ user_message = update.message.text
118
+ user_id = update.effective_user.id
119
+
120
+ start_time = time.time()
121
+
122
+ try:
123
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
124
+
125
+ # استفاده از Context هوشمند اگر فعال باشد
126
+ if HAS_SMART_CONTEXT:
127
+ smart_context = _get_or_create_smart_context(user_id)
128
+
129
+ # پردازش پیام کاربر با سیستم هوشمند
130
+ await smart_context.process_message("user", user_message)
131
+
132
+ # بازیابی context مرتبط
133
+ retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)
134
+
135
+ # آماده‌سازی پیام‌ها برای API
136
+ messages = await smart_context.get_context_for_api(user_message)
137
+
138
+ logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")
139
+ else:
140
+ # استفاده از سیستم قدیمی
141
+ user_context = data_manager.get_context_for_api(user_id)
142
+ data_manager.add_to_user_context(user_id, "user", user_message)
143
+ messages = user_context.copy()
144
+ messages.append({"role": "user", "content": user_message})
145
+
146
+ # ارسال به API
147
+ response = await client.chat.completions.create(
148
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
149
+ messages=messages,
150
+ temperature=1.0,
151
+ top_p=0.95,
152
+ stream=False,
153
+ )
154
+
155
+ end_time = time.time()
156
+ response_time = end_time - start_time
157
+ data_manager.update_response_stats(response_time)
158
+
159
+ ai_response = response.choices[0].message.content
160
+
161
+ # ذخیره پاسخ در سیستم مناسب
162
+ if HAS_SMART_CONTEXT:
163
+ await smart_context.process_message("assistant", ai_response)
164
+ else:
165
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
166
+
167
+ await update.message.reply_text(ai_response)
168
+ data_manager.update_user_stats(user_id, update.effective_user)
169
+
170
+ except httpx.TimeoutException:
171
+ logger.warning(f"Request timed out for user {user_id}.")
172
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
173
+ except Exception as e:
174
+ logger.error(f"Error while processing message for user {user_id}: {e}")
175
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+ # smart_context.py - اصلاح توابع async
194
+
195
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
196
+ layer: str) -> List[Dict[str, Any]]:
197
+ """بازیابی حافظه‌های معنایی"""
198
+ memories = []
199
+
200
+ if layer not in self.memory_layers:
201
+ return memories
202
+
203
+ layer_memories = self.memory_layers[layer]
204
+
205
+ for item in layer_memories:
206
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
207
+
208
+ if node and node.embeddings is not None:
209
+ similarity = self.embedding_manager.cosine_similarity(
210
+ query_embedding, node.embeddings
211
+ )
212
+
213
+ if similarity > self.semantic_similarity_threshold:
214
+ recency_weight = 1.0 if layer == 'working' else 0.7
215
+
216
+ memories.append({
217
+ 'node': node,
218
+ 'source': layer,
219
+ 'relevance': similarity,
220
+ 'recency': recency_weight,
221
+ 'importance': node.importance_score
222
+ })
223
+
224
+ return memories
225
+
226
+ # اصلاح تابع process_message برای جلوگیری از block کردن
227
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
228
+ """پرداش کامل یک پیام جدید"""
229
+ start_time = datetime.now()
230
+
231
+ # 1. تحلیل پیام
232
+ analysis = self.analyzer.analyze_message(content, role)
233
+
234
+ # 2. ایجاد گره حافظه
235
+ message_id = self._generate_message_id(content)
236
+
237
+ # ایجاد embedding به صورت غیرهمزمان
238
+ embedding_task = asyncio.create_task(
239
+ self._get_embedding_async(content)
240
+ )
241
+
242
+ node = MessageNode(
243
+ id=message_id,
244
+ content=content,
245
+ role=role,
246
+ timestamp=datetime.now(),
247
+ message_type=analysis['type'],
248
+ importance_score=analysis['importance'],
249
+ emotion_score=analysis['emotion'],
250
+ tokens=data_manager.count_tokens(content),
251
+ embeddings=None, # موقتاً None
252
+ metadata={
253
+ 'analysis': analysis,
254
+ 'topics': analysis['topics'],
255
+ 'intent': analysis['intent'],
256
+ 'complexity': analysis['complexity']
257
+ }
258
+ )
259
+
260
+ # دریافت embedding (اگر موجود باشد)
261
+ try:
262
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
263
+ except asyncio.TimeoutError:
264
+ logger.warning(f"Embedding generation timeout for message {message_id}")
265
+ node.embeddings = self.embedding_manager.get_embedding(content)
266
+
267
+ # 3. افزودن به حافظه و گراف
268
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
269
+ await asyncio.to_thread(self.memory_graph.add_node, node)
270
+
271
+ # 4. ایجاد ارتباطات
272
+ await asyncio.to_thread(self._create_memory_connections, node)
273
+
274
+ # 5. به‌روزرسانی پروفایل کاربر
275
+ if role == 'user':
276
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
277
+
278
+ # 6. بهینه‌سازی حافظه
279
+ await asyncio.to_thread(self._optimize_memory)
280
+
281
+ # 7. به‌روزرسانی آمار
282
+ self.stats['total_messages'] += 1
283
+ self.stats['average_importance'] = (
284
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
285
+ analysis['importance']
286
+ ) / self.stats['total_messages']
287
+
288
+ # 8. ذخیره داده‌ها
289
+ await asyncio.to_thread(self._save_data)
290
+
291
+ processing_time = (datetime.now() - start_time).total_seconds()
292
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
293
+
294
+ return {
295
+ 'node_id': message_id,
296
+ 'analysis': analysis,
297
+ 'processing_time': processing_time
298
+ }
299
+
300
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
301
+ """دریافت embedding به صورت async"""
302
+ loop = asyncio.get_event_loop()
303
+ return await loop.run_in_executor(
304
+ None,
305
+ self.embedding_manager.get_embedding,
306
+ text
307
+ )
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+ # admin_panel.py - اصلاح توابع async در smart_context
338
+
339
+ @admin_only
340
+ async def admin_smart_context_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
341
+ """نمایش آمار context هوشمند برای کاربران"""
342
+ if not HAS_SMART_CONTEXT:
343
+ await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
344
+ return
345
+
346
+ if not context.args:
347
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/smart_stats 123456789`")
348
+ return
349
+
350
+ user_id = int(context.args[0])
351
+
352
+ # بررسی وجود مدیر context
353
+ if user_id not in smart_context_managers:
354
+ smart_context_managers[user_id] = IntelligentContextManager(user_id)
355
+
356
+ smart_context = smart_context_managers[user_id]
357
+ summary = await asyncio.to_thread(smart_context.get_summary)
358
+
359
+ # ... بقیه کد بدون تغییر
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+ # smart_context.py - اضافه کردن خطاگیری بهتر
388
+
389
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
390
+ """بازیابی هوشمند context مرتبط با query"""
391
+ try:
392
+ if max_tokens is None:
393
+ max_tokens = self.max_context_tokens
394
+
395
+ start_time = datetime.now()
396
+
397
+ # دریافت embedding با timeout
398
+ try:
399
+ embedding_task = asyncio.create_task(
400
+ self._get_embedding_async(query)
401
+ )
402
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
403
+ except asyncio.TimeoutError:
404
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
405
+ query_embedding = self.embedding_manager.get_embedding(query)
406
+
407
+ # بازیابی از حافظه‌های مختلف به صورت موازی
408
+ tasks = []
409
+
410
+ # حافظه فعال
411
+ tasks.append(asyncio.create_task(
412
+ asyncio.to_thread(self._retrieve_from_working_memory)
413
+ ))
414
+
415
+ # حافظه معنایی
416
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
417
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
418
+
419
+ # حافظه هسته
420
+ tasks.append(asyncio.create_task(
421
+ asyncio.to_thread(self._retrieve_core_memories, query)
422
+ ))
423
+
424
+ # اجرای موازی همه tasks
425
+ results = await asyncio.gather(*tasks, return_exceptions=True)
426
+
427
+ # جمع‌آوری نتایج
428
+ retrieved_memories = []
429
+ for result in results:
430
+ if isinstance(result, Exception):
431
+ logger.error(f"Error retrieving memory: {result}")
432
+ continue
433
+ retrieved_memories.extend(result)
434
+
435
+ # ادامه پردازش...
436
+ # ... بقیه کد بدون تغییر
437
+
438
+ except Exception as e:
439
+ logger.error(f"Error in retrieve_context: {e}")
440
+ # Fallback: برگرداندن حافظه فعال
441
+ return self._retrieve_from_working_memory()
BOT/2/admin_panel.py ADDED
@@ -0,0 +1,1682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin_panel.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import csv
7
+ import io
8
+ import asyncio
9
+ from datetime import datetime, timedelta
10
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
11
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler
12
+ from telegram.error import TelegramError
13
+
14
+ import matplotlib
15
+ matplotlib.use('Agg')
16
+ import matplotlib.pyplot as plt
17
+ import pandas as pd
18
+ import tempfile
19
+ import psutil
20
+ import platform
21
+ import time
22
+
23
+ # --- تنظیمات ---
24
+ # خواندن ADMIN_IDS از محیط
25
+ ENV_ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
26
+
27
+ import data_manager
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # تابع برای دریافت لیست کامل ادمین‌ها
32
+ def get_admin_ids():
33
+ """دریافت لیست کامل ادمین‌ها (ادمین‌های اصلی + ادمین‌های اضافه شده)"""
34
+ env_admins = ENV_ADMIN_IDS
35
+ added_admins = data_manager.DATA.get('added_admins', [])
36
+
37
+ # ترکیب لیست‌ها و حذف تکراری‌ها
38
+ all_admins = list(set(env_admins + added_admins))
39
+ return all_admins
40
+
41
+ # تابع برای بررسی ادمین ارشد بودن
42
+ def is_super_admin(user_id: int) -> bool:
43
+ """بررسی اینکه آیا کاربر ادمین ارشد است (از طریق محیط تنظیم شده)"""
44
+ return user_id in ENV_ADMIN_IDS
45
+
46
+ # تابع برای بررسی اینکه کاربر ادمین است
47
+ def is_admin(user_id: int) -> bool:
48
+ """بررسی اینکه آیا کاربر ادمین است (از لیست کامل)"""
49
+ return user_id in get_admin_ids()
50
+
51
+ # --- دکوراتور برای دسترسی ادمین ---
52
+ def admin_only(func):
53
+ async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
54
+ if update.effective_user.id not in get_admin_ids():
55
+ await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
56
+ return
57
+ return await func(update, context, *args, **kwargs)
58
+ return wrapped
59
+
60
+ # --- هندلرهای دستورات ادمین ---
61
+ @admin_only
62
+ async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
63
+ """نمایش تمام دستورات موجود ادمین."""
64
+ commands_text = (
65
+ "📋 **دستورات ادمین ربات:**\n\n"
66
+ "👑 `/add_admin_bot [آیدی]` - اضافه کردن ادمین جدید\n"
67
+ "👑 `/remove_admin_bot [آیدی]` - حذف ادمین\n"
68
+ "👑 `/list_admins` - نمایش لیست ادمین‌ها\n\n"
69
+ "📊 `/stats` - نمایش آمار ربات\n"
70
+ "📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
71
+ "🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
72
+ "📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامه‌ریزی شده\n"
73
+ "📋 `/list_scheduled` - نمایش لیست ارسال‌های برنامه‌ریزی شده\n"
74
+ "🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامه‌ریزی شده\n"
75
+ "🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
76
+ "✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
77
+ "💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
78
+ "ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
79
+ "📝 `/logs` - نمایش آخرین لاگ‌ها\n"
80
+ "📂 `/logs_file` - دانلود فایل کامل لاگ‌ها\n"
81
+ "👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
82
+ "🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
83
+ "💾 `/backup` - ایجاد نسخه پشتیبان از داده‌ها\n"
84
+ "📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
85
+ "🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
86
+ "👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
87
+ "👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
88
+ "📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
89
+ "⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
90
+ "🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
91
+ "✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
92
+ "📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
93
+ "💻 `/system_info` - نمایش اطلاعات سیستم\n"
94
+ "🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
95
+ "🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
96
+ "📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
97
+ "📋 `/view_replies [user|group] [آیدی]` - مشاهده ریپلای‌ها\n"
98
+ "🔄 `/set_context_mode [separate|group_shared|hybrid]` - تغییر حالت context\n"
99
+ "📊 `/group_info [آیدی]` - نمایش اطلاعات گروه\n"
100
+ "🗑️ `/clear_group_context [آیدی]` - پاک کردن context گروه\n"
101
+ "💾 `/memory_status` - نمایش وضعیت حافظه\n"
102
+ "⚙️ `/set_global_system [متن]` - تنظیم system instruction سراسری\n"
103
+ "👥 `/set_group_system [آیدی گروه] [متن]` - تنظیم system instruction برای گروه\n"
104
+ "👤 `/set_user_system [آیدی کاربر] [متن]` - تنظیم system instruction برای کاربر\n"
105
+ "📋 `/list_system_instructions` - نمایش لیست system instruction‌ها\n"
106
+ "📋 `/commands` - نمایش این لیست دستورات"
107
+ )
108
+ await update.message.reply_text(commands_text, parse_mode='Markdown')
109
+
110
+ @admin_only
111
+ async def admin_add_admin_bot(update: Update, context: ContextTypes.DEFAULT_TYPE):
112
+ """اضافه کردن کاربر به لیست ادمین‌های ربات"""
113
+ if not context.args or not context.args[0].isdigit():
114
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/add_admin_bot 123456789`")
115
+ return
116
+
117
+ user_id_to_add = int(context.args[0])
118
+ current_user_id = update.effective_user.id
119
+
120
+ # بررسی اینکه کاربر فعلی ادمین ارشد است
121
+ if not is_super_admin(current_user_id):
122
+ await update.message.reply_text("⛔️ فقط ادمین‌های ارشد می‌توانند ادمین جدید اضافه کنند.")
123
+ return
124
+
125
+ # بررسی اینکه کاربر از قبل ادمین است
126
+ if is_admin(user_id_to_add):
127
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_add}` از قبل ادمین است.")
128
+ return
129
+
130
+ # افزودن کاربر به لیست ادمین‌های اضافه شده
131
+ if 'added_admins' not in data_manager.DATA:
132
+ data_manager.DATA['added_admins'] = []
133
+
134
+ if user_id_to_add not in data_manager.DATA['added_admins']:
135
+ data_manager.DATA['added_admins'].append(user_id_to_add)
136
+ data_manager.save_data()
137
+
138
+ # تلاش برای اطلاع دادن به کاربر جدید
139
+ try:
140
+ await context.bot.send_message(
141
+ chat_id=user_id_to_add,
142
+ text=f"🎉 شما توسط ادمین ربات به عنوان ادمین جدید ربات منصوب شدید!\n\n"
143
+ f"اکنون می‌توانید از دستورات مدیریتی ربات استفاده کنید.\n"
144
+ f"برای مشاهده دستورات از /help استفاده کنید."
145
+ )
146
+ except TelegramError as e:
147
+ logger.warning(f"Could not send admin notification to user {user_id_to_add}: {e}")
148
+
149
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_add}` با موفقیت به لیست ادمین‌های ربات اضافه شد.", parse_mode='Markdown')
150
+
151
+ # لاگ کردن عمل
152
+ admin_name = update.effective_user.first_name
153
+ logger.info(f"Super admin {admin_name} ({current_user_id}) added user {user_id_to_add} as admin.")
154
+ else:
155
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_add}` از قبل در لیست ادمین‌های اضافه شده است.")
156
+
157
+ @admin_only
158
+ async def admin_remove_admin_bot(update: Update, context: ContextTypes.DEFAULT_TYPE):
159
+ """حذف کاربر از لیست ادمین‌های ربات (فقط برای ادمین‌های ارشد)"""
160
+ if not context.args or not context.args[0].isdigit():
161
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/remove_admin_bot 123456789`")
162
+ return
163
+
164
+ user_id_to_remove = int(context.args[0])
165
+ current_user_id = update.effective_user.id
166
+
167
+ # بررسی اینکه کاربر فعلی ادمین ارشد است
168
+ if not is_super_admin(current_user_id):
169
+ await update.message.reply_text("⛔️ فقط ادمین‌های ارشد می‌توانند ادمین‌ها را حذف کنند.")
170
+ return
171
+
172
+ # بررسی اینکه کاربر در لیست ادمین‌های ارشد نیست
173
+ if is_super_admin(user_id_to_remove):
174
+ await update.message.reply_text("⛔️ نمی‌توان ادمین‌های ارشد را حذف کرد.")
175
+ return
176
+
177
+ # بررسی اینکه کاربر در لیست ادمین‌های اضافه شده است
178
+ if 'added_admins' not in data_manager.DATA or user_id_to_remove not in data_manager.DATA['added_admins']:
179
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_remove}` در لیست ادمین‌های اضافه شده وجود ندارد.")
180
+ return
181
+
182
+ # حذف کاربر از لیست ادمین‌های اضافه شده
183
+ data_manager.DATA['added_admins'].remove(user_id_to_remove)
184
+ data_manager.save_data()
185
+
186
+ # اطلاع دادن به کاربر حذف شده
187
+ try:
188
+ await context.bot.send_message(
189
+ chat_id=user_id_to_remove,
190
+ text="⛔️ دسترسی ادمین شما از ربات برداشته شد.\n\n"
191
+ "شما دیگر نمی‌توانید از دستورات مدیریتی استفاده کنید."
192
+ )
193
+ except TelegramError as e:
194
+ logger.warning(f"Could not send removal notification to user {user_id_to_remove}: {e}")
195
+
196
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_remove}` از لیست ادمین‌های ربات حذف شد.", parse_mode='Markdown')
197
+
198
+ # لاگ کردن عمل
199
+ admin_name = update.effective_user.first_name
200
+ logger.info(f"Super admin {admin_name} ({current_user_id}) removed user {user_id_to_remove} from admin list.")
201
+
202
+ @admin_only
203
+ async def admin_list_admins(update: Update, context: ContextTypes.DEFAULT_TYPE):
204
+ """نمایش لیست ادمین‌های ربات"""
205
+ env_admins = ENV_ADMIN_IDS
206
+ added_admins = data_manager.DATA.get('added_admins', [])
207
+ all_admins = get_admin_ids()
208
+
209
+ # جمع‌آوری اطلاعات ادمین‌ها
210
+ admin_info = []
211
+
212
+ # ادمین‌های ارشد (از محیط)
213
+ for admin_id in env_admins:
214
+ admin_data = data_manager.DATA['users'].get(str(admin_id), {})
215
+ name = admin_data.get('first_name', 'نامشخص')
216
+ username = admin_data.get('username', 'نامشخص')
217
+ admin_info.append({
218
+ 'id': admin_id,
219
+ 'name': name,
220
+ 'username': username,
221
+ 'type': 'ارشد 🔥',
222
+ 'last_seen': admin_data.get('last_seen', 'نامشخص')
223
+ })
224
+
225
+ # ادمین‌های اضافه شده
226
+ for admin_id in added_admins:
227
+ admin_data = data_manager.DATA['users'].get(str(admin_id), {})
228
+ name = admin_data.get('first_name', 'نامشخص')
229
+ username = admin_data.get('username', 'نامشخص')
230
+ admin_info.append({
231
+ 'id': admin_id,
232
+ 'name': name,
233
+ 'username': username,
234
+ 'type': 'عادی 👤',
235
+ 'last_seen': admin_data.get('last_seen', 'نامشخص')
236
+ })
237
+
238
+ if not admin_info:
239
+ await update.message.reply_text("⚠️ لیست ادمین‌ها خالی است.")
240
+ return
241
+
242
+ # ایجاد متن خروجی
243
+ text = "👑 **لیست ادمین‌های ربات:**\n\n"
244
+
245
+ for i, admin in enumerate(admin_info, 1):
246
+ text += f"{i}. {admin['type']} `{admin['id']}` - {admin['name']} (@{admin['username']})\n"
247
+ text += f" ⏰ آخرین فعالیت: {admin['last_seen']}\n\n"
248
+
249
+ text += f"\n📊 **آمار:**\n"
250
+ text += f"• ادمین‌های ارشد: {len(env_admins)}\n"
251
+ text += f"• ادمین‌های عادی: {len(added_admins)}\n"
252
+ text += f"• کل ادمین‌ها: {len(all_admins)}"
253
+
254
+ await update.message.reply_text(text, parse_mode='Markdown')
255
+
256
+ @admin_only
257
+ async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
258
+ """آمار ربات را نمایش می‌دهد."""
259
+ total_users = len(data_manager.DATA['users'])
260
+ total_groups = len(data_manager.DATA['groups'])
261
+ total_messages = data_manager.DATA['stats']['total_messages']
262
+ banned_count = len(data_manager.DATA['banned_users'])
263
+
264
+ # تعداد ادمین‌ها
265
+ env_admins = ENV_ADMIN_IDS
266
+ added_admins = data_manager.DATA.get('added_admins', [])
267
+ total_admins = len(env_admins) + len(added_admins)
268
+
269
+ now = datetime.now()
270
+ active_24h = sum(1 for user in data_manager.DATA['users'].values()
271
+ if 'last_seen' in user and
272
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
273
+
274
+ active_7d = sum(1 for user in data_manager.DATA['users'].values()
275
+ if 'last_seen' in user and
276
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
277
+
278
+ active_users = sorted(
279
+ data_manager.DATA['users'].items(),
280
+ key=lambda item: item[1].get('last_seen', ''),
281
+ reverse=True
282
+ )[:5]
283
+
284
+ active_users_text = "\n".join(
285
+ [f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
286
+ for user_id, info in active_users]
287
+ )
288
+
289
+ # اطلاعات context
290
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values()
291
+ if user.get('context') and len(user['context']) > 0)
292
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
293
+
294
+ # اطلاعات ریپلای‌ها
295
+ total_replies = 0
296
+ for user in data_manager.DATA['users'].values():
297
+ if 'context' in user:
298
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
299
+
300
+ # آمار گروه‌ها
301
+ groups_with_context = sum(1 for group in data_manager.DATA['groups'].values()
302
+ if group.get('context') and len(group['context']) > 0)
303
+
304
+ # آمار system instructions
305
+ system_stats = data_manager.DATA['system_instructions']
306
+ group_system_count = len(system_stats.get('groups', {}))
307
+ user_system_count = len(system_stats.get('users', {}))
308
+
309
+ text = (
310
+ f"📊 **آمار ربات**\n\n"
311
+ f"👥 **تعداد کل کاربران:** `{total_users}`\n"
312
+ f"👥 **تعداد کل گروه‌ها:** `{total_groups}`\n"
313
+ f"📝 **تعداد کل پیام‌ها:** `{total_messages}`\n"
314
+ f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
315
+ f"👑 **تعداد ادمین‌ها:** `{total_admins}`\n"
316
+ f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
317
+ f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
318
+ f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
319
+ f"💬 **گروه‌های با context فعال:** `{groups_with_context}`\n"
320
+ f"📝 **کل پیام‌های context:** `{total_context_messages}`\n"
321
+ f"📎 **کل ریپلای‌های ثبت شده:** `{total_replies}`\n"
322
+ f"🔄 **حالت context فعلی:** `{data_manager.get_context_mode()}`\n"
323
+ f"⚙️ **System Instructions گروه‌ها:** `{group_system_count}`\n"
324
+ f"⚙️ **System Instructions کاربران:** `{user_system_count}`\n\n"
325
+ f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
326
+ )
327
+ await update.message.reply_text(text, parse_mode='Markdown')
328
+
329
+ @admin_only
330
+ async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
331
+ """یک پیام را به تمام کاربران ارسال می‌کند."""
332
+ if not context.args:
333
+ await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
334
+ return
335
+
336
+ message_text = " ".join(context.args)
337
+ user_ids = list(data_manager.DATA['users'].keys())
338
+ total_sent = 0
339
+ total_failed = 0
340
+
341
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
342
+
343
+ for user_id_str in user_ids:
344
+ try:
345
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
346
+ total_sent += 1
347
+ await asyncio.sleep(0.05)
348
+ except TelegramError as e:
349
+ logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
350
+ total_failed += 1
351
+
352
+ result_text = (
353
+ f"✅ **ارسال همگانی تمام شد**\n\n"
354
+ f"✅ موفق: `{total_sent}`\n"
355
+ f"❌ ناموفق: `{total_failed}`"
356
+ )
357
+ await update.message.reply_text(result_text, parse_mode='Markdown')
358
+
359
+ @admin_only
360
+ async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
361
+ """ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
362
+ if len(context.args) < 3:
363
+ await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
364
+ "معیارهای موجود: `active_days`, `message_count`, `banned`")
365
+ return
366
+
367
+ criteria = context.args[0].lower()
368
+ value = context.args[1]
369
+ message_text = " ".join(context.args[2:])
370
+
371
+ target_users = []
372
+
373
+ if criteria == "active_days":
374
+ try:
375
+ days = int(value)
376
+ target_users = data_manager.get_active_users(days)
377
+ except ValueError:
378
+ await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
379
+ return
380
+
381
+ elif criteria == "message_count":
382
+ try:
383
+ min_count = int(value)
384
+ target_users = data_manager.get_users_by_message_count(min_count)
385
+ except ValueError:
386
+ await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
387
+ return
388
+
389
+ elif criteria == "banned":
390
+ if value.lower() == "true":
391
+ target_users = list(data_manager.DATA['banned_users'])
392
+ elif value.lower() == "false":
393
+ for user_id in data_manager.DATA['users']:
394
+ if int(user_id) not in data_manager.DATA['banned_users']:
395
+ target_users.append(int(user_id))
396
+ else:
397
+ await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
398
+ return
399
+
400
+ else:
401
+ await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
402
+ return
403
+
404
+ if not target_users:
405
+ await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
406
+ return
407
+
408
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
409
+
410
+ total_sent, total_failed = 0, 0
411
+ for user_id in target_users:
412
+ try:
413
+ await context.bot.send_message(chat_id=user_id, text=message_text)
414
+ total_sent += 1
415
+ await asyncio.sleep(0.05)
416
+ except TelegramError as e:
417
+ logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
418
+ total_failed += 1
419
+
420
+ result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
421
+ await update.message.reply_text(result_text, parse_mode='Markdown')
422
+
423
+ @admin_only
424
+ async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
425
+ """تنظیم ارسال برنامه‌ریزی شده پیام به همه کاربران."""
426
+ if len(context.args) < 3:
427
+ await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
428
+ return
429
+
430
+ try:
431
+ date_str, time_str = context.args[0], context.args[1]
432
+ message_text = " ".join(context.args[2:])
433
+
434
+ scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
435
+
436
+ if scheduled_time <= datetime.now():
437
+ await update.message.reply_text("⚠️ زمان برنامه‌ریزی شده باید در آینده باشد.")
438
+ return
439
+
440
+ data_manager.DATA['scheduled_broadcasts'].append({
441
+ 'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
442
+ 'message': message_text,
443
+ 'status': 'pending'
444
+ })
445
+ data_manager.save_data()
446
+
447
+ await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامه‌ریزی شد.")
448
+
449
+ except ValueError:
450
+ await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
451
+
452
+ @admin_only
453
+ async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
454
+ """نمایش لیست ارسال‌های برنامه‌ریزی شده."""
455
+ if not data_manager.DATA['scheduled_broadcasts']:
456
+ await update.message.reply_text("هیچ ارسال برنامه‌ریزی شده‌ای وجود ندارد.")
457
+ return
458
+
459
+ broadcasts_text = "📅 **لیست ارسال‌های برنامه‌ریزی شده:**\n\n"
460
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
461
+ status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
462
+ broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
463
+
464
+ await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
465
+
466
+ @admin_only
467
+ async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
468
+ """حذف یک ارسال برنامه‌ریزی شده."""
469
+ if not context.args or not context.args[0].isdigit():
470
+ await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامه‌ریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
471
+ return
472
+
473
+ index = int(context.args[0]) - 1
474
+
475
+ if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
476
+ await update.message.reply_text("⚠️ شماره ارسال برنامه‌ریزی شده نامعتبر است.")
477
+ return
478
+
479
+ removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
480
+ data_manager.save_data()
481
+
482
+ await update.message.reply_text(f"✅ ارسال برنامه‌ریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
483
+
484
+ @admin_only
485
+ async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
486
+ """یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع می‌دهد."""
487
+ if not context.args or not context.args[0].isdigit():
488
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
489
+ return
490
+
491
+ user_id_to_ban = int(context.args[0])
492
+
493
+ if is_admin(user_id_to_ban):
494
+ await update.message.reply_text("🛡️ شما نمی‌توانید یک ادمین را مسدود کنید!")
495
+ return
496
+
497
+ if data_manager.is_user_banned(user_id_to_ban):
498
+ await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
499
+ return
500
+
501
+ data_manager.ban_user(user_id_to_ban)
502
+
503
+ # ارسال پیام به کاربر مسدود شده
504
+ try:
505
+ await context.bot.send_message(
506
+ chat_id=user_id_to_ban,
507
+ text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمی‌توانید از خدمات ربات استفاده کنید."
508
+ )
509
+ except TelegramError as e:
510
+ logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
511
+
512
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
513
+
514
+ @admin_only
515
+ async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
516
+ """مسدودیت یک کاربر را برمی‌دارد و به او اطلاع می‌دهد."""
517
+ if not context.args or not context.args[0].isdigit():
518
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
519
+ return
520
+
521
+ user_id_to_unban = int(context.args[0])
522
+
523
+ if not data_manager.is_user_banned(user_id_to_unban):
524
+ await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شده‌ها وجود ندارد.")
525
+ return
526
+
527
+ data_manager.unban_user(user_id_to_unban)
528
+
529
+ # ارسال پیام به کاربر برای رفع مسدودیت
530
+ try:
531
+ await context.bot.send_message(
532
+ chat_id=user_id_to_unban,
533
+ text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. می‌توانید دوباره از ربات استفاده کنید."
534
+ )
535
+ except TelegramError as e:
536
+ logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
537
+
538
+ await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
539
+
540
+ @admin_only
541
+ async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
542
+ """ارسال پیام مستقیم به یک کاربر خاص."""
543
+ if len(context.args) < 2:
544
+ await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
545
+ return
546
+
547
+ user_id_str = context.args[0]
548
+ if not user_id_str.isdigit():
549
+ await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
550
+ return
551
+
552
+ message_text = " ".join(context.args[1:])
553
+ user_id = int(user_id_str)
554
+
555
+ try:
556
+ await context.bot.send_message(chat_id=user_id, text=message_text)
557
+ await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
558
+ except TelegramError as e:
559
+ await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
560
+
561
+ @admin_only
562
+ async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
563
+ """اطلاعات یک کاربر خاص را نمایش می‌دهد."""
564
+ if not context.args or not context.args[0].isdigit():
565
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
566
+ return
567
+
568
+ user_id = int(context.args[0])
569
+ user_info = data_manager.DATA['users'].get(str(user_id))
570
+
571
+ if not user_info:
572
+ await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
573
+ return
574
+
575
+ is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
576
+ is_admin_user = "بله 🔥" if is_super_admin(user_id) else "بله 👤" if is_admin(user_id) else "خیر"
577
+
578
+ if 'first_seen' in user_info and 'last_seen' in user_info:
579
+ try:
580
+ first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
581
+ last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
582
+ days_active = max(1, (last_date - first_date).days)
583
+ avg_messages = user_info.get('message_count', 0) / days_active
584
+ except:
585
+ avg_messages = user_info.get('message_count', 0)
586
+ else:
587
+ avg_messages = user_info.get('message_count', 0)
588
+
589
+ # اطلاعات context
590
+ context_messages = len(user_info.get('context', []))
591
+ context_tokens = data_manager.get_context_token_count(user_id)
592
+
593
+ # اطلاعات ریپلای‌ها
594
+ reply_count = 0
595
+ if 'context' in user_info:
596
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
597
+
598
+ # اطلاعات system instruction
599
+ system_info = data_manager.get_system_instruction_info(user_id=user_id)
600
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'user' else "❌"
601
+ system_type = system_info['type']
602
+
603
+ text = (
604
+ f"ℹ️ **اطلاعات کاربر**\n\n"
605
+ f"🆔 **آیدی:** `{user_id}`\n"
606
+ f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
607
+ f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
608
+ f"👑 **ادمین:** {is_admin_user}\n"
609
+ f"📊 **تعداد پیام‌ها:** `{user_info.get('message_count', 0)}`\n"
610
+ f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
611
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
612
+ f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
613
+ f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
614
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
615
+ f"🔢 **توکن‌های context:** `{context_tokens}`\n"
616
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
617
+ f"🚫 **وضعیت مسدودیت:** {is_banned}"
618
+ )
619
+ await update.message.reply_text(text, parse_mode='Markdown')
620
+
621
+ @admin_only
622
+ async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
623
+ """آخرین خطوط لاگ ربات را ارسال می‌کند."""
624
+ try:
625
+ with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
626
+ lines = f.readlines()
627
+ last_lines = lines[-30:]
628
+ log_text = "".join(last_lines)
629
+ if not log_text:
630
+ await update.message.reply_text("فایل لاگ خالی است.")
631
+ return
632
+
633
+ if len(log_text) > 4096:
634
+ for i in range(0, len(log_text), 4096):
635
+ await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
636
+ else:
637
+ await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
638
+
639
+ except FileNotFoundError:
640
+ await update.message.reply_text("فایل لاگ یافت نشد.")
641
+ except Exception as e:
642
+ await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
643
+
644
+ @admin_only
645
+ async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
646
+ """فایل کامل لاگ ربات را ارسال می‌کند."""
647
+ try:
648
+ await update.message.reply_document(
649
+ document=open(data_manager.LOG_FILE, 'rb'),
650
+ caption="📂 فایل کامل لاگ‌های ربات"
651
+ )
652
+ except FileNotFoundError:
653
+ await update.message.reply_text("فایل لاگ یافت نشد.")
654
+ except Exception as e:
655
+ await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
656
+
657
+ @admin_only
658
+ async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
659
+ """نمایش لیست کامل کاربران با صفحه‌بندی."""
660
+ users = data_manager.DATA['users']
661
+
662
+ page = 1
663
+ if context.args and context.args[0].isdigit():
664
+ page = int(context.args[0])
665
+ if page < 1: page = 1
666
+
667
+ users_per_page = 20
668
+ total_users = len(users)
669
+ total_pages = (total_users + users_per_page - 1) // users_per_page
670
+
671
+ if page > total_pages: page = total_pages
672
+
673
+ start_idx = (page - 1) * users_per_page
674
+ end_idx = min(start_idx + users_per_page, total_users)
675
+
676
+ sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
677
+
678
+ users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
679
+
680
+ for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
681
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
682
+
683
+ # بررسی ادمین بودن
684
+ is_admin_user = ""
685
+ if is_super_admin(int(user_id)):
686
+ is_admin_user = "🔥"
687
+ elif is_admin(int(user_id)):
688
+ is_admin_user = "👑"
689
+
690
+ username = user_info.get('username', 'N/A')
691
+ first_name = user_info.get('first_name', 'N/A')
692
+ last_seen = user_info.get('last_seen', 'N/A')
693
+ message_count = user_info.get('message_count', 0)
694
+ context_count = len(user_info.get('context', []))
695
+
696
+ # تعداد ریپلای‌ها
697
+ reply_count = 0
698
+ if 'context' in user_info:
699
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
700
+
701
+ # system instruction
702
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
703
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
704
+
705
+ users_text += f"{i}. {is_banned} {is_admin_user} {has_system} `{user_id}` - {first_name} (@{username})\n"
706
+ users_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
707
+ users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
708
+
709
+ keyboard = []
710
+ if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
711
+ if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
712
+
713
+ reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
714
+ await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
715
+
716
+ @admin_only
717
+ async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
718
+ """جستجوی کاربر بر اساس نام یا نام کاربری."""
719
+ if not context.args:
720
+ await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
721
+ return
722
+
723
+ search_term = " ".join(context.args).lower()
724
+ users = data_manager.DATA['users']
725
+
726
+ matching_users = []
727
+ for user_id, user_info in users.items():
728
+ first_name = (user_info.get('first_name') or '').lower()
729
+ username = (user_info.get('username') or '').lower()
730
+
731
+ if search_term in first_name or search_term in username:
732
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
733
+
734
+ # بررسی ادمین بودن
735
+ is_admin_user = ""
736
+ if is_super_admin(int(user_id)):
737
+ is_admin_user = "🔥"
738
+ elif is_admin(int(user_id)):
739
+ is_admin_user = "👑"
740
+
741
+ matching_users.append((user_id, user_info, is_banned, is_admin_user))
742
+
743
+ if not matching_users:
744
+ await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
745
+ return
746
+
747
+ results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
748
+
749
+ for user_id, user_info, is_banned, is_admin_user in matching_users:
750
+ username_display = user_info.get('username', 'N/A')
751
+ first_name_display = user_info.get('first_name', 'N/A')
752
+ last_seen = user_info.get('last_seen', 'N/A')
753
+ message_count = user_info.get('message_count', 0)
754
+ context_count = len(user_info.get('context', []))
755
+
756
+ # تعداد ریپلای‌ها
757
+ reply_count = 0
758
+ if 'context' in user_info:
759
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
760
+
761
+ # system instruction
762
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
763
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
764
+
765
+ results_text += f"{is_banned} {is_admin_user} {has_system} `{user_id}` - {first_name_display} (@{username_display})\n"
766
+ results_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
767
+ results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
768
+
769
+ await update.message.reply_text(results_text, parse_mode='Markdown')
770
+
771
+ @admin_only
772
+ async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
773
+ """ایجاد نسخه پشتیبان از داده‌های ربات."""
774
+ try:
775
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
776
+ backup_file = f"bot_backup_{timestamp}.json"
777
+
778
+ data_to_backup = data_manager.DATA.copy()
779
+ data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
780
+
781
+ with open(backup_file, 'w', encoding='utf-8') as f:
782
+ json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
783
+
784
+ await update.message.reply_document(
785
+ document=open(backup_file, 'rb'),
786
+ caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
787
+ )
788
+
789
+ logger.info(f"Backup created: {backup_file}")
790
+ os.remove(backup_file)
791
+ except Exception as e:
792
+ await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
793
+ logger.error(f"Error creating backup: {e}")
794
+
795
+ @admin_only
796
+ async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
797
+ """ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
798
+ users = data_manager.DATA['users']
799
+
800
+ df_data = []
801
+ for user_id, user_info in users.items():
802
+ user_id_int = int(user_id)
803
+ is_banned = "بله" if user_id_int in data_manager.DATA['banned_users'] else "خیر"
804
+
805
+ # وضعیت ادمین
806
+ admin_status = ""
807
+ if is_super_admin(user_id_int):
808
+ admin_status = "ارشد"
809
+ elif is_admin(user_id_int):
810
+ admin_status = "عادی"
811
+ else:
812
+ admin_status = "کاربر"
813
+
814
+ context_count = len(user_info.get('context', []))
815
+ context_tokens = data_manager.get_context_token_count(user_id_int)
816
+
817
+ # تعداد ریپلای‌ها
818
+ reply_count = 0
819
+ if 'context' in user_info:
820
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
821
+
822
+ # system instruction
823
+ system_info = data_manager.get_system_instruction_info(user_id=user_id_int)
824
+ has_system = "بله" if system_info['has_instruction'] and system_info['type'] == 'user' else "خیر"
825
+ system_type = system_info['type']
826
+
827
+ df_data.append({
828
+ 'User ID': user_id,
829
+ 'First Name': user_info.get('first_name', 'N/A'),
830
+ 'Username': user_info.get('username', 'N/A'),
831
+ 'Admin Status': admin_status,
832
+ 'Message Count': user_info.get('message_count', 0),
833
+ 'Context Messages': context_count,
834
+ 'Context Tokens': context_tokens,
835
+ 'Reply Count': reply_count,
836
+ 'Has System Instruction': has_system,
837
+ 'System Type': system_type,
838
+ 'First Seen': user_info.get('first_seen', 'N/A'),
839
+ 'Last Seen': user_info.get('last_seen', 'N/A'),
840
+ 'Banned': is_banned
841
+ })
842
+
843
+ df = pd.DataFrame(df_data)
844
+
845
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
846
+ df.to_csv(f.name, index=False)
847
+ temp_file_path = f.name
848
+
849
+ await update.message.reply_document(
850
+ document=open(temp_file_path, 'rb'),
851
+ caption="📊 فایل CSV اطلاعات کاربران"
852
+ )
853
+
854
+ os.unlink(temp_file_path)
855
+
856
+ @admin_only
857
+ async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
858
+ """حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع می‌دهد."""
859
+ if not context.args or context.args[0].lower() not in ['on', 'off']:
860
+ await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
861
+ return
862
+
863
+ status = context.args[0].lower()
864
+
865
+ if status == 'on':
866
+ if data_manager.DATA.get('maintenance_mode', False):
867
+ await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
868
+ return
869
+
870
+ data_manager.DATA['maintenance_mode'] = True
871
+ data_manager.save_data()
872
+
873
+ await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاع‌رسانی به کاربران...")
874
+
875
+ user_ids = list(data_manager.DATA['users'].keys())
876
+ for user_id_str in user_ids:
877
+ try:
878
+ if int(user_id_str) not in get_admin_ids():
879
+ await context.bot.send_message(
880
+ chat_id=int(user_id_str),
881
+ text="🔧 ربات در حال حاضر در حالت به‌روزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
882
+ )
883
+ await asyncio.sleep(0.05)
884
+ except TelegramError:
885
+ continue
886
+
887
+ elif status == 'off':
888
+ if not data_manager.DATA.get('maintenance_mode', False):
889
+ await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
890
+ return
891
+
892
+ data_manager.DATA['maintenance_mode'] = False
893
+ data_manager.save_data()
894
+
895
+ await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاع‌رسانی به کاربران...")
896
+
897
+ user_ids = list(data_manager.DATA['users'].keys())
898
+ for user_id_str in user_ids:
899
+ try:
900
+ if int(user_id_str) not in get_admin_ids():
901
+ await context.bot.send_message(
902
+ chat_id=int(user_id_str),
903
+ text="✅ به‌روزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! می‌توانید دوباره از ربات استفاده کنید."
904
+ )
905
+ await asyncio.sleep(0.05)
906
+ except TelegramError:
907
+ continue
908
+
909
+ @admin_only
910
+ async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
911
+ """تنظیم پیام خوشامدگویی جدید."""
912
+ if not context.args:
913
+ await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
914
+ "مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
915
+ return
916
+
917
+ new_message = " ".join(context.args)
918
+ data_manager.DATA['welcome_message'] = new_message
919
+ data_manager.save_data()
920
+
921
+ await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت به‌روزرسانی شد.")
922
+
923
+ @admin_only
924
+ async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
925
+ """تنظیم پیام خداحافظ�� جدید."""
926
+ if not context.args:
927
+ await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
928
+ "مثال: `/set_goodbye {user_mention}، خداحافظ!`")
929
+ return
930
+
931
+ new_message = " ".join(context.args)
932
+ data_manager.DATA['goodbye_message'] = new_message
933
+ data_manager.save_data()
934
+
935
+ await update.message.reply_text("✅ پیام خداحافظی با موفقیت به‌روزرسانی شد.")
936
+
937
+ @admin_only
938
+ async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
939
+ """ایجاد و ارسال نمودار فعالیت کاربران."""
940
+ users = data_manager.DATA['users']
941
+ activity_hours = [0] * 24
942
+
943
+ for user_info in users.values():
944
+ if 'last_seen' in user_info:
945
+ try:
946
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
947
+ activity_hours[last_seen.hour] += 1
948
+ except ValueError:
949
+ continue
950
+
951
+ plt.figure(figsize=(12, 6))
952
+ plt.bar(range(24), activity_hours, color='skyblue')
953
+ plt.title('نمودار فعالیت کاربران بر اساس ساعت')
954
+ plt.xlabel('ساعت')
955
+ plt.ylabel('تعداد کاربران فعال')
956
+ plt.xticks(range(24))
957
+ plt.grid(axis='y', alpha=0.3)
958
+
959
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
960
+ plt.savefig(f.name, bbox_inches='tight')
961
+ temp_file_path = f.name
962
+
963
+ plt.close()
964
+
965
+ await update.message.reply_photo(
966
+ photo=open(temp_file_path, 'rb'),
967
+ caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
968
+ )
969
+
970
+ os.unlink(temp_file_path)
971
+
972
+ @admin_only
973
+ async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
974
+ """نمایش آمار زمان پاسخگویی ربات."""
975
+ stats = data_manager.DATA['stats']
976
+ await update.message.reply_text(
977
+ "📈 **آمار زمان پاسخگویی ربات**\n\n"
978
+ f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
979
+ f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
980
+ f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
981
+ f"📊 کل پاسخ‌های ثبت شده: `{stats.get('total_responses', 0)}`"
982
+ )
983
+
984
+ @admin_only
985
+ async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
986
+ """افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
987
+ if not context.args:
988
+ await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
989
+ "مثال: `/add_blocked_word کلمه_نامناسب`")
990
+ return
991
+
992
+ word = " ".join(context.args).lower()
993
+
994
+ if word in data_manager.DATA['blocked_words']:
995
+ await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
996
+ return
997
+
998
+ data_manager.DATA['blocked_words'].append(word)
999
+ data_manager.save_data()
1000
+
1001
+ await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
1002
+
1003
+ @admin_only
1004
+ async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
1005
+ """حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
1006
+ if not context.args:
1007
+ await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
1008
+ "مثال: `/remove_blocked_word کلمه_نامناسب`")
1009
+ return
1010
+
1011
+ word = " ".join(context.args).lower()
1012
+
1013
+ if word not in data_manager.DATA['blocked_words']:
1014
+ await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
1015
+ return
1016
+
1017
+ data_manager.DATA['blocked_words'].remove(word)
1018
+ data_manager.save_data()
1019
+
1020
+ await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
1021
+
1022
+ @admin_only
1023
+ async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
1024
+ """نمایش لیست کلمات مسدود شده."""
1025
+ if not data_manager.DATA['blocked_words']:
1026
+ await update.message.reply_text("هیچ کلمه مسدود شده‌ای در لیست وجود ندارد.")
1027
+ return
1028
+
1029
+ words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
1030
+ await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
1031
+
1032
+ @admin_only
1033
+ async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
1034
+ """��مایش اطلاعات سیستم و منابع."""
1035
+ bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
1036
+ try:
1037
+ bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
1038
+ uptime = datetime.now() - bot_start_time
1039
+ uptime_str = f"{uptime.days} روز, {uptime.seconds // 3600} ساعت, {(uptime.seconds % 3600) // 60} دقیقه"
1040
+ except:
1041
+ uptime_str = "نامشخص"
1042
+
1043
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
1044
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
1045
+
1046
+ # تعداد کل ریپلای‌ها
1047
+ total_replies = 0
1048
+ for user in data_manager.DATA['users'].values():
1049
+ if 'context' in user:
1050
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
1051
+
1052
+ # آمار system instructions
1053
+ system_stats = data_manager.DATA['system_instructions']
1054
+ group_system_count = len(system_stats.get('groups', {}))
1055
+ user_system_count = len(system_stats.get('users', {}))
1056
+
1057
+ # آمار ادمین‌ها
1058
+ env_admins = ENV_ADMIN_IDS
1059
+ added_admins = data_manager.DATA.get('added_admins', [])
1060
+ total_admins = len(env_admins) + len(added_admins)
1061
+
1062
+ system_info = (
1063
+ f"💻 **اطلاعات سیستم:**\n\n"
1064
+ f"🖥️ سیستم‌عامل: {platform.system()} {platform.release()}\n"
1065
+ f"🐍 نسخه پایتون: {platform.python_version()}\n"
1066
+ f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
1067
+ f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
1068
+ f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
1069
+ f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
1070
+ f"⏱️ زمان اجرای ربات: {uptime_str}\n"
1071
+ f"👑 تعداد ادمین‌ها: {total_admins}\n"
1072
+ f"💭 کاربران با context: {users_with_context}\n"
1073
+ f"💬 کل پیام‌های context: {total_context_messages}\n"
1074
+ f"📎 کل ریپلای‌های ثبت شده: {total_replies}\n"
1075
+ f"⚙️ System Instructions گروه‌ها: {group_system_count}\n"
1076
+ f"⚙️ System Instructions کاربران: {user_system_count}"
1077
+ )
1078
+
1079
+ await update.message.reply_text(system_info, parse_mode='Markdown')
1080
+
1081
+ @admin_only
1082
+ async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
1083
+ """ریست کردن آمار ربات."""
1084
+ if not context.args:
1085
+ await update.message.reply_text("⚠️ لطفاً نوع آماری که می‌خواهید ریست کنید را مشخص کنید.\n"
1086
+ "مثال: `/reset_stats messages` یا `/reset_stats all`")
1087
+ return
1088
+
1089
+ stat_type = context.args[0].lower()
1090
+
1091
+ if stat_type == "messages":
1092
+ data_manager.DATA['stats']['total_messages'] = 0
1093
+ for user_id in data_manager.DATA['users']:
1094
+ data_manager.DATA['users'][user_id]['message_count'] = 0
1095
+ await update.message.reply_text("✅ آمار پیام‌ها با موفقیت ریست شد.")
1096
+
1097
+ elif stat_type == "all":
1098
+ data_manager.DATA['stats'] = {
1099
+ 'total_messages': 0,
1100
+ 'total_users': len(data_manager.DATA['users']),
1101
+ 'total_groups': len(data_manager.DATA['groups']),
1102
+ 'avg_response_time': 0,
1103
+ 'max_response_time': 0,
1104
+ 'min_response_time': 0,
1105
+ 'total_responses': 0
1106
+ }
1107
+ for user_id in data_manager.DATA['users']:
1108
+ data_manager.DATA['users'][user_id]['message_count'] = 0
1109
+ await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
1110
+
1111
+ else:
1112
+ await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینه‌های موجود: messages, all")
1113
+ return
1114
+
1115
+ data_manager.save_data()
1116
+
1117
+ # --- دستورات مدیریت context ---
1118
+ @admin_only
1119
+ async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1120
+ """پاک کردن context یک کاربر"""
1121
+ if not context.args or not context.args[0].isdigit():
1122
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
1123
+ return
1124
+
1125
+ user_id = int(context.args[0])
1126
+ data_manager.clear_user_context(user_id)
1127
+
1128
+ await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
1129
+
1130
+ @admin_only
1131
+ async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1132
+ """مشاهده context یک کاربر"""
1133
+ if not context.args or not context.args[0].isdigit():
1134
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
1135
+ return
1136
+
1137
+ user_id = int(context.args[0])
1138
+ user_context = data_manager.get_user_context(user_id)
1139
+
1140
+ if not user_context:
1141
+ await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
1142
+ return
1143
+
1144
+ context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
1145
+ total_tokens = 0
1146
+ reply_count = 0
1147
+
1148
+ for i, msg in enumerate(user_context, 1):
1149
+ role_emoji = "👤" if msg['role'] == 'user' else "🤖"
1150
+ tokens = data_manager.count_tokens(msg['content'])
1151
+ total_tokens += tokens
1152
+
1153
+ # بررسی ریپلای
1154
+ has_reply = msg.get('has_reply', False)
1155
+ if has_reply:
1156
+ reply_count += 1
1157
+ reply_emoji = "📎"
1158
+ else:
1159
+ reply_emoji = ""
1160
+
1161
+ content_preview = msg['content']
1162
+ if len(content_preview) > 100:
1163
+ content_preview = content_preview[:500] + "..."
1164
+
1165
+ context_text += f"{i}. {role_emoji} {reply_emoji} **{msg['role']}** ({tokens} توکن)\n"
1166
+ context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
1167
+
1168
+ if has_reply:
1169
+ context_text += f" 📎 ریپلای به: {msg.get('reply_to_user_name', 'Unknown')}\n"
1170
+
1171
+ context_text += f" 📝 {content_preview}\n\n"
1172
+
1173
+ context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن، {reply_count} ریپلای"
1174
+
1175
+ await update.message.reply_text(context_text, parse_mode='Markdown')
1176
+
1177
+ @admin_only
1178
+ async def admin_view_replies(update: Update, context: ContextTypes.DEFAULT_TYPE):
1179
+ """مشاهده ریپلای‌های یک کاربر یا گروه"""
1180
+ if len(context.args) < 2:
1181
+ await update.message.reply_text(
1182
+ "⚠️ فرمت صحیح: `/view_replies [user|group] [آیدی]`\n"
1183
+ "مثال: `/view_replies user 123456789`\n"
1184
+ "مثال: `/view_replies group -1001234567890`"
1185
+ )
1186
+ return
1187
+
1188
+ entity_type = context.args[0].lower()
1189
+ entity_id = context.args[1]
1190
+
1191
+ if entity_type == 'user':
1192
+ try:
1193
+ user_id = int(entity_id)
1194
+ user_context = data_manager.get_user_context(user_id)
1195
+ if not user_context:
1196
+ await update.message.reply_text(f"کاربر `{entity_id}` context ندارد.")
1197
+ return
1198
+
1199
+ replies = [msg for msg in user_context if msg.get('has_reply', False)]
1200
+
1201
+ if not replies:
1202
+ await update.message.reply_text(f"کاربر `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
1203
+ return
1204
+
1205
+ text = f"📋 **ریپلای‌های کاربر `{entity_id}`**\n\n"
1206
+ for i, msg in enumerate(replies, 1):
1207
+ text += f"{i}. **زمان:** {msg.get('timestamp', 'N/A')}\n"
1208
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
1209
+ if msg.get('is_reply_to_bot', False):
1210
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
1211
+ else:
1212
+ text += f" **نوع:** ریپلای به کاربر\n"
1213
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1214
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1215
+
1216
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1217
+
1218
+ await update.message.reply_text(text, parse_mode='Markdown')
1219
+ except ValueError:
1220
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1221
+
1222
+ elif entity_type == 'group':
1223
+ try:
1224
+ chat_id = int(entity_id)
1225
+ group_context = data_manager.get_group_context(chat_id)
1226
+ if not group_context:
1227
+ await update.message.reply_text(f"گروه `{entity_id}` context ندارد.")
1228
+ return
1229
+
1230
+ replies = [msg for msg in group_context if msg.get('has_reply', False)]
1231
+
1232
+ if not replies:
1233
+ await update.message.reply_text(f"گروه `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
1234
+ return
1235
+
1236
+ text = f"📋 **ریپلای‌های گروه `{entity_id}`**\n\n"
1237
+ for i, msg in enumerate(replies, 1):
1238
+ user_name = msg.get('user_name', 'Unknown')
1239
+ text += f"{i}. **کاربر:** {user_name}\n"
1240
+ text += f" **زمان:** {msg.get('timestamp', 'N/A')}\n"
1241
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
1242
+ if msg.get('is_reply_to_bot', False):
1243
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
1244
+ else:
1245
+ text += f" **نوع:** ریپلای به ک��ربر\n"
1246
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1247
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1248
+
1249
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1250
+
1251
+ await update.message.reply_text(text, parse_mode='Markdown')
1252
+ except ValueError:
1253
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1254
+
1255
+ else:
1256
+ await update.message.reply_text("⚠️ نوع نامعتبر. فقط 'user' یا 'group' مجاز است.")
1257
+
1258
+ # --- دستورات جدید برای مدیریت گروه‌ها ---
1259
+ @admin_only
1260
+ async def admin_set_context_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
1261
+ """تنظیم حالت context ربات"""
1262
+ if not context.args or context.args[0].lower() not in ['separate', 'group_shared', 'hybrid']:
1263
+ await update.message.reply_text(
1264
+ "⚠️ فرمت صحیح: `/set_context_mode [separate|group_shared|hybrid]`\n\n"
1265
+ "• **separate**: هر کاربر context جداگانه دارد (16384 توکن)\n"
1266
+ "• **group_shared**: همه کاربران در یک گروه context مشترک دارند (32768 توکن)\n"
1267
+ "• **hybrid**: ترکیبی از context شخصی و گروهی - بهترین برای بحث‌های گروهی\n\n"
1268
+ "💡 **مزایای Hybrid:**\n"
1269
+ "✅ هر کاربر تاریخچه شخصی خود را دارد\n"
1270
+ "✅ ربات از مکالمات گروه نیز مطلع است\n"
1271
+ "✅ پاسخ‌های دقیق‌تر و شخصی‌سازی شده\n"
1272
+ "✅ برای کار تیمی و بحث‌های پیچیده ایده‌آل\n\n"
1273
+ "🎯 **پیشنهاد:**\n"
1274
+ "- گروه‌های کوچک: Separate\n"
1275
+ "- گروه‌های بحث و تبادل نظر: Hybrid\n"
1276
+ "- گروه‌های آموزشی: Group Shared"
1277
+ )
1278
+ return
1279
+
1280
+ mode = context.args[0].lower()
1281
+ if data_manager.set_context_mode(mode):
1282
+ description = {
1283
+ 'separate': 'هر کاربر تاریخچه جداگانه خود را دارد (16384 توکن). ایده‌آل برای گروه‌های کوچک.',
1284
+ 'group_shared': 'همه کاربران تاریخچه مشترک دارند (32768 توکن). برای بحث‌های گروهی ساده.',
1285
+ 'hybrid': 'ترکیب هوشمند تاریخچه شخصی و گروهی. بهترین انتخاب برای کار تیمی و بحث‌های پیچیده.'
1286
+ }
1287
+
1288
+ await update.message.reply_text(
1289
+ f"✅ حالت context به `{mode}` تغییر یافت.\n\n"
1290
+ f"📝 **توضیحات:**\n{description[mode]}\n\n"
1291
+ f"🔄 تغییرات از پیام بعدی کاربران اعمال خواهد شد."
1292
+ )
1293
+ else:
1294
+ await update.message.reply_text("❌ خطا در تغییر حالت context.")
1295
+
1296
+ @admin_only
1297
+ async def admin_group_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
1298
+ """نمایش اطلاعات یک گروه"""
1299
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1300
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی گروه را وارد کنید.\nمثال: `/group_info -1001234567890`")
1301
+ return
1302
+
1303
+ chat_id = int(context.args[0])
1304
+ group_info = data_manager.DATA['groups'].get(str(chat_id))
1305
+
1306
+ if not group_info:
1307
+ await update.message.reply_text(f"گروهی با آیدی `{chat_id}` در دیتابیس یافت نشد.")
1308
+ return
1309
+
1310
+ # تبدیل set اعضا به لیست برای نمایش
1311
+ members = list(group_info.get('members', set()))
1312
+ members_count = len(members)
1313
+
1314
+ # اطلاعات context گروه
1315
+ context_messages = len(group_info.get('context', []))
1316
+ total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info.get('context', []))
1317
+
1318
+ # تعداد ریپلای‌ها در گروه
1319
+ reply_count = 0
1320
+ if 'context' in group_info:
1321
+ reply_count = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1322
+
1323
+ # system instruction
1324
+ system_info = data_manager.get_system_instruction_info(chat_id=chat_id)
1325
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'group' else "❌"
1326
+ system_type = system_info['type']
1327
+
1328
+ text = (
1329
+ f"📊 **اطلاعات گروه**\n\n"
1330
+ f"🆔 **آیدی:** `{chat_id}`\n"
1331
+ f"🏷️ **عنوان:** {group_info.get('title', 'N/A')}\n"
1332
+ f"📝 **تعداد پیام‌ها:** `{group_info.get('message_count', 0)}`\n"
1333
+ f"👥 **تعداد اعضا:** `{members_count}`\n"
1334
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
1335
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
1336
+ f"�� **توکن‌های context:** `{total_tokens}`\n"
1337
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
1338
+ f"📅 **اولین فعالیت:** {group_info.get('first_seen', 'N/A')}\n"
1339
+ f"🕒 **آخرین فعالیت:** {group_info.get('last_seen', 'N/A')}"
1340
+ )
1341
+
1342
+ await update.message.reply_text(text, parse_mode='Markdown')
1343
+
1344
+ @admin_only
1345
+ async def admin_clear_group_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1346
+ """پاک کردن context یک گروه"""
1347
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1348
+ await update.message.reply_text("⚠️ لطفاً آیدی گروه را وارد کنید.\nمثال: `/clear_group_context -1001234567890`")
1349
+ return
1350
+
1351
+ chat_id = int(context.args[0])
1352
+ data_manager.clear_group_context(chat_id)
1353
+
1354
+ await update.message.reply_text(f"✅ context گروه `{chat_id}` با موفقیت پاک شد.")
1355
+
1356
+ @admin_only
1357
+ async def admin_memory_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
1358
+ """نمایش وضعیت حافظه و context گروه‌ها"""
1359
+ groups = data_manager.DATA['groups']
1360
+
1361
+ if not groups:
1362
+ await update.message.reply_text("هیچ گروهی در دیتابیس وجود ندارد.")
1363
+ return
1364
+
1365
+ # محاسبه آمار
1366
+ total_groups = len(groups)
1367
+ groups_with_context = sum(1 for g in groups.values() if g.get('context'))
1368
+ total_context_messages = sum(len(g.get('context', [])) for g in groups.values())
1369
+ total_context_tokens = 0
1370
+ total_replies = 0
1371
+ groups_with_system = 0
1372
+
1373
+ # آمار کاربران در حالت Hybrid
1374
+ users_in_hybrid = 0
1375
+ if data_manager.get_context_mode() == 'hybrid':
1376
+ users_in_hybrid = len(data_manager.DATA['users'])
1377
+
1378
+ for group_id, group_info in groups.items():
1379
+ if 'context' in group_info:
1380
+ total_context_tokens += sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1381
+ total_replies += sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1382
+
1383
+ # بررسی system instruction
1384
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1385
+ if system_info['has_instruction'] and system_info['type'] == 'group':
1386
+ groups_with_system += 1
1387
+
1388
+ # لیست گروه‌هایی که بیشترین استفاده از حافظه را دارند
1389
+ groups_by_tokens = []
1390
+ for group_id, group_info in groups.items():
1391
+ if 'context' in group_info:
1392
+ tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1393
+ messages = len(group_info['context'])
1394
+ replies = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1395
+
1396
+ # system instruction
1397
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1398
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'group' else ""
1399
+
1400
+ groups_by_tokens.append((group_id, tokens, messages, replies, has_system))
1401
+
1402
+ # مرتب‌سازی بر اساس تعداد توکن
1403
+ groups_by_tokens.sort(key=lambda x: x[1], reverse=True)
1404
+
1405
+ context_mode = data_manager.get_context_mode()
1406
+ mode_info = {
1407
+ 'separate': 'جداگانه (هر کاربر 16384 توکن)',
1408
+ 'group_shared': 'مشترک گروهی (32768 توکن)',
1409
+ 'hybrid': 'ترکیبی (شخصی + گروهی)'
1410
+ }
1411
+
1412
+ status_text = (
1413
+ f"💾 **وضعیت حافظه گروه‌ها**\n\n"
1414
+ f"🎯 **حالت فعلی:** {context_mode} - {mode_info[context_mode]}\n\n"
1415
+ f"📊 **آمار کلی:**\n"
1416
+ f"• تعداد کل گروه‌ها: `{total_groups}`\n"
1417
+ f"• گروه‌های دارای context: `{groups_with_context}`\n"
1418
+ f"• گروه‌های دارای system instruction: `{groups_with_system}`\n"
1419
+ )
1420
+
1421
+ if context_mode == 'hybrid':
1422
+ status_text += f"• کاربران فعال در حالت Hybrid: `{users_in_hybrid}`\n"
1423
+
1424
+ status_text += (
1425
+ f"• کل پیام‌های context: `{total_context_messages}`\n"
1426
+ f"• کل ریپلای‌ها: `{total_replies}`\n"
1427
+ f"• کل توکن‌های استفاده شده: `{total_context_tokens}`\n"
1428
+ f"• میانگین توکن per گروه: `{total_context_tokens/max(1, groups_with_context):.0f}`\n\n"
1429
+ )
1430
+
1431
+ if groups_by_tokens:
1432
+ status_text += f"🏆 **گروه‌های با بیشترین استفاده از حافظه:**\n"
1433
+
1434
+ for i, (group_id, tokens, messages, replies, has_system) in enumerate(groups_by_tokens[:10], 1):
1435
+ usage_percent = (tokens / 32768) * 100
1436
+ status_text += f"{i}. {has_system} گروه `{group_id}`: {messages} پیام، {replies} ریپلای، {tokens} توکن ({usage_percent:.1f}%)\n"
1437
+
1438
+ await update.message.reply_text(status_text, parse_mode='Markdown')
1439
+
1440
+ # --- دستورات مدیریت system instructions ---
1441
+ @admin_only
1442
+ async def admin_set_global_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1443
+ """تنظیم system instruction سراسری"""
1444
+ if not context.args:
1445
+ await update.message.reply_text(
1446
+ "⚠️ لطفاً system instruction سراسری را وارد کنید.\n\n"
1447
+ "مثال: `/set_global_system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n\n"
1448
+ "برای مشاهده وضعیت فعلی: `/system_status`"
1449
+ )
1450
+ return
1451
+
1452
+ instruction_text = " ".join(context.args)
1453
+
1454
+ if data_manager.set_global_system_instruction(instruction_text):
1455
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1456
+ await update.message.reply_text(
1457
+ f"✅ system instruction سراسری تنظیم شد:\n\n"
1458
+ f"{instruction_preview}\n\n"
1459
+ f"این دستور برای تمام کاربران و گروه‌هایی که دستور خاصی ندارند اعمال خواهد شد."
1460
+ )
1461
+ else:
1462
+ await update.message.reply_text("❌ خطا در تنظیم system instruction سراسری.")
1463
+
1464
+ @admin_only
1465
+ async def admin_set_group_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1466
+ """تنظیم system instruction برای گروه"""
1467
+ if len(context.args) < 2:
1468
+ await update.message.reply_text(
1469
+ "⚠️ فرمت صحیح: `/set_group_system [آیدی گروه] [متن]`\n\n"
1470
+ "مثال: `/set_group_system -1001234567890 تو در این گروه فقط باید به سوالات فنی پاسخ بدهی.`"
1471
+ )
1472
+ return
1473
+
1474
+ chat_id_str = context.args[0]
1475
+ if not chat_id_str.lstrip('-').isdigit():
1476
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1477
+ return
1478
+
1479
+ chat_id = int(chat_id_str)
1480
+ instruction_text = " ".join(context.args[1:])
1481
+ user_id = update.effective_user.id
1482
+
1483
+ if data_manager.set_group_system_instruction(chat_id, instruction_text, user_id):
1484
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1485
+ await update.message.reply_text(
1486
+ f"✅ system instruction برای گروه `{chat_id}` تنظیم شد:\n\n"
1487
+ f"{instruction_preview}"
1488
+ )
1489
+ else:
1490
+ await update.message.reply_text("❌ خطا در تنظیم system instruction گروه.")
1491
+
1492
+ @admin_only
1493
+ async def admin_set_user_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1494
+ """تنظیم system instruction برای کاربر"""
1495
+ if len(context.args) < 2:
1496
+ await update.message.reply_text(
1497
+ "⚠️ فرمت صحیح: `/set_user_system [آیدی کاربر] [متن]`\n\n"
1498
+ "مثال: `/set_user_system 123456789 تو برای این کاربر باید به زبان ساده و با مثال پاسخ بدهی.`"
1499
+ )
1500
+ return
1501
+
1502
+ user_id_str = context.args[0]
1503
+ if not user_id_str.isdigit():
1504
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1505
+ return
1506
+
1507
+ user_id = int(user_id_str)
1508
+ instruction_text = " ".join(context.args[1:])
1509
+ admin_id = update.effective_user.id
1510
+
1511
+ if data_manager.set_user_system_instruction(user_id, instruction_text, admin_id):
1512
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1513
+ await update.message.reply_text(
1514
+ f"✅ system instruction برای کاربر `{user_id}` تنظیم شد:\n\n"
1515
+ f"{instruction_preview}"
1516
+ )
1517
+ else:
1518
+ await update.message.reply_text("❌ خطا در تنظیم system instruction کاربر.")
1519
+
1520
+ @admin_only
1521
+ async def admin_list_system_instructions(update: Update, context: ContextTypes.DEFAULT_TYPE):
1522
+ """نمایش لیست system instruction‌ها - فقط برای ادمین‌های ربات"""
1523
+ system_data = data_manager.DATA['system_instructions']
1524
+
1525
+ # نمایش system instruction سراسری
1526
+ global_instruction = system_data.get('global', '')
1527
+ global_preview = global_instruction[:150] + "..." if len(global_instruction) > 150 else global_instruction
1528
+
1529
+ text = (
1530
+ f"🌐 **Global System Instruction:**\n{global_preview}\n\n"
1531
+ f"⚠️ **توجه:** این اطلاعات فقط برای ادمین‌های ربات نمایش داده می‌شود.\n"
1532
+ f"ادمین‌های گروه فقط می‌توانند system instruction گروه خودشان را مشاهده کنند.\n\n"
1533
+ )
1534
+
1535
+ # نمایش system instruction گروه‌ها
1536
+ groups = system_data.get('groups', {})
1537
+ if groups:
1538
+ text += f"👥 **System Instruction گروه‌ها ({len(groups)}):**\n"
1539
+
1540
+ for i, (chat_id, group_data) in enumerate(groups.items(), 1):
1541
+ instruction = group_data.get('instruction', '')
1542
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1543
+ set_by = group_data.get('set_by', 'نامشخص')
1544
+ enabled = "✅" if group_data.get('enabled', True) else "❌"
1545
+
1546
+ text += f"{i}. گروه `{chat_id}` {enabled}\n"
1547
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1548
+ text += f" 📝 {preview}\n\n"
1549
+
1550
+ # نمایش system instruction کاربران
1551
+ users = system_data.get('users', {})
1552
+ if users:
1553
+ text += f"👤 **System Instruction کاربران ({len(users)}):**\n"
1554
+
1555
+ for i, (user_id, user_data) in enumerate(users.items(), 1):
1556
+ instruction = user_data.get('instruction', '')
1557
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1558
+ set_by = user_data.get('set_by', 'نامشخص')
1559
+ enabled = "✅" if user_data.get('enabled', True) else "❌"
1560
+
1561
+ text += f"{i}. کاربر `{user_id}` {enabled}\n"
1562
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1563
+ text += f" 📝 {preview}\n\n"
1564
+
1565
+ if not groups and not users:
1566
+ text += "⚠️ هیچ system instruction خاصی (گروهی یا کاربری) تنظیم شده است."
1567
+
1568
+ await update.message.reply_text(text, parse_mode='Markdown')
1569
+
1570
+ # --- هندلر برای دکمه‌های صفحه‌بندی ---
1571
+ async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
1572
+ """پردازش دکمه‌های صفحه‌بندی لیست کاربران."""
1573
+ query = update.callback_query
1574
+ await query.answer()
1575
+
1576
+ if query.data.startswith("users_list:"):
1577
+ page = int(query.data.split(":")[1])
1578
+ context.args = [str(page)]
1579
+ await admin_users_list(update, context)
1580
+
1581
+ # --- تابع برای پردازش ارسال‌های برنامه‌ریزی شده ---
1582
+ async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
1583
+ """پردازش ارسال‌های برنامه‌ریزی شده و ارسال پیام‌ها در زمان مقرر."""
1584
+ now = datetime.now()
1585
+ broadcasts_to_send_indices = []
1586
+
1587
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
1588
+ if broadcast['status'] == 'pending':
1589
+ broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
1590
+ if broadcast_time <= now:
1591
+ broadcasts_to_send_indices.append(i)
1592
+
1593
+ if not broadcasts_to_send_indices:
1594
+ return
1595
+
1596
+ user_ids = list(data_manager.DATA['users'].keys())
1597
+
1598
+ for index in broadcasts_to_send_indices:
1599
+ broadcast = data_manager.DATA['scheduled_broadcasts'][index]
1600
+ message_text = broadcast['message']
1601
+ total_sent, total_failed = 0, 0
1602
+
1603
+ for user_id_str in user_ids:
1604
+ try:
1605
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
1606
+ total_sent += 1
1607
+ await asyncio.sleep(0.05)
1608
+ except TelegramError as e:
1609
+ logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
1610
+ total_failed += 1
1611
+
1612
+ # به‌روزرسانی وضعیت ارسال
1613
+ data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
1614
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
1615
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
1616
+ data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
1617
+
1618
+ logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
1619
+
1620
+ data_manager.save_data()
1621
+
1622
+ # --- تابع راه‌اندازی هندلرها ---
1623
+ def setup_admin_handlers(application):
1624
+ """هندلرهای پنل ادمین را به اپلیکیشن اضافه می‌کند."""
1625
+ # هندلرهای اصلی
1626
+ application.add_handler(CommandHandler("commands", admin_commands))
1627
+ application.add_handler(CommandHandler("stats", admin_stats))
1628
+ application.add_handler(CommandHandler("broadcast", admin_broadcast))
1629
+ application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
1630
+ application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
1631
+ application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
1632
+ application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
1633
+ application.add_handler(CommandHandler("ban", admin_ban))
1634
+ application.add_handler(CommandHandler("unban", admin_unban))
1635
+ application.add_handler(CommandHandler("direct_message", admin_direct_message))
1636
+ application.add_handler(CommandHandler("user_info", admin_userinfo))
1637
+ application.add_handler(CommandHandler("logs", admin_logs))
1638
+ application.add_handler(CommandHandler("logs_file", admin_logs_file))
1639
+ application.add_handler(CommandHandler("users_list", admin_users_list))
1640
+ application.add_handler(CommandHandler("user_search", admin_user_search))
1641
+ application.add_handler(CommandHandler("backup", admin_backup))
1642
+ application.add_handler(CommandHandler("export_csv", admin_export_csv))
1643
+ application.add_handler(CommandHandler("maintenance", admin_maintenance))
1644
+ application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
1645
+ application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
1646
+ application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
1647
+ application.add_handler(CommandHandler("response_stats", admin_response_stats))
1648
+ application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
1649
+ application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
1650
+ application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
1651
+ application.add_handler(CommandHandler("system_info", admin_system_info))
1652
+ application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
1653
+
1654
+ # هندلرهای مدیریت context
1655
+ application.add_handler(CommandHandler("clear_context", admin_clear_context))
1656
+ application.add_handler(CommandHandler("view_context", admin_view_context))
1657
+ application.add_handler(CommandHandler("view_replies", admin_view_replies))
1658
+
1659
+ # هندلرهای جدید برای مدیریت گروه‌ها
1660
+ application.add_handler(CommandHandler("set_context_mode", admin_set_context_mode))
1661
+ application.add_handler(CommandHandler("group_info", admin_group_info))
1662
+ application.add_handler(CommandHandler("clear_group_context", admin_clear_group_context))
1663
+ application.add_handler(CommandHandler("memory_status", admin_memory_status))
1664
+
1665
+ # هندلرهای system instruction
1666
+ application.add_handler(CommandHandler("set_global_system", admin_set_global_system))
1667
+ application.add_handler(CommandHandler("set_group_system", admin_set_group_system))
1668
+ application.add_handler(CommandHandler("set_user_system", admin_set_user_system))
1669
+ application.add_handler(CommandHandler("list_system_instructions", admin_list_system_instructions))
1670
+
1671
+ # هندلرهای مدیریت ادمین‌ها
1672
+ application.add_handler(CommandHandler("add_admin_bot", admin_add_admin_bot))
1673
+ application.add_handler(CommandHandler("remove_admin_bot", admin_remove_admin_bot))
1674
+ application.add_handler(CommandHandler("list_admins", admin_list_admins))
1675
+
1676
+ # هندلر برای دکمه‌های صفحه‌بندی
1677
+ application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
1678
+
1679
+ # شروع وظیفه دوره‌ای برای بررسی ارسال‌های برنامه‌ریزی شده
1680
+ application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
1681
+
1682
+ logger.info("Admin panel handlers have been set up.")
BOT/2/data_manager.py ADDED
@@ -0,0 +1,871 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # data_manager.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ from datetime import datetime, timedelta
7
+ import tiktoken
8
+ import threading
9
+
10
+ # --- افزودن قفل برای ایمنی thread-safe ---
11
+ DATA_LOCK = threading.Lock()
12
+
13
+
14
+ # --- تنظیمات مسیر فایل‌ها ---
15
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
16
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
17
+ LOG_FILE = os.path.join(BASE_DIR, "bot.log")
18
+
19
+ # --- کش داده‌های گلوبال ---
20
+ DATA = {
21
+ "users": {},
22
+ "groups": {},
23
+ "banned_users": set(),
24
+ "stats": {
25
+ "total_messages": 0,
26
+ "total_users": 0,
27
+ "total_groups": 0,
28
+ "avg_response_time": 0.0,
29
+ "max_response_time": 0.0,
30
+ "min_response_time": float('inf'),
31
+ "total_responses": 0
32
+ },
33
+ "welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
34
+ "group_welcome_message": "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید",
35
+ "goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
36
+ "maintenance_mode": False,
37
+ "blocked_words": [],
38
+ "scheduled_broadcasts": [],
39
+ "bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
40
+ "context_mode": "separate",
41
+ "system_instructions": {
42
+ "global": "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد. از کلمات فارسی صحیح استفاده کنید و در صورت نیاز توضیحات کامل ارائه دهید.",
43
+ "groups": {},
44
+ "users": {}
45
+ }
46
+ }
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ # --- توابع کمکی ---
51
+ def count_tokens(text: str) -> int:
52
+ """شمارش تعداد توکن‌های متن با استفاده از tokenizer"""
53
+ try:
54
+ encoding = tiktoken.get_encoding("cl100k_base")
55
+ return len(encoding.encode(text))
56
+ except Exception as e:
57
+ logger.warning(f"Error counting tokens: {e}, using fallback")
58
+ return max(1, len(text) // 4)
59
+
60
+ def load_data():
61
+ """داده‌ها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره می‌کند."""
62
+ global DATA
63
+ with DATA_LOCK:
64
+ try:
65
+ if not os.path.exists(DATA_FILE):
66
+ logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد می‌شود.")
67
+ save_data()
68
+ return
69
+
70
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
71
+ loaded_data = json.load(f)
72
+ loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
73
+
74
+ # اطمینان از وجود کلیدهای جدید
75
+ if 'groups' not in loaded_data: loaded_data['groups'] = {}
76
+ if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'separate'
77
+ if 'group_welcome_message' not in loaded_data:
78
+ loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..."
79
+ if 'total_groups' not in loaded_data.get('stats', {}):
80
+ if 'stats' not in loaded_data: loaded_data['stats'] = {}
81
+ loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {}))
82
+
83
+ # تبدیل اعضای گروه از list به set
84
+ for group_id in loaded_data.get('groups', {}):
85
+ if 'members' in loaded_data['groups'][group_id]:
86
+ # اگر members یک list است، آن را به set تبدیل کن
87
+ if isinstance(loaded_data['groups'][group_id]['members'], list):
88
+ loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members'])
89
+ elif not isinstance(loaded_data['groups'][group_id]['members'], set):
90
+ # اگر نه list است نه set، آن را set خالی کن
91
+ loaded_data['groups'][group_id]['members'] = set()
92
+ else:
93
+ loaded_data['groups'][group_id]['members'] = set()
94
+
95
+ # اطمینان از وجود context برای گروه‌های قدیمی
96
+ for group_id in loaded_data.get('groups', {}):
97
+ if 'context' not in loaded_data['groups'][group_id]:
98
+ loaded_data['groups'][group_id]['context'] = []
99
+
100
+ # اطمینان از وجود context برای کاربران قدیمی
101
+ for user_id in loaded_data.get('users', {}):
102
+ if 'context' not in loaded_data['users'][user_id]:
103
+ loaded_data['users'][user_id]['context'] = []
104
+
105
+ # اطمینان از وجود کلیدهای آمار پاسخگویی
106
+ if 'stats' in loaded_data:
107
+ stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses']
108
+ for key in stats_keys:
109
+ if key not in loaded_data['stats']:
110
+ if key == 'min_response_time':
111
+ loaded_data['stats'][key] = float('inf')
112
+ else:
113
+ loaded_data['stats'][key] = 0.0
114
+
115
+ # اطمینان از وجود system_instructions
116
+ if 'system_instructions' not in loaded_data:
117
+ loaded_data['system_instructions'] = {
118
+ 'global': DATA['system_instructions']['global'],
119
+ 'groups': {},
120
+ 'users': {}
121
+ }
122
+
123
+ if 'added_admins' not in loaded_data:
124
+ loaded_data['added_admins'] = []
125
+
126
+ DATA.update(loaded_data)
127
+ logger.info(f"داده‌ها با موفقیت از {DATA_FILE} بارگذاری شدند.")
128
+
129
+ except json.JSONDecodeError as e:
130
+ logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
131
+ except Exception as e:
132
+ logger.error(f"خطای غیرمنتظره هنگام بارگذاری داده‌ها: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
133
+
134
+ def save_data():
135
+ """کش گلوبال داده‌ها را در فایل JSON ذخیره می‌کند."""
136
+ global DATA
137
+ try:
138
+ data_to_save = DATA.copy()
139
+ data_to_save['banned_users'] = list(DATA['banned_users'])
140
+
141
+ # تبدیل set اعضای گروه به list برای ذخیره JSON
142
+ for group_id in data_to_save.get('groups', {}):
143
+ if 'members' in data_to_save['groups'][group_id]:
144
+ # اگر members یک set است، آن را به list تبدیل کن
145
+ if isinstance(data_to_save['groups'][group_id]['members'], set):
146
+ data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members'])
147
+ elif not isinstance(data_to_save['groups'][group_id]['members'], list):
148
+ # اگر نه set است نه list، آن را list خالی کن
149
+ data_to_save['groups'][group_id]['members'] = []
150
+
151
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
152
+ json.dump(data_to_save, f, indent=4, ensure_ascii=False)
153
+ logger.debug(f"داده‌ها با موفقیت در {DATA_FILE} ذخیره شدند.")
154
+ except Exception as e:
155
+ logger.error(f"خطای مهلک: امکان ذخیره داده‌ها در {DATA_FILE} وجود ندارد. خطا: {e}")
156
+
157
+ # --- توابع مدیریت کاربران ---
158
+ def update_user_stats(user_id: int, user):
159
+ """آمار کاربر را پس از هر پیام به‌روز کرده و داده‌ها را ذخیره می‌کند."""
160
+ global DATA
161
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
162
+ user_id_str = str(user_id)
163
+
164
+ if user_id_str not in DATA['users']:
165
+ DATA['users'][user_id_str] = {
166
+ 'first_name': user.first_name,
167
+ 'username': user.username,
168
+ 'first_seen': now_str,
169
+ 'message_count': 0,
170
+ 'context': []
171
+ }
172
+ DATA['stats']['total_users'] += 1
173
+ logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
174
+
175
+ DATA['users'][user_id_str]['last_seen'] = now_str
176
+ DATA['users'][user_id_str]['message_count'] += 1
177
+ DATA['stats']['total_messages'] += 1
178
+
179
+ save_data()
180
+
181
+ def update_response_stats(response_time: float):
182
+ """آمار زمان پاسخگویی را به‌روز می‌کند."""
183
+ global DATA
184
+
185
+ if DATA['stats']['total_responses'] == 0:
186
+ DATA['stats']['min_response_time'] = response_time
187
+
188
+ DATA['stats']['total_responses'] += 1
189
+
190
+ # محاسبه میانگین جدید
191
+ current_avg = DATA['stats']['avg_response_time']
192
+ total_responses = DATA['stats']['total_responses']
193
+ new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
194
+ DATA['stats']['avg_response_time'] = new_avg
195
+
196
+ # به‌روزرسانی حداکثر و حداقل زمان پاسخگویی
197
+ if response_time > DATA['stats']['max_response_time']:
198
+ DATA['stats']['max_response_time'] = response_time
199
+
200
+ if response_time < DATA['stats']['min_response_time']:
201
+ DATA['stats']['min_response_time'] = response_time
202
+
203
+ save_data()
204
+
205
+ # --- توابع مدیریت مسدودیت ---
206
+ def is_user_banned(user_id: int) -> bool:
207
+ """بررسی می‌کند آیا کاربر مسدود شده است یا خیر."""
208
+ return user_id in DATA['banned_users']
209
+
210
+ def ban_user(user_id: int):
211
+ """کاربر را مسدود کرده و ذخیره می‌کند."""
212
+ DATA['banned_users'].add(user_id)
213
+ save_data()
214
+
215
+ def unban_user(user_id: int):
216
+ """مسدودیت کاربر را برداشته و ذخیره می‌کند."""
217
+ DATA['banned_users'].discard(user_id)
218
+ save_data()
219
+
220
+ def contains_blocked_words(text: str) -> bool:
221
+ """بررسی می‌کند آیا متن حاوی کلمات مسدود شده است یا خیر."""
222
+ if not DATA['blocked_words']:
223
+ return False
224
+
225
+ text_lower = text.lower()
226
+ for word in DATA['blocked_words']:
227
+ if word in text_lower:
228
+ return True
229
+
230
+ return False
231
+
232
+ # --- توابع مدیریت کاربران و گروه‌ها ---
233
+ def get_active_users(days: int) -> list:
234
+ """لیست کاربران فعال در بازه زمانی مشخص را برمی‌گرداند."""
235
+ now = datetime.now()
236
+ cutoff_date = now - timedelta(days=days)
237
+
238
+ active_users = []
239
+ for user_id, user_info in DATA['users'].items():
240
+ if 'last_seen' in user_info:
241
+ try:
242
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
243
+ if last_seen >= cutoff_date:
244
+ active_users.append(int(user_id))
245
+ except ValueError:
246
+ continue
247
+
248
+ return active_users
249
+
250
+ def get_users_by_message_count(min_count: int) -> list:
251
+ """لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمی‌گرداند."""
252
+ users = []
253
+ for user_id, user_info in DATA['users'].items():
254
+ if user_info.get('message_count', 0) >= min_count:
255
+ users.append(int(user_id))
256
+
257
+ return users
258
+
259
+ # --- توابع مدیریت context کاربران ---
260
+ def add_to_user_context(user_id: int, role: str, content: str):
261
+ """اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن"""
262
+ add_to_user_context_with_reply(user_id, role, content, None)
263
+
264
+ def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None):
265
+ """اضافه کردن پیام به context کاربر با اطلاعات ریپلای"""
266
+ user_id_str = str(user_id)
267
+
268
+ if user_id_str not in DATA['users']:
269
+ return
270
+
271
+ if 'context' not in DATA['users'][user_id_str]:
272
+ DATA['users'][user_id_str]['context'] = []
273
+
274
+ # اضافه کردن پیام جدید
275
+ message = {
276
+ 'role': role,
277
+ 'content': content,
278
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
279
+ 'has_reply': False
280
+ }
281
+
282
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
283
+ message['has_reply'] = True
284
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
285
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
286
+ message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
287
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
288
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
289
+
290
+ DATA['users'][user_id_str]['context'].append(message)
291
+
292
+ # محدود کردن context به 16384 توکن
293
+ trim_user_context(user_id, max_tokens=16384)
294
+
295
+ save_data()
296
+
297
+ def trim_user_context(user_id: int, max_tokens: int = 16384):
298
+ """کوتاه کردن context کاربر به تعداد توکن مشخص"""
299
+ user_id_str = str(user_id)
300
+
301
+ if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
302
+ return
303
+
304
+ context = DATA['users'][user_id_str]['context']
305
+
306
+ if not context:
307
+ return
308
+
309
+ # محاسبه توکن‌های کل
310
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
311
+
312
+ # حذف قدیمی‌ترین پیام‌ها تا زمانی که توکن‌ها زیر حد مجاز باشد
313
+ while total_tokens > max_tokens and len(context) > 1:
314
+ removed_message = context.pop(0)
315
+ total_tokens -= count_tokens(removed_message['content'])
316
+
317
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
318
+ if total_tokens > max_tokens and context:
319
+ last_message = context[-1]
320
+ content = last_message['content']
321
+
322
+ tokens = count_tokens(content)
323
+ if tokens > max_tokens:
324
+ context.pop()
325
+ else:
326
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
327
+ words = content.split()
328
+ if len(words) > 1:
329
+ content = ' '.join(words[:-1])
330
+ else:
331
+ content = content[:-1] if len(content) > 1 else ''
332
+ tokens = count_tokens(content)
333
+
334
+ if content:
335
+ context[-1]['content'] = content
336
+ else:
337
+ context.pop()
338
+
339
+ save_data()
340
+
341
+ def get_user_context(user_id: int) -> list:
342
+ """دریافت context کاربر"""
343
+ user_id_str = str(user_id)
344
+
345
+ if user_id_str not in DATA['users']:
346
+ return []
347
+
348
+ return DATA['users'][user_id_str].get('context', [])
349
+
350
+ def clear_user_context(user_id: int):
351
+ """پاک کردن context کاربر"""
352
+ user_id_str = str(user_id)
353
+
354
+ if user_id_str in DATA['users']:
355
+ if 'context' in DATA['users'][user_id_str]:
356
+ DATA['users'][user_id_str]['context'] = []
357
+ save_data()
358
+ logger.info(f"Context cleared for user {user_id}")
359
+
360
+ def get_context_summary(user_id: int) -> str:
361
+ """خلاصه‌ای از context کاربر"""
362
+ context = get_user_context(user_id)
363
+ if not context:
364
+ return "بدون تاریخچه"
365
+
366
+ total_messages = len(context)
367
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
368
+
369
+ # تعداد ریپلای‌ها
370
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
371
+
372
+ # نمایش آخرین پیام
373
+ last_message = context[-1] if context else {}
374
+ last_content = last_message.get('content', '')[:50]
375
+ if len(last_message.get('content', '')) > 50:
376
+ last_content += "..."
377
+
378
+ return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}"
379
+
380
+ def get_context_for_api(user_id: int) -> list:
381
+ """فرمت context برای ارسال به API"""
382
+ context = get_user_context(user_id)
383
+
384
+ api_context = []
385
+ for msg in context:
386
+ api_context.append({
387
+ 'role': msg['role'],
388
+ 'content': msg['content']
389
+ })
390
+
391
+ return api_context
392
+
393
+ def get_context_token_count(user_id: int) -> int:
394
+ """تعداد کل توکن‌های context کاربر"""
395
+ context = get_user_context(user_id)
396
+ return sum(count_tokens(msg['content']) for msg in context)
397
+
398
+ # --- توابع مدیریت گروه‌ها ---
399
+ def update_group_stats(chat_id: int, chat, user_id: int = None):
400
+ """آمار گروه را به‌روز کرده و داده‌ها را ذخیره می‌کند."""
401
+ global DATA
402
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
403
+ chat_id_str = str(chat_id)
404
+
405
+ if chat_id_str not in DATA['groups']:
406
+ DATA['groups'][chat_id_str] = {
407
+ 'title': chat.title if hasattr(chat, 'title') else 'Private Group',
408
+ 'type': chat.type,
409
+ 'first_seen': now_str,
410
+ 'message_count': 0,
411
+ 'members': set(),
412
+ 'context': []
413
+ }
414
+ DATA['stats']['total_groups'] += 1
415
+ logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})")
416
+
417
+ DATA['groups'][chat_id_str]['last_seen'] = now_str
418
+ DATA['groups'][chat_id_str]['message_count'] += 1
419
+
420
+ # اضافه کردن کاربر به لیست اعضای گروه
421
+ if user_id is not None:
422
+ # اطمینان از اینکه members یک set است
423
+ if 'members' not in DATA['groups'][chat_id_str]:
424
+ DATA['groups'][chat_id_str]['members'] = set()
425
+ elif isinstance(DATA['groups'][chat_id_str]['members'], list):
426
+ # اگر members یک list است، آن را به set تبدیل کن
427
+ DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members'])
428
+
429
+ # اکنون اضافه کردن کاربر
430
+ DATA['groups'][chat_id_str]['members'].add(user_id)
431
+
432
+ save_data()
433
+
434
+ def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None):
435
+ """اضافه کردن پیام به context گروه و محدود کردن به 16384 توکن"""
436
+ add_to_group_context_with_reply(chat_id, role, content, user_name, None)
437
+
438
+ def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None):
439
+ """اضافه کردن پیام به context گروه با اطلاعات ریپلای"""
440
+ chat_id_str = str(chat_id)
441
+
442
+ if chat_id_str not in DATA['groups']:
443
+ return
444
+
445
+ if 'context' not in DATA['groups'][chat_id_str]:
446
+ DATA['groups'][chat_id_str]['context'] = []
447
+
448
+ # اضافه کردن نام کاربر به محتوا اگر مشخص باشد
449
+ if user_name and role == 'user':
450
+ content_with_name = f"{user_name}: {content}"
451
+ else:
452
+ content_with_name = content
453
+
454
+ # اضافه کردن پیام جدید با اطلاعات ریپلای
455
+ message = {
456
+ 'role': role,
457
+ 'content': content_with_name if role == 'user' else content,
458
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
459
+ 'user_name': user_name if role == 'user' else None,
460
+ 'has_reply': False
461
+ }
462
+
463
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
464
+ message['has_reply'] = True
465
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
466
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
467
+ message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
468
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
469
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
470
+
471
+ DATA['groups'][chat_id_str]['context'].append(message)
472
+
473
+ # محدود کردن context به 32768 توکن
474
+ trim_group_context(chat_id, max_tokens=32768)
475
+
476
+ save_data()
477
+
478
+ def optimize_group_context(chat_id: int):
479
+ """بهینه‌سازی context گروه برای حفظ مهم‌ترین پیام‌ها"""
480
+ chat_id_str = str(chat_id)
481
+
482
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
483
+ return
484
+
485
+ context = DATA['groups'][chat_id_str]['context']
486
+ if len(context) <= 10:
487
+ return
488
+
489
+ # محاسبه اهمیت هر پیام بر اساس عوامل مختلف
490
+ scored_messages = []
491
+ for i, msg in enumerate(context):
492
+ score = 0
493
+
494
+ # امتیاز بر اساس طول
495
+ content_length = len(msg['content'])
496
+ score += min(content_length / 100, 10)
497
+
498
+ # امتیاز بر اساس تازگی
499
+ recency = len(context) - i
500
+ score += min(recency / 10, 20)
501
+
502
+ # امتیاز بیشتر برای پاسخ‌های هوش مصنوعی
503
+ if msg['role'] == 'assistant':
504
+ score += 15
505
+
506
+ # امتیاز بیشتر برای پیام‌های دارای ریپلای (مهم‌تر هستند)
507
+ if msg.get('has_reply', False):
508
+ score += 10
509
+
510
+ # امتیاز منفی برای پیام‌های کوتاه و کم‌محتوا
511
+ if content_length < 20:
512
+ score -= 5
513
+
514
+ scored_messages.append((score, msg))
515
+
516
+ # مرتب‌سازی بر اساس امتیاز
517
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
518
+
519
+ # حفظ 70% از پیام‌های با بالاترین امتیاز
520
+ keep_count = int(len(scored_messages) * 0.9)
521
+ kept_messages = [msg for _, msg in scored_messages[:keep_count]]
522
+
523
+ # مرتب‌سازی مجدد بر اساس زمان
524
+ kept_messages.sort(key=lambda x: x.get('timestamp', ''))
525
+
526
+ DATA['groups'][chat_id_str]['context'] = kept_messages
527
+ save_data()
528
+
529
+ logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages")
530
+
531
+ def trim_group_context(chat_id: int, max_tokens: int = 32768):
532
+ """کوتاه کردن context گروه به تعداد توکن مشخص"""
533
+ chat_id_str = str(chat_id)
534
+
535
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
536
+ return
537
+
538
+ context = DATA['groups'][chat_id_str]['context']
539
+
540
+ if not context:
541
+ return
542
+
543
+ # محاسبه توکن‌های کل
544
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
545
+
546
+ # اگر تعداد توکن‌ها بیش از حد مجاز است، ابتدا بهینه‌سازی کن
547
+ if total_tokens > max_tokens * 1.5:
548
+ optimize_group_context(chat_id)
549
+ context = DATA['groups'][chat_id_str]['context']
550
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
551
+
552
+ # حذف قدیمی‌ترین پیام‌ها
553
+ while total_tokens > max_tokens and len(context) > 1:
554
+ removed_message = context.pop(0)
555
+ total_tokens -= count_tokens(removed_message['content'])
556
+
557
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
558
+ if total_tokens > max_tokens and context:
559
+ last_message = context[-1]
560
+ content = last_message['content']
561
+
562
+ tokens = count_tokens(content)
563
+ if tokens > max_tokens:
564
+ context.pop()
565
+ else:
566
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
567
+ words = content.split()
568
+ if len(words) > 1:
569
+ content = ' '.join(words[:-1])
570
+ else:
571
+ content = content[:-1] if len(content) > 1 else ''
572
+ tokens = count_tokens(content)
573
+
574
+ if content:
575
+ context[-1]['content'] = content
576
+ else:
577
+ context.pop()
578
+
579
+ save_data()
580
+
581
+ def get_group_context(chat_id: int) -> list:
582
+ """دریافت context گروه"""
583
+ chat_id_str = str(chat_id)
584
+
585
+ if chat_id_str not in DATA['groups']:
586
+ return []
587
+
588
+ return DATA['groups'][chat_id_str].get('context', [])
589
+
590
+ def get_context_for_api_group(chat_id: int) -> list:
591
+ """فرمت context گروه برای ارسال به API"""
592
+ context = get_group_context(chat_id)
593
+
594
+ api_context = []
595
+ for msg in context:
596
+ api_context.append({
597
+ 'role': msg['role'],
598
+ 'content': msg['content']
599
+ })
600
+
601
+ return api_context
602
+
603
+ def clear_group_context(chat_id: int):
604
+ """پاک کردن context گروه"""
605
+ chat_id_str = str(chat_id)
606
+
607
+ if chat_id_str in DATA['groups']:
608
+ if 'context' in DATA['groups'][chat_id_str]:
609
+ DATA['groups'][chat_id_str]['context'] = []
610
+ save_data()
611
+ logger.info(f"Context cleared for group {chat_id}")
612
+
613
+ def get_group_context_summary(chat_id: int) -> str:
614
+ """خلاصه‌ای از context گروه"""
615
+ context = get_group_context(chat_id)
616
+ if not context:
617
+ return "بدون تاریخچه"
618
+
619
+ total_messages = len(context)
620
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
621
+
622
+ # تعداد ریپلای‌ها
623
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
624
+
625
+ last_message = context[-1] if context else {}
626
+ last_content = last_message.get('content', '')[:50]
627
+ if len(last_message.get('content', '')) > 50:
628
+ last_content += "..."
629
+
630
+ return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('user_name', last_message.get('role', ''))}: {last_content}"
631
+
632
+ # --- توابع ترکیبی (User + Group) ---
633
+ def add_to_hybrid_context(user_id: int, chat_id: int, role: str, content: str, user_name: str = None):
634
+ """
635
+ اضافه کردن پیام به context ترکیبی
636
+ هم در context کاربر و هم در context گروه ذخیره می‌شود
637
+ """
638
+ # ذخیره در context کاربر
639
+ add_to_user_context(user_id, role, content)
640
+
641
+ # ذخیره در context گروه
642
+ add_to_group_context(chat_id, role, content, user_name)
643
+
644
+ def add_to_hybrid_context_with_reply(user_id: int, chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None):
645
+ """
646
+ اضافه کردن پیام به context ترکیبی با اطلاعات ریپلای
647
+ هم در context کاربر و هم در context گروه ذخیره می‌شود
648
+ """
649
+ # ذخیره در context کاربر
650
+ add_to_user_context_with_reply(user_id, role, content, reply_info)
651
+
652
+ # ذخیره در context گروه
653
+ add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info)
654
+
655
+ def get_hybrid_context_for_api(user_id: int, chat_id: int) -> list:
656
+ """
657
+ دریافت context ترکیبی برای ارسال به API
658
+ ترکیب هوشمندانه context کاربر و گروه
659
+ """
660
+ group_context = get_context_for_api_group(chat_id)
661
+ user_context = get_context_for_api(user_id)
662
+
663
+ # ترکیب context‌ها به صورت هوشمند
664
+ combined_context = []
665
+
666
+ # ابتدا system instruction (اگر در context گروه یا کاربر وجود دارد)
667
+ system_messages = []
668
+ for msg in group_context:
669
+ if msg['role'] == 'system':
670
+ system_messages.append(msg)
671
+
672
+ for msg in user_context:
673
+ if msg['role'] == 'system' and msg not in system_messages:
674
+ system_messages.append(msg)
675
+
676
+ # اضافه کردن system instruction‌ها
677
+ combined_context.extend(system_messages)
678
+
679
+ # ترکیب پیام‌های گروه و کاربر
680
+ # برای حفظ جریان مکالمه، به ترتیب زمانی ترکیب می‌کنیم
681
+ all_messages = []
682
+
683
+ # پیام‌های گروه با اطلاعات زمان
684
+ for msg in group_context:
685
+ if msg['role'] != 'system':
686
+ all_messages.append({
687
+ 'source': 'group',
688
+ 'role': msg['role'],
689
+ 'content': msg['content'],
690
+ 'timestamp': msg.get('timestamp', '')
691
+ })
692
+
693
+ # پیام‌های کاربر با اطلاعات زمان
694
+ for msg in user_context:
695
+ if msg['role'] != 'system':
696
+ all_messages.append({
697
+ 'source': 'user',
698
+ 'role': msg['role'],
699
+ 'content': msg['content'],
700
+ 'timestamp': msg.get('timestamp', '')
701
+ })
702
+
703
+ # مرتب‌سازی بر اساس زمان
704
+ all_messages.sort(key=lambda x: x.get('timestamp', ''))
705
+
706
+ # محدود کردن به 30 پیام آخر برای حفظ کارایی
707
+ recent_messages = all_messages[-30:] if len(all_messages) > 30 else all_messages
708
+
709
+ # تبدیل به فرمت API
710
+ for msg in recent_messages:
711
+ # در حالت hybrid، نام کاربر در محتوای پیام‌های user ذخیره می‌شود
712
+ if msg['source'] == 'group' and 'user_name:' in msg['content']:
713
+ # پیام‌های گروه که حاوی نام کارب�� هستند
714
+ combined_context.append({
715
+ 'role': msg['role'],
716
+ 'content': msg['content']
717
+ })
718
+ elif msg['source'] == 'user':
719
+ # پیام‌های شخصی کاربر
720
+ combined_context.append({
721
+ 'role': msg['role'],
722
+ 'content': msg['content']
723
+ })
724
+
725
+ # اگر تعداد پیام‌ها کم است، از context گروه استفاده کن
726
+ if len(combined_context) < 5 and group_context:
727
+ # فقط پیام‌های اخیر گروه
728
+ recent_group = [msg for msg in group_context if msg['role'] != 'system'][-10:]
729
+ combined_context.extend(recent_group)
730
+
731
+ return combined_context
732
+
733
+ # --- توابع مدیریت حالت context ---
734
+ def get_context_mode() -> str:
735
+ """دریافت حالت فعلی context"""
736
+ return DATA.get('context_mode', 'separate')
737
+
738
+ def set_context_mode(mode: str):
739
+ """تنظیم حالت context"""
740
+ valid_modes = ['separate', 'group_shared', 'hybrid']
741
+ if mode in valid_modes:
742
+ DATA['context_mode'] = mode
743
+ save_data()
744
+ logger.info(f"Context mode changed to: {mode}")
745
+ return True
746
+ return False
747
+
748
+ # --- توابع مدیریت system instructions ---
749
+ def get_system_instruction(user_id: int = None, chat_id: int = None) -> str:
750
+ """دریافت system instruction مناسب برای کاربر/گروه"""
751
+ # اولویت: کاربر > گروه > سراسری
752
+ user_id_str = str(user_id) if user_id else None
753
+ chat_id_str = str(chat_id) if chat_id else None
754
+
755
+ # بررسی برای کاربر
756
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
757
+ instruction_data = DATA['system_instructions']['users'][user_id_str]
758
+ if instruction_data.get('enabled', True):
759
+ return instruction_data.get('instruction', '')
760
+
761
+ # بررسی برای گروه
762
+ if chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
763
+ instruction_data = DATA['system_instructions']['groups'][chat_id_str]
764
+ if instruction_data.get('enabled', True):
765
+ return instruction_data.get('instruction', '')
766
+
767
+ # بازگشت به حالت سراسری
768
+ return DATA['system_instructions'].get('global', '')
769
+
770
+ def set_global_system_instruction(instruction: str) -> bool:
771
+ """تنظیم system instruction سراسری"""
772
+ DATA['system_instructions']['global'] = instruction
773
+ save_data()
774
+ return True
775
+
776
+ def set_group_system_instruction(chat_id: int, instruction: str, set_by_user_id: int) -> bool:
777
+ """تنظیم system instruction برای گروه"""
778
+ chat_id_str = str(chat_id)
779
+ DATA['system_instructions']['groups'][chat_id_str] = {
780
+ 'instruction': instruction,
781
+ 'set_by': set_by_user_id,
782
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
783
+ 'enabled': True
784
+ }
785
+ save_data()
786
+ return True
787
+
788
+ def set_user_system_instruction(user_id: int, instruction: str, set_by_user_id: int) -> bool:
789
+ """تنظیم system instruction برای کاربر"""
790
+ user_id_str = str(user_id)
791
+ DATA['system_instructions']['users'][user_id_str] = {
792
+ 'instruction': instruction,
793
+ 'set_by': set_by_user_id,
794
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
795
+ 'enabled': True
796
+ }
797
+ save_data()
798
+ return True
799
+
800
+ def remove_group_system_instruction(chat_id: int) -> bool:
801
+ """حذف system instruction گروه"""
802
+ chat_id_str = str(chat_id)
803
+ if chat_id_str in DATA['system_instructions']['groups']:
804
+ del DATA['system_instructions']['groups'][chat_id_str]
805
+ save_data()
806
+ return True
807
+ return False
808
+
809
+ def remove_user_system_instruction(user_id: int) -> bool:
810
+ """حذف system instruction کاربر"""
811
+ user_id_str = str(user_id)
812
+ if user_id_str in DATA['system_instructions']['users']:
813
+ del DATA['system_instructions']['users'][user_id_str]
814
+ save_data()
815
+ return True
816
+ return False
817
+
818
+ def toggle_group_system_instruction(chat_id: int, enabled: bool) -> bool:
819
+ """فعال/غیرفعال کردن system instruction گروه"""
820
+ chat_id_str = str(chat_id)
821
+ if chat_id_str in DATA['system_instructions']['groups']:
822
+ DATA['system_instructions']['groups'][chat_id_str]['enabled'] = enabled
823
+ save_data()
824
+ return True
825
+ return False
826
+
827
+ def toggle_user_system_instruction(user_id: int, enabled: bool) -> bool:
828
+ """فعال/غیرفعال کردن system instruction کاربر"""
829
+ user_id_str = str(user_id)
830
+ if user_id_str in DATA['system_instructions']['users']:
831
+ DATA['system_instructions']['users'][user_id_str]['enabled'] = enabled
832
+ save_data()
833
+ return True
834
+ return False
835
+
836
+ def get_system_instruction_info(user_id: int = None, chat_id: int = None) -> dict:
837
+ """دریافت اطلاعات system instruction"""
838
+ user_id_str = str(user_id) if user_id else None
839
+ chat_id_str = str(chat_id) if chat_id else None
840
+
841
+ result = {
842
+ 'has_instruction': False,
843
+ 'type': 'global',
844
+ 'instruction': DATA['system_instructions'].get('global', ''),
845
+ 'details': None
846
+ }
847
+
848
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
849
+ user_data = DATA['system_instructions']['users'][user_id_str]
850
+ result.update({
851
+ 'has_instruction': True,
852
+ 'type': 'user',
853
+ 'instruction': user_data.get('instruction', ''),
854
+ 'details': user_data
855
+ })
856
+ elif chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
857
+ group_data = DATA['system_instructions']['groups'][chat_id_str]
858
+ result.update({
859
+ 'has_instruction': True,
860
+ 'type': 'group',
861
+ 'instruction': group_data.get('instruction', ''),
862
+ 'details': group_data
863
+ })
864
+
865
+ return result
866
+
867
+ # بارگذاری اولیه داده‌ها
868
+ load_data()
869
+
870
+ # برای جلوگیری از خطای time در توابع
871
+ import time
BOT/2/fix_data.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fix_data.py
2
+ import json
3
+ import os
4
+
5
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
6
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
7
+
8
+ def fix_data_file():
9
+ """رفع مشکلات فایل داده‌های موجود"""
10
+ if not os.path.exists(DATA_FILE):
11
+ print(f"فایل داده در {DATA_FILE} یافت نشد.")
12
+ return
13
+
14
+ try:
15
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
16
+ data = json.load(f)
17
+
18
+ # رفع مشکل banned_users
19
+ if 'banned_users' in data and isinstance(data['banned_users'], list):
20
+ data['banned_users'] = list(set(data['banned_users'])) # حذف duplicates
21
+
22
+ # رفع مشکل groups و members
23
+ if 'groups' in data:
24
+ for group_id, group_info in data['groups'].items():
25
+ # رفع مشکل members
26
+ if 'members' in group_info:
27
+ if isinstance(group_info['members'], list):
28
+ # تبدیل list به set و سپس دوباره به list (حذف duplicates)
29
+ members_set = set(group_info['members'])
30
+ group_info['members'] = list(members_set)
31
+ elif isinstance(group_info['members'], set):
32
+ # اگر set است، به list تبدیل کن
33
+ group_info['members'] = list(group_info['members'])
34
+ else:
35
+ # اگر نه list است نه set، آن را list خالی کن
36
+ group_info['members'] = []
37
+
38
+ # اطمینان از وجود کلیدهای ضروری
39
+ if 'context' not in group_info:
40
+ group_info['context'] = []
41
+ if 'title' not in group_info:
42
+ group_info['title'] = 'Unknown Group'
43
+ if 'type' not in group_info:
44
+ group_info['type'] = 'group'
45
+
46
+ # رفع مشکل users
47
+ if 'users' in data:
48
+ for user_id, user_info in data['users'].items():
49
+ if 'context' not in user_info:
50
+ user_info['context'] = []
51
+
52
+ # ذخیره فایل اصلاح شده
53
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
54
+ json.dump(data, f, indent=4, ensure_ascii=False)
55
+
56
+ print(f"فایل داده در {DATA_FILE} با موفقیت اصلاح شد.")
57
+
58
+ # نمایش آمار
59
+ print("\n📊 آمار فایل اصلاح شده:")
60
+ print(f"تعداد کاربران: {len(data.get('users', {}))}")
61
+ print(f"تعداد گروه‌ها: {len(data.get('groups', {}))}")
62
+ print(f"کاربران مسدود شده: {len(data.get('banned_users', []))}")
63
+
64
+ # بررسی groups
65
+ groups_with_member_issues = 0
66
+ for group_id, group_info in data.get('groups', {}).items():
67
+ if 'members' in group_info and not isinstance(group_info['members'], list):
68
+ groups_with_member_issues += 1
69
+
70
+ if groups_with_member_issues > 0:
71
+ print(f"⚠️ {groups_with_member_issues} گروه دارای مشکل در members هستند.")
72
+ else:
73
+ print("✅ همه groups به درستی اصلاح شدند.")
74
+
75
+ except Exception as e:
76
+ print(f"خطا در اصلاح فایل داده: {e}")
77
+
78
+ if __name__ == "__main__":
79
+ fix_data_file()
BOT/2/keep_alive.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import threading
3
+ import time
4
+
5
+ def ping_service():
6
+ """ارسال درخواست پینگ به سرویس برای نگه داشتن آن فعال."""
7
+ url = "https://render-telegram-bot-2-bmin.onrender.com"
8
+ while True:
9
+ try:
10
+ requests.get(url)
11
+ print(f"Pinged {url} to keep service alive")
12
+ except Exception as e:
13
+ print(f"Error pinging service: {e}")
14
+
15
+ # هر 14 دقیقه یک بار پینگ بزن (زیر 15 دقیقه برای جلوگیری از خاموشی)
16
+ time.sleep(5 * 60)
17
+
18
+ # شروع ترد پینگ در پس‌زمینه
19
+ def start_keep_alive():
20
+ """شروع سرویس نگه داشتن ربات فعال."""
21
+ thread = threading.Thread(target=ping_service)
22
+ thread.daemon = True
23
+ thread.start()
BOT/2/main.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import asyncio
4
+ import httpx
5
+ import time
6
+ from telegram import Update
7
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
8
+ from openai import AsyncOpenAI
9
+ from keep_alive import start_keep_alive
10
+
11
+ # وارد کردن مدیر داده‌ها و پنل ادمین
12
+ import data_manager
13
+ import admin_panel
14
+ import system_instruction_handlers
15
+
16
+ # بارگذاری داده‌ها در ابتدا
17
+ data_manager.load_data()
18
+
19
+ # شروع سرویس نگه داشتن ربات فعال
20
+ start_keep_alive()
21
+
22
+ # --- بهبود لاگینگ ---
23
+ logging.basicConfig(
24
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
25
+ level=logging.INFO,
26
+ filename=data_manager.LOG_FILE,
27
+ filemode='a'
28
+ )
29
+ logger = logging.getLogger(__name__)
30
+
31
+ try:
32
+ with open(data_manager.LOG_FILE, 'a') as f:
33
+ f.write("")
34
+ except Exception as e:
35
+ print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
36
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
37
+
38
+ # --- ایجاد یک کلاینت HTTP بهینه‌سازی‌شده ---
39
+ http_client = httpx.AsyncClient(
40
+ http2=True,
41
+ limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
42
+ timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
43
+ )
44
+
45
+ # کلاینت OpenAI (HuggingFace)
46
+ client = AsyncOpenAI(
47
+ base_url="https://router.huggingface.co/v1",
48
+ api_key=os.environ["HF_TOKEN"],
49
+ http_client=http_client
50
+ )
51
+
52
+ # --- دیکشنری برای مدیریت وظایف پس‌زمینه هر کاربر ---
53
+ user_tasks = {} # برای چت خصوصی: {user_id: task}
54
+ user_group_tasks = {} # برای گروه: {(chat_id, user_id): task}
55
+ # ساختار user_group_tasks: کلید ترکیبی از chat_id و user_id برای هر کاربر در هر گروه
56
+
57
+ # --- توابع کمکی برای مدیریت ریپلای ---
58
+ def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple:
59
+ """استخراج اطلاعات از ریپلای"""
60
+ message = update.message
61
+
62
+ # اگر ریپلای وجود نداشت
63
+ if not message or not message.reply_to_message:
64
+ return None, None, None, None
65
+
66
+ replied_message = message.reply_to_message
67
+
68
+ # اطلاعات پیام ریپلای شده
69
+ replied_user_id = replied_message.from_user.id if replied_message.from_user else None
70
+ replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown"
71
+
72
+ # استخراج متن پیام ریپلای شده
73
+ replied_text = ""
74
+ if replied_message.text:
75
+ replied_text = replied_message.text
76
+ elif replied_message.caption:
77
+ replied_text = replied_message.caption
78
+
79
+ # بررسی اینکه آیا ریپلای به ربات است
80
+ is_reply_to_bot = False
81
+ if replied_message.from_user:
82
+ # بررسی اینکه آیا پیام از خود ربات است
83
+ if replied_message.from_user.is_bot:
84
+ is_reply_to_bot = True
85
+ # یا آیا پیام حاوی منشن ربات است
86
+ elif context.bot and context.bot.username and replied_message.text:
87
+ if f"@{context.bot.username}" in replied_message.text:
88
+ is_reply_to_bot = True
89
+
90
+ return replied_user_id, replied_user_name, replied_text, is_reply_to_bot
91
+
92
+ def format_reply_message(user_message: str, replied_user_name: str, replied_text: str, is_reply_to_bot: bool = False, current_user_name: str = None) -> str:
93
+ """فرمت‌دهی پیام با در نظر گرفتن ریپلای"""
94
+ if not replied_text:
95
+ return user_message
96
+
97
+ # محدود کردن طول متن ریپلای شده
98
+ if len(replied_text) > 100:
99
+ replied_preview = replied_text[:97] + "..."
100
+ else:
101
+ replied_preview = replied_text
102
+
103
+ # حذف منشن ربات از متن ریپلای شده اگر وجود دارد
104
+ replied_preview = replied_preview.replace("@", "(at)") # جایگزین موقت برای جلوگیری از منشن
105
+
106
+ if is_reply_to_bot:
107
+ # ریپلای به ربات
108
+ if current_user_name:
109
+ return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}"
110
+ else:
111
+ return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}"
112
+ else:
113
+ # ریپلای به کاربر دیگر
114
+ if current_user_name:
115
+ return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
116
+ else:
117
+ return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
118
+
119
+ def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot):
120
+ """ایجاد دیکشنری اطلاعات ریپلای"""
121
+ if not replied_text:
122
+ return None
123
+
124
+ return {
125
+ 'replied_user_id': replied_user_id,
126
+ 'replied_user_name': replied_user_name,
127
+ 'replied_text': replied_text[:1500], # محدود کردن طول
128
+ 'is_reply_to_bot': is_reply_to_bot,
129
+ 'timestamp': time.time()
130
+ }
131
+
132
+ # --- توابع کمکی برای مدیریت وظایف ---
133
+ def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int):
134
+ if task_id in task_dict and task_dict[task_id] == task:
135
+ del task_dict[task_id]
136
+ logger.info(f"Cleaned up finished task for ID {task_id}.")
137
+ try:
138
+ exception = task.exception()
139
+ if exception:
140
+ logger.error(f"Background task for ID {task_id} failed: {exception}")
141
+ except asyncio.CancelledError:
142
+ logger.info(f"Task for ID {task_id} was cancelled.")
143
+ except asyncio.InvalidStateError:
144
+ pass
145
+
146
+ def _cleanup_user_group_task(task: asyncio.Task, chat_id: int, user_id: int):
147
+ """پاک‌سازی وظایف کاربران در گروه"""
148
+ task_key = (chat_id, user_id)
149
+ if task_key in user_group_tasks and user_group_tasks[task_key] == task:
150
+ del user_group_tasks[task_key]
151
+ logger.info(f"Cleaned up finished task for group {chat_id}, user {user_id}.")
152
+ try:
153
+ exception = task.exception()
154
+ if exception:
155
+ logger.error(f"Background task for group {chat_id}, user {user_id} failed: {exception}")
156
+ except asyncio.CancelledError:
157
+ logger.info(f"Task for group {chat_id}, user {user_id} was cancelled.")
158
+ except asyncio.InvalidStateError:
159
+ pass
160
+
161
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
162
+ """پردازش درخواست کاربر در چت خصوصی"""
163
+ chat_id = update.effective_chat.id
164
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
165
+ user_id = update.effective_user.id
166
+
167
+ if not user_message:
168
+ logger.warning(f"No message content for user {user_id}")
169
+ return
170
+
171
+ # اگر reply_info از بیرون داده نشده، استخراج کن
172
+ if reply_info is None:
173
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
174
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
175
+
176
+ # اگر ریپلای وجود داشت، متن را فرمت کن
177
+ if reply_info and reply_info.get('replied_text'):
178
+ formatted_message = format_reply_message(
179
+ user_message,
180
+ reply_info.get('replied_user_name', 'Unknown'),
181
+ reply_info.get('replied_text'),
182
+ reply_info.get('is_reply_to_bot', False)
183
+ )
184
+ else:
185
+ formatted_message = user_message
186
+
187
+ start_time = time.time()
188
+
189
+ try:
190
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
191
+
192
+ # دریافت context کاربر
193
+ user_context = data_manager.get_context_for_api(user_id)
194
+
195
+ # اضافه کردن پیام کاربر به context (با فرمت ریپلای اگر وجود داشت)
196
+ data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
197
+
198
+ # دریافت system instruction
199
+ system_instruction = data_manager.get_system_instruction(user_id=user_id)
200
+
201
+ # ایجاد لیست پیام‌ها برای API
202
+ messages = []
203
+
204
+ # اضافه کردن system instruction اگر وجود دارد
205
+ if system_instruction:
206
+ messages.append({"role": "system", "content": system_instruction})
207
+
208
+ messages.extend(user_context.copy())
209
+ messages.append({"role": "user", "content": formatted_message})
210
+
211
+ logger.info(f"User {user_id} sending {len(messages)} messages to AI")
212
+ if reply_info and reply_info.get('replied_text'):
213
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
214
+
215
+ response = await client.chat.completions.create(
216
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
217
+ messages=messages,
218
+ temperature=0.7,
219
+ top_p=0.95,
220
+ stream=False,
221
+ )
222
+
223
+ end_time = time.time()
224
+ response_time = end_time - start_time
225
+ data_manager.update_response_stats(response_time)
226
+
227
+ ai_response = response.choices[0].message.content
228
+
229
+ # اضافه کردن پاسخ هوش مصنوعی به context
230
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
231
+
232
+ await update.message.reply_text(ai_response)
233
+ data_manager.update_user_stats(user_id, update.effective_user)
234
+
235
+ except httpx.TimeoutException:
236
+ logger.warning(f"Request timed out for user {user_id}.")
237
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
238
+ except Exception as e:
239
+ logger.error(f"Error while processing message for user {user_id}: {e}")
240
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
241
+
242
+ async def _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
243
+ """پردازش درخواست در گروه"""
244
+ chat_id = update.effective_chat.id
245
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
246
+ user_id = update.effective_user.id
247
+ user_name = update.effective_user.first_name
248
+
249
+ if not user_message:
250
+ logger.warning(f"No message content for group {chat_id}, user {user_id}")
251
+ return
252
+
253
+ # اگر reply_info از بیرون داده نشده، استخراج کن
254
+ if reply_info is None:
255
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
256
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
257
+
258
+ # اگر ریپلای وجود داشت، متن را فرمت کن
259
+ if reply_info and reply_info.get('replied_text'):
260
+ formatted_message = format_reply_message(
261
+ user_message,
262
+ reply_info.get('replied_user_name', 'Unknown'),
263
+ reply_info.get('replied_text'),
264
+ reply_info.get('is_reply_to_bot', False),
265
+ user_name
266
+ )
267
+ else:
268
+ formatted_message = user_message
269
+
270
+ start_time = time.time()
271
+
272
+ try:
273
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
274
+
275
+ # بررسی حالت context
276
+ context_mode = data_manager.get_context_mode()
277
+
278
+ if context_mode == 'group_shared':
279
+ # حالت مشترک گروه: فقط از context گروه استفاده می‌شود
280
+ messages = data_manager.get_context_for_api_group(chat_id)
281
+ data_manager.add_to_group_context_with_reply(chat_id, "user", formatted_message, user_name, reply_info)
282
+
283
+ elif context_mode == 'hybrid':
284
+ # حالت ترکیبی: از context ترکیبی استفاده می‌شود
285
+ messages = data_manager.get_hybrid_context_for_api(user_id, chat_id)
286
+ # ذخیره در هر دو context
287
+ data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "user", formatted_message, user_name, reply_info)
288
+
289
+ else: # separate (پیش‌فرض)
290
+ # حالت جداگانه: هر کاربر context خودش را دارد
291
+ messages = data_manager.get_context_for_api(user_id)
292
+ data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
293
+
294
+ # دریافت system instruction مناسب
295
+ system_instruction = data_manager.get_system_instruction(user_id=user_id, chat_id=chat_id)
296
+
297
+ # اضافه کردن system instruction به ابتدای messages
298
+ if system_instruction:
299
+ # اگر system instruction وجود دارد، آن را به ابتدای لیست اضافه کن
300
+ messages_with_system = [{"role": "system", "content": system_instruction}]
301
+ messages_with_system.extend(messages)
302
+ messages = messages_with_system
303
+
304
+ # اضافه کردن پیام جدید
305
+ if context_mode == 'group_shared':
306
+ messages.append({"role": "user", "content": f"{user_name}: {formatted_message}"})
307
+ elif context_mode == 'hybrid':
308
+ # در حالت hybrid، نام کاربر در محتوا ذخیره می‌شود
309
+ messages.append({"role": "user", "content": f"{user_name}: {formatted_message}"})
310
+ else:
311
+ messages.append({"role": "user", "content": formatted_message})
312
+
313
+ logger.info(f"Group {chat_id} - User {user_id} ({context_mode} mode) sending {len(messages)} messages to AI")
314
+ if reply_info and reply_info.get('replied_text'):
315
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
316
+
317
+ response = await client.chat.completions.create(
318
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
319
+ messages=messages,
320
+ temperature=0.7,
321
+ top_p=0.95,
322
+ stream=False,
323
+ )
324
+
325
+ end_time = time.time()
326
+ response_time = end_time - start_time
327
+ data_manager.update_response_stats(response_time)
328
+
329
+ ai_response = response.choices[0].message.content
330
+
331
+ # ذخیره پاسخ بر اساس حالت context
332
+ if context_mode == 'group_shared':
333
+ data_manager.add_to_group_context(chat_id, "assistant", ai_response)
334
+ elif context_mode == 'hybrid':
335
+ # در حالت hybrid، پاسخ در هر دو context ذخیره می‌شود
336
+ data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "assistant", ai_response, None, None)
337
+ else:
338
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
339
+
340
+ # به‌روزرسانی آمار گروه با user_id
341
+ data_manager.update_group_stats(chat_id, update.effective_chat, user_id)
342
+
343
+ # پاسخ مستقیم به کاربر با ریپلای به پیام او
344
+ await update.message.reply_text(
345
+ ai_response,
346
+ reply_to_message_id=update.message.message_id
347
+ )
348
+
349
+ except httpx.TimeoutException:
350
+ logger.warning(f"Request timed out for group {chat_id}, user {user_id}.")
351
+ await update.message.reply_text(
352
+ "⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.",
353
+ reply_to_message_id=update.message.message_id
354
+ )
355
+ except Exception as e:
356
+ logger.error(f"Error while processing message for group {chat_id}, user {user_id}: {e}")
357
+ await update.message.reply_text(
358
+ "❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
359
+ reply_to_message_id=update.message.message_id
360
+ )
361
+
362
+ # --- هندلرهای اصلی ربات ---
363
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
364
+ user = update.effective_user
365
+ user_id = user.id
366
+ chat = update.effective_chat
367
+
368
+ if chat.type in ['group', 'supergroup']:
369
+ # در گروه
370
+ data_manager.update_group_stats(chat.id, chat, user_id)
371
+
372
+ welcome_msg = data_manager.DATA.get('group_welcome_message',
373
+ "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیام‌ها ریپلای کنید")
374
+
375
+ context_mode = data_manager.get_context_mode()
376
+ mode_info = ""
377
+ if context_mode == 'group_shared':
378
+ mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده می‌شود. همه کاربران تاریخچه مکالمه یکسانی دارند (تا 32768 توکن)."
379
+ elif context_mode == 'hybrid':
380
+ mode_info = "\n\n📝 **نکته:** در این گروه از context ترکیبی استفاده می‌شود."
381
+
382
+ # نمایش اطلاعات system instruction گروه
383
+ system_info = data_manager.get_system_instruction_info(chat_id=chat.id)
384
+ if system_info['type'] == 'group' and system_info['has_instruction']:
385
+ instruction_preview = system_info['instruction'][:100] + "..." if len(system_info['instruction']) > 100 else system_info['instruction']
386
+ mode_info += f"\n\n⚙️ **سیستم‌اینستراکشن:**\n{instruction_preview}"
387
+
388
+ await update.message.reply_html(
389
+ welcome_msg + mode_info,
390
+ disable_web_page_preview=True
391
+ )
392
+ else:
393
+ # در چت خصوصی
394
+ data_manager.update_user_stats(user_id, user)
395
+
396
+ welcome_msg = data_manager.DATA.get('welcome_message',
397
+ "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\n\n💡 **نکته:** می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.")
398
+
399
+ await update.message.reply_html(
400
+ welcome_msg.format(user_mention=user.mention_html()),
401
+ disable_web_page_preview=True
402
+ )
403
+
404
+ async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
405
+ """پاک کردن تاریخچه چت"""
406
+ user_id = update.effective_user.id
407
+ chat = update.effective_chat
408
+
409
+ if chat.type in ['group', 'supergroup']:
410
+ # پاک کردن context گروه
411
+ data_manager.clear_group_context(chat.id)
412
+
413
+ context_mode = data_manager.get_context_mode()
414
+ if context_mode == 'group_shared':
415
+ await update.message.reply_text(
416
+ "🧹 تاریخچه مکالمه گروه پاک شد.\n"
417
+ "از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد."
418
+ )
419
+ else:
420
+ await update.message.reply_text(
421
+ "🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n"
422
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
423
+ )
424
+ else:
425
+ # پاک کردن context کاربر
426
+ data_manager.clear_user_context(user_id)
427
+
428
+ await update.message.reply_text(
429
+ "🧹 تاریخچه مکالمه شما پاک شد.\n"
430
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
431
+ )
432
+
433
+ async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
434
+ """نمایش اطلاعات context"""
435
+ user_id = update.effective_user.id
436
+ chat = update.effective_chat
437
+
438
+ if chat.type in ['group', 'supergroup']:
439
+ context_mode = data_manager.get_context_mode()
440
+
441
+ if context_mode == 'group_shared':
442
+ context_summary = data_manager.get_group_context_summary(chat.id)
443
+ await update.message.reply_text(
444
+ f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n"
445
+ f"{context_summary}\n\n"
446
+ f"**حالت:** مشترک بین همه اعضای گروه\n"
447
+ f"**سقف توکن:** 32768 توکن\n"
448
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
449
+ )
450
+ elif context_mode == 'hybrid':
451
+ hybrid_summary = data_manager.get_hybrid_context_summary(user_id, chat.id)
452
+ await update.message.reply_text(
453
+ f"📊 **اطلاعات تاریخچه مکالمه (حالت ترکیبی):**\n\n"
454
+ f"{hybrid_summary}\n\n"
455
+ f"**توضیحات:** در این حالت هم تاریخچه شخصی شما و هم تاریخچه گروه ذخیره می‌شود.\n"
456
+ f"• تاریخچه شخصی: تا 16384 توکن\n"
457
+ f"• تاریخچه گروهی: تا 32768 توکن\n"
458
+ f"• پاسخ‌های ربات در هر دو ذخیره می‌شود\n\n"
459
+ f"برای پاک کردن تاریخچه شخصی از دستور /clear استفاده کنید.\n"
460
+ f"برای پاک کردن تاریخچه گروه، ادمین از دستور /clear_group_context استفاده کند."
461
+ )
462
+ else:
463
+ context_summary = data_manager.get_context_summary(user_id)
464
+ await update.message.reply_text(
465
+ f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n"
466
+ f"{context_summary}\n\n"
467
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
468
+ )
469
+ else:
470
+ context_summary = data_manager.get_context_summary(user_id)
471
+
472
+ await update.message.reply_text(
473
+ f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
474
+ f"{context_summary}\n\n"
475
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
476
+ )
477
+
478
+ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
479
+ """نمایش دستورات کمک"""
480
+ user_id = update.effective_user.id
481
+ chat = update.effective_chat
482
+
483
+ # بررسی مجوزها - استفاده از تابع get_admin_ids
484
+ admin_ids = admin_panel.get_admin_ids()
485
+ is_admin_bot = user_id in admin_ids
486
+ is_admin_group = system_instruction_handlers.is_group_admin(update) if chat.type in ['group', 'supergroup'] else False
487
+
488
+ if chat.type in ['group', 'supergroup']:
489
+ help_text = (
490
+ "🤖 **دستورات ربات در گروه:**\n\n"
491
+ "🟢 `/start` - شروع کار با ربات در گروه\n"
492
+ "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
493
+ "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
494
+ "🟢 `/help` - نمایش این پیام راهنما\n\n"
495
+ "📝 **نکته:** ربات به سه صورت کار می‌کند:\n"
496
+ "1. پاسخ به پیام‌های مستقیم\n"
497
+ "2. پاسخ وقتی منشن می‌شوید\n"
498
+ "3. پاسخ به ریپلای‌ها (روی پیام‌های من یا دیگران)\n\n"
499
+ f"**حالت فعلی:** {data_manager.get_context_mode()}\n"
500
+ "• **separate**: هر کاربر تاریخچه جداگانه (16384 توکن)\n"
501
+ "• **group_shared**: تاریخچه مشترک برای همه (32768 توکن)\n"
502
+ "• **hybrid**: ترکیب هر دو - هم تاریخچه شخصی و هم گروهی\n\n"
503
+ "💡 **مزایای حالت Hybrid:**\n"
504
+ "✅ ربات تاریخچه شخصی شما را به خاطر می‌سپارد\n"
505
+ "✅ ربات از مکالمات گروه نیز آگاه است\n"
506
+ "✅ پاسخ‌های دقیق‌تر و شخصی‌سازی شده\n"
507
+ "✅ برای بحث‌های گروهی پیچیده ایده‌آل است"
508
+ )
509
+
510
+ # اضافه کردن دستورات system instruction
511
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
512
+
513
+ if is_admin_bot or is_admin_group:
514
+ # برای ادمین‌ها
515
+ help_text += (
516
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
517
+ "• `/system clear` - حذف system instruction این گروه\n"
518
+ "• `/system_status` - نمایش وضعیت فعلی\n"
519
+ "• `/system_help` - نمایش راهنما\n\n"
520
+ )
521
+
522
+ if is_admin_bot:
523
+ help_text += "🎯 **دسترسی ادمین ربات:**\n"
524
+ help_text += "- می‌توانید Global System Instruction را مدیریت کنید\n"
525
+ help_text += "- برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n"
526
+ help_text += "- می‌توانید حالت context را با `/set_context_mode` تغییر دهید\n"
527
+ else:
528
+ help_text += "🎯 **دسترسی ادمین گروه:**\n"
529
+ help_text += "- فقط می‌توانید system instruction همین گروه را مدیریت کنید\n"
530
+ else:
531
+ # برای کاربران عادی
532
+ help_text += (
533
+ "این دستورات فقط برای ادمین‌های گروه در دسترس است.\n"
534
+ "برای تنظیم شخصیت ربات در این گروه، با ادمین‌های گروه تماس بگیرید."
535
+ )
536
+
537
+ else:
538
+ # در چت خصوصی
539
+ help_text = (
540
+ "🤖 **دستورات ربات:**\n\n"
541
+ "🟢 `/start` - شروع کار با ربات\n"
542
+ "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
543
+ "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
544
+ "🟢 `/help` - نمایش این پیام راهنما\n\n"
545
+ "📝 **نکته:** ربات تاریخچه مکالمه شما را تا 16384 توکن ذخیره می‌کند. "
546
+ "می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n"
547
+ "برای شروع مکالمه جدید از دستور /clear استفاده کنید."
548
+ )
549
+
550
+ # اضافه کردن دستورات system instruction
551
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
552
+
553
+ if is_admin_bot:
554
+ help_text += (
555
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
556
+ "• `/system_help` - نمایش راهنما\n\n"
557
+ "🎯 **دسترسی ادمین ربات:**\n"
558
+ "- می‌توانید Global System Instruction را مدیریت کنید\n"
559
+ "- از پنل ادمین برای تنظیمات پیشرفته استفاده کنید"
560
+ )
561
+ else:
562
+ help_text += "این دستورات فقط برای ادمین‌های ربات در دسترس است."
563
+
564
+ await update.message.reply_text(help_text, parse_mode='Markdown')
565
+
566
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
567
+ """هندلر اصلی برای پیام‌ها"""
568
+ # بررسی وجود پیام
569
+ if not update.message:
570
+ return
571
+
572
+ user_id = update.effective_user.id
573
+ chat = update.effective_chat
574
+
575
+ # بررسی مسدود بودن کاربر
576
+ if data_manager.is_user_banned(user_id):
577
+ logger.info(f"Banned user {user_id} tried to send a message.")
578
+ return
579
+
580
+ # بررسی حالت نگهداری
581
+ admin_ids = admin_panel.get_admin_ids()
582
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
583
+ await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
584
+ return
585
+
586
+ # بررسی کلمات مسدود شده
587
+ message_text = update.message.text or update.message.caption or ""
588
+ if not message_text:
589
+ return
590
+
591
+ if data_manager.contains_blocked_words(message_text):
592
+ logger.info(f"User {user_id} sent a message with a blocked word.")
593
+ return
594
+
595
+ if chat.type in ['group', 'supergroup']:
596
+ # پردازش در گروه - هر کاربر task جداگانه دارد
597
+ task_key = (chat.id, user_id)
598
+
599
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
600
+ user_group_tasks[task_key].cancel()
601
+ logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")
602
+
603
+ task = asyncio.create_task(_process_group_request(update, context))
604
+ user_group_tasks[task_key] = task
605
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
606
+ else:
607
+ # پردازش در چت خصوصی
608
+ if user_id in user_tasks and not user_tasks[user_id].done():
609
+ user_tasks[user_id].cancel()
610
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
611
+
612
+ task = asyncio.create_task(_process_user_request(update, context))
613
+ user_tasks[user_id] = task
614
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
615
+
616
+ async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
617
+ """هندلر برای زمانی که ربات در گروه منشن می‌شود"""
618
+ if not update.message:
619
+ return
620
+
621
+ if update.effective_chat.type in ['group', 'supergroup']:
622
+ # استخراج اطلاعات ریپلای
623
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
624
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
625
+
626
+ # حذف منشن از متن
627
+ message_text = update.message.text or ""
628
+ bot_username = context.bot.username
629
+
630
+ # حذف منشن ربات از متن
631
+ if bot_username and f"@{bot_username}" in message_text:
632
+ message_text = message_text.replace(f"@{bot_username}", "").strip()
633
+
634
+ if message_text:
635
+ # پردازش پیام مانند حالت عادی اما با متن فرمت‌شده
636
+ user_name = update.effective_user.first_name
637
+
638
+ # اگر ریپلای وجود داشت، متن را فرمت کن
639
+ if reply_info and reply_info.get('replied_text'):
640
+ formatted_message = format_reply_message(
641
+ message_text,
642
+ reply_info.get('replied_user_name', 'Unknown'),
643
+ reply_info.get('replied_text'),
644
+ reply_info.get('is_reply_to_bot', False),
645
+ user_name
646
+ )
647
+ else:
648
+ formatted_message = message_text
649
+
650
+ # پردازش درخواست - هر کاربر task جداگانه دارد
651
+ task_key = (update.effective_chat.id, update.effective_user.id)
652
+
653
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
654
+ user_group_tasks[task_key].cancel()
655
+ logger.info(f"Cancelled previous task for group {update.effective_chat.id}, user {update.effective_user.id} to start a new one.")
656
+
657
+ task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info))
658
+ user_group_tasks[task_key] = task
659
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, update.effective_chat.id, update.effective_user.id))
660
+ else:
661
+ await update.message.reply_text("بله؟ چگونه می‌توانم کمک کنم؟")
662
+
663
+ async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
664
+ """هندلر مخصوص ریپلای‌ها"""
665
+ # بررسی وجود پیام
666
+ if not update.message:
667
+ return
668
+
669
+ # فقط ریپلای‌هایی که متن دارند
670
+ message_text = update.message.text or update.message.caption or ""
671
+ if not message_text:
672
+ return
673
+
674
+ user_id = update.effective_user.id
675
+ chat = update.effective_chat
676
+
677
+ # بررسی مسدود بودن کاربر
678
+ if data_manager.is_user_banned(user_id):
679
+ return
680
+
681
+ # بررسی حالت نگهداری
682
+ admin_ids = admin_panel.get_admin_ids()
683
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
684
+ return
685
+
686
+ # بررسی کلمات مسدود شده
687
+ if data_manager.contains_blocked_words(message_text):
688
+ return
689
+
690
+ if chat.type in ['group', 'supergroup']:
691
+ # پردازش در گروه - هر کاربر task جداگانه دارد
692
+ task_key = (chat.id, user_id)
693
+
694
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
695
+ user_group_tasks[task_key].cancel()
696
+ logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")
697
+
698
+ task = asyncio.create_task(_process_group_request(update, context))
699
+ user_group_tasks[task_key] = task
700
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
701
+ else:
702
+ # پردازش در چت خصوصی
703
+ if user_id in user_tasks and not user_tasks[user_id].done():
704
+ user_tasks[user_id].cancel()
705
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
706
+
707
+ task = asyncio.create_task(_process_user_request(update, context))
708
+ user_tasks[user_id] = task
709
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
710
+
711
+ def main() -> None:
712
+ token = os.environ.get("BOT_TOKEN")
713
+ if not token:
714
+ logger.error("BOT_TOKEN not set in environment variables!")
715
+ return
716
+
717
+ application = (
718
+ Application.builder()
719
+ .token(token)
720
+ .concurrent_updates(True)
721
+ .build()
722
+ )
723
+
724
+ # هندلرهای کاربران
725
+ application.add_handler(CommandHandler("start", start))
726
+ application.add_handler(CommandHandler("clear", clear_chat))
727
+ application.add_handler(CommandHandler("context", context_info))
728
+ application.add_handler(CommandHandler("help", help_command))
729
+
730
+ # هندلر برای ریپلای‌ها
731
+ application.add_handler(MessageHandler(
732
+ filters.TEXT & filters.REPLY,
733
+ reply_handler
734
+ ))
735
+
736
+ # هندلر برای منشن در گروه
737
+ application.add_handler(MessageHandler(
738
+ filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS,
739
+ mention_handler
740
+ ))
741
+
742
+ # هندلر برای پیام‌های متنی معمولی (بدون ریپلای و بدون منشن)
743
+ application.add_handler(MessageHandler(
744
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY,
745
+ handle_message
746
+ ))
747
+
748
+ # هندلر برای پیام‌های متنی در گروه (بدون منشن و بدون ریپلای)
749
+ application.add_handler(MessageHandler(
750
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS & ~filters.Entity("mention") & ~filters.REPLY,
751
+ handle_message
752
+ ))
753
+
754
+ # راه‌اندازی و ثبت هندلرهای پنل ادمین
755
+ admin_panel.setup_admin_handlers(application)
756
+
757
+ # راه‌اندازی هندلرهای system instruction
758
+ system_instruction_handlers.setup_system_instruction_handlers(application)
759
+
760
+ # تنظیم هندلر خطا
761
+ async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
762
+ logger.error(f"Exception while handling an update: {context.error}")
763
+ try:
764
+ if update and update.message:
765
+ await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.")
766
+ except:
767
+ pass
768
+
769
+ application.add_error_handler(error_handler)
770
+
771
+ port = int(os.environ.get("PORT", 8443))
772
+ webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
773
+
774
+ if webhook_url:
775
+ application.run_webhook(
776
+ listen="0.0.0.0",
777
+ port=port,
778
+ webhook_url=webhook_url,
779
+ url_path="webhook"
780
+ )
781
+ else:
782
+ application.run_polling()
783
+
784
+ if __name__ == "__main__":
785
+ main()
BOT/2/render.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ - type: web
3
+ name: telegram-ai-bot
4
+ env: python
5
+ buildCommand: pip install -r requirements.txt
6
+ startCommand: python main.py
7
+ plan: free # می‌توانید از پلن رایگان استفاده کنید
8
+ envVars:
9
+ - key: BOT_TOKEN
10
+ sync: false # مقدار این متغیر را باید در داشبورد Render وارد کنید
11
+ - key: HF_TOKEN
12
+ sync: false # مقدار این متغیر را نیز در داشبورد Render وارد کنید
BOT/2/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-telegram-bot[job-queue]
2
+ python-telegram-bot[webhooks]
3
+ openai
4
+ requests
5
+ huggingface_hub
6
+ aiohttp
7
+ httpx[http2]
8
+ matplotlib
9
+ pandas
10
+ psutil
11
+ tiktoken
BOT/2/restart.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # restart.py
2
+ import os
3
+ import sys
4
+ import subprocess
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def restart_bot():
10
+ """ریستارت کردن ربات"""
11
+ logger.info("Restarting bot...")
12
+ python = sys.executable
13
+ os.execl(python, python, *sys.argv)
BOT/2/smart_context.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import asyncio
7
+ import hashlib
8
+ import numpy as np
9
+ from datetime import datetime, timedelta
10
+ from typing import List, Dict, Any, Optional, Tuple, Set
11
+ from collections import defaultdict, deque
12
+ import pickle
13
+ from dataclasses import dataclass, field
14
+ from enum import Enum
15
+ import re
16
+ import heapq
17
+
18
+ # برای embeddings (در صورت نبود کتابخانه، از روش جایگزین استفاده می‌شود)
19
+ try:
20
+ from sentence_transformers import SentenceTransformer
21
+ HAS_SBERT = True
22
+ except ImportError:
23
+ HAS_SBERT = False
24
+ from sklearn.feature_extraction.text import TfidfVectorizer
25
+ import warnings
26
+ warnings.filterwarnings("ignore")
27
+
28
+ # وارد کردن مدیر داده‌ها
29
+ import data_manager
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # ==================== ENUMS و DataClasses ====================
34
+
35
+ class MemoryPriority(Enum):
36
+ """اولویت حافظه"""
37
+ LOW = 1
38
+ MEDIUM = 2
39
+ HIGH = 3
40
+ CRITICAL = 4
41
+
42
+ class MessageType(Enum):
43
+ """نوع پیام"""
44
+ FACT = "fact"
45
+ PREFERENCE = "preference"
46
+ EMOTION = "emotion"
47
+ QUESTION = "question"
48
+ ANSWER = "answer"
49
+ DECISION = "decision"
50
+ ACTION = "action"
51
+ CHITCHAT = "chitchat"
52
+
53
+ class EmotionType(Enum):
54
+ """نوع احساس"""
55
+ POSITIVE = "positive"
56
+ NEUTRAL = "neutral"
57
+ NEGATIVE = "negative"
58
+ EXCITED = "excited"
59
+ ANGRY = "angry"
60
+ CONFUSED = "confused"
61
+
62
+ @dataclass
63
+ class MessageNode:
64
+ """گره پیام در گراف حافظه"""
65
+ id: str
66
+ content: str
67
+ role: str
68
+ timestamp: datetime
69
+ message_type: MessageType
70
+ importance_score: float = 0.5
71
+ emotion_score: Dict[EmotionType, float] = field(default_factory=dict)
72
+ tokens: int = 0
73
+ embeddings: Optional[np.ndarray] = None
74
+ metadata: Dict[str, Any] = field(default_factory=dict)
75
+
76
+ def __hash__(self):
77
+ return hash(self.id)
78
+
79
+ def __eq__(self, other):
80
+ return self.id == other.id
81
+
82
+ @dataclass
83
+ class MemoryConnection:
84
+ """اتصال بین پیام‌ها در گراف حافظه"""
85
+ source_id: str
86
+ target_id: str
87
+ connection_type: str # 'semantic', 'temporal', 'causal', 'contextual'
88
+ strength: float = 1.0
89
+ metadata: Dict[str, Any] = field(default_factory=dict)
90
+
91
+ @dataclass
92
+ class UserProfile:
93
+ """پروفایل کاربر"""
94
+ user_id: int
95
+ personality_traits: Dict[str, float] = field(default_factory=dict)
96
+ interests: Set[str] = field(default_factory=set)
97
+ preferences: Dict[str, Any] = field(default_factory=dict)
98
+ conversation_style: str = "balanced"
99
+ knowledge_level: Dict[str, float] = field(default_factory=dict)
100
+ emotional_patterns: Dict[str, List[float]] = field(default_factory=dict)
101
+ learning_style: Optional[str] = None
102
+
103
+ def update_from_message(self, message: str, analysis: Dict[str, Any]):
104
+ """به‌روزرسانی پروفایل بر اساس پیام جدید"""
105
+ if 'personality_clues' in analysis:
106
+ for trait, score in analysis['personality_clues'].items():
107
+ current = self.personality_traits.get(trait, 0.5)
108
+ self.personality_traits[trait] = 0.7 * current + 0.3 * score
109
+
110
+ if 'interests' in analysis:
111
+ self.interests.update(analysis['interests'])
112
+
113
+ if 'preferences' in analysis:
114
+ self.preferences.update(analysis['preferences'])
115
+
116
+ # ==================== کلاس Embedding Manager ====================
117
+
118
+ class EmbeddingManager:
119
+ """مدیریت embeddings برای جستجوی معنایی"""
120
+
121
+ def __init__(self, model_name: str = None):
122
+ self.model = None
123
+ self.vectorizer = None
124
+ self.use_sbert = HAS_SBERT
125
+
126
+ if self.use_sbert:
127
+ try:
128
+ self.model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
129
+ logger.info("Loaded multilingual sentence transformer")
130
+ except Exception as e:
131
+ logger.warning(f"Failed to load sentence transformer: {e}")
132
+ self.use_sbert = False
133
+
134
+ if not self.use_sbert:
135
+ try:
136
+ from sklearn.feature_extraction.text import TfidfVectorizer
137
+ self.vectorizer = TfidfVectorizer(max_features=1000)
138
+ logger.info("Using TF-IDF for embeddings")
139
+ except ImportError:
140
+ logger.warning("scikit-learn not available, using simple word vectors")
141
+ self.vectorizer = None
142
+
143
+ def get_embedding(self, text: str) -> np.ndarray:
144
+ """دریافت embedding برای متن"""
145
+ if self.use_sbert and self.model:
146
+ return self.model.encode([text])[0]
147
+ elif self.vectorizer:
148
+ # برای TF-IDF نیاز به fit داریم، فقط بردار ساده برمی‌گردانیم
149
+ words = text.lower().split()
150
+ unique_words = list(set(words))
151
+ embedding = np.zeros(100)
152
+ for i, word in enumerate(unique_words[:100]):
153
+ embedding[i] = hash(word) % 100 / 100.0
154
+ return embedding
155
+ else:
156
+ # روش ساده‌تر
157
+ text_lower = text.lower()
158
+ embedding = np.zeros(50)
159
+ # وزن بر اساس طول و محتوا
160
+ embedding[0] = len(text) / 1000.0
161
+ embedding[1] = text.count('؟') / 5.0
162
+ embedding[2] = text.count('!') / 5.0
163
+ # ویژگی‌های ساده
164
+ embedding[3] = 1.0 if 'چه' in text_lower else 0.0
165
+ embedding[4] = 1.0 if 'چرا' in text_lower else 0.0
166
+ embedding[5] = 1.0 if 'چگونه' in text_lower else 0.0
167
+ return embedding
168
+
169
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
170
+ """محاسبه cosine similarity"""
171
+ norm1 = np.linalg.norm(vec1)
172
+ norm2 = np.linalg.norm(vec2)
173
+ if norm1 == 0 or norm2 == 0:
174
+ return 0.0
175
+ return np.dot(vec1, vec2) / (norm1 * norm2)
176
+
177
+ # ==================== کلاس Memory Graph ====================
178
+
179
+ class MemoryGraph:
180
+ """گراف حافظه برای ذخیره و بازیابی ارتباطات"""
181
+
182
+ def __init__(self):
183
+ self.nodes: Dict[str, MessageNode] = {}
184
+ self.connections: List[MemoryConnection] = []
185
+ self.adjacency: Dict[str, List[MemoryConnection]] = defaultdict(list)
186
+ self.topic_clusters: Dict[str, Set[str]] = defaultdict(set)
187
+ self.time_index: List[Tuple[datetime, str]] = []
188
+
189
+ def add_node(self, node: MessageNode):
190
+ """افزودن گره جدید"""
191
+ self.nodes[node.id] = node
192
+ self.time_index.append((node.timestamp, node.id))
193
+ self.time_index.sort(key=lambda x: x[0])
194
+
195
+ def add_connection(self, connection: MemoryConnection):
196
+ """افزودن اتصال جدید"""
197
+ self.connections.append(connection)
198
+ self.adjacency[connection.source_id].append(connection)
199
+
200
+ def find_similar_nodes(self, query_embedding: np.ndarray,
201
+ threshold: float = 0.7,
202
+ max_results: int = 5) -> List[Tuple[str, float]]:
203
+ """یافتن گره‌های مشابه"""
204
+ similarities = []
205
+ for node_id, node in self.nodes.items():
206
+ if node.embeddings is not None:
207
+ similarity = self._cosine_similarity(query_embedding, node.embeddings)
208
+ if similarity > threshold:
209
+ similarities.append((node_id, similarity))
210
+
211
+ similarities.sort(key=lambda x: x[1], reverse=True)
212
+ return similarities[:max_results]
213
+
214
+ def get_temporal_neighbors(self, node_id: str,
215
+ time_window: timedelta = timedelta(hours=24)) -> List[str]:
216
+ """یافتن همسایه‌های زمانی"""
217
+ if node_id not in self.nodes:
218
+ return []
219
+
220
+ node_time = self.nodes[node_id].timestamp
221
+ neighbors = []
222
+
223
+ for timestamp, nid in self.time_index:
224
+ if nid != node_id and abs(timestamp - node_time) <= time_window:
225
+ neighbors.append(nid)
226
+
227
+ return neighbors
228
+
229
+ def get_semantic_cluster(self, node_id: str, min_similarity: float = 0.6) -> Set[str]:
230
+ """دریافت خوشه معنایی یک گره"""
231
+ cluster = {node_id}
232
+
233
+ if node_id not in self.nodes or self.nodes[node_id].embeddings is None:
234
+ return cluster
235
+
236
+ query_embedding = self.nodes[node_id].embeddings
237
+
238
+ for other_id, other_node in self.nodes.items():
239
+ if other_id != node_id and other_node.embeddings is not None:
240
+ similarity = self._cosine_similarity(query_embedding, other_node.embeddings)
241
+ if similarity > min_similarity:
242
+ cluster.add(other_id)
243
+
244
+ return cluster
245
+
246
+ def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
247
+ """محاسبه cosine similarity"""
248
+ norm1 = np.linalg.norm(vec1)
249
+ norm2 = np.linalg.norm(vec2)
250
+ if norm1 == 0 or norm2 == 0:
251
+ return 0.0
252
+ return np.dot(vec1, vec2) / (norm1 * norm2)
253
+
254
+ # ==================== کلاس Context Analyzer ====================
255
+
256
+ class ContextAnalyzer:
257
+ """آنالیزور هوشمند context"""
258
+
259
+ def __init__(self):
260
+ self.keyword_patterns = {
261
+ 'name': [r'نام\s+من\s+(.*?)(?:است|می‌باشد)', r'اسم\s+من\s+(.*?)'],
262
+ 'age': [r'سن\s+من\s+(\d+)', r'(\d+)\s+سالمه'],
263
+ 'location': [r'اهل\s+(.*?)\s+هستم', r'د��\s+(.*?)\s+زندگی می‌کنم'],
264
+ 'preference': [r'دوست\s+دارم\s+(.*?)', r'علاقه\s+دارم\s+(.*?)', r'ترجیح\s+می‌دهم\s+(.*?)'],
265
+ 'dislike': [r'دوست\s+ندارم\s+(.*?)', r'مخالف\s+(.*?)\s+هستم'],
266
+ 'goal': [r'می‌خواهم\s+(.*?)', r'هدف\s+من\s+(.*?)\s+است'],
267
+ 'question': [r'(چرا|چگونه|چه|کجا|کی|آیا)\s+.*?\?'],
268
+ 'decision': [r'تصمیم\s+گرفتم\s+(.*?)', r'قصد\s+دارم\s+(.*?)'],
269
+ 'emotion': [r'احساس\s+(.*?)\s+دارم', r'(خوشحالم|ناراحتم|عصبانی‌ام|خستهام)']
270
+ }
271
+
272
+ self.emotion_keywords = {
273
+ EmotionType.POSITIVE: ['خوب', 'عالی', 'خوشحال', 'عالی', 'ممنون', 'مرسی', 'دوست دارم', 'عالیه'],
274
+ EmotionType.NEGATIVE: ['بد', 'بدی', 'ناراحت', 'غمگین', 'عصبانی', 'مشکل', 'خطا', 'اشتباه'],
275
+ EmotionType.EXCITED: ['هیجان‌زده', 'هیجان', 'جالب', 'شگفت‌انگیز', 'عالی', 'وای'],
276
+ EmotionType.ANGRY: ['عصبانی', 'خشمگین', 'ناراحت', 'اعصاب', 'دیوانه'],
277
+ EmotionType.CONFUSED: ['سردرگم', 'گیج', 'نمی‌فهمم', 'مشکل دارم', 'کمک']
278
+ }
279
+
280
+ def analyze_message(self, text: str, role: str) -> Dict[str, Any]:
281
+ """آنالیز پیام و استخراج اطلاعات"""
282
+ analysis = {
283
+ 'type': self._detect_message_type(text, role),
284
+ 'entities': self._extract_entities(text),
285
+ 'keywords': self._extract_keywords(text),
286
+ 'emotion': self._analyze_emotion(text),
287
+ 'importance': self._calculate_importance(text, role),
288
+ 'topics': self._extract_topics(text),
289
+ 'intent': self._detect_intent(text),
290
+ 'complexity': self._calculate_complexity(text),
291
+ 'has_personal_info': False,
292
+ 'personal_info': {}
293
+ }
294
+
295
+ # استخراج اطلاعات شخصی
296
+ personal_info = self._extract_personal_info(text)
297
+ if personal_info:
298
+ analysis['has_personal_info'] = True
299
+ analysis['personal_info'] = personal_info
300
+
301
+ # استخراج ترجیحات
302
+ preferences = self._extract_preferences(text)
303
+ if preferences:
304
+ analysis['preferences'] = preferences
305
+
306
+ return analysis
307
+
308
+ def _detect_message_type(self, text: str, role: str) -> MessageType:
309
+ """تشخیص نوع پیام"""
310
+ text_lower = text.lower()
311
+
312
+ if role == 'user':
313
+ if any(q in text_lower for q in ['؟', '?', 'چرا', 'چگونه', 'چه', 'کجا']):
314
+ return MessageType.QUESTION
315
+ elif any(e in text_lower for e in ['احساس', 'حالم', 'خوشحالم', 'ناراحتم']):
316
+ return MessageType.EMOTION
317
+ elif any(d in text_lower for d in ['تصمیم', 'قصد', 'می‌خواهم']):
318
+ return MessageType.DECISION
319
+ elif any(p in text_lower for p in ['دوست دارم', 'علاقه', 'ترجیح']):
320
+ return MessageType.PREFERENCE
321
+ else:
322
+ return MessageType.FACT
323
+ else:
324
+ if '؟' in text_lower:
325
+ return MessageType.QUESTION
326
+ elif any(a in text_lower for a in ['پاسخ', 'جواب', 'راه حل']):
327
+ return MessageType.ANSWER
328
+ else:
329
+ return MessageType.FACT
330
+
331
+ def _extract_entities(self, text: str) -> List[str]:
332
+ """استخراج موجودیت‌ها"""
333
+ entities = []
334
+ # الگوهای ساده برای اسامی
335
+ name_patterns = [
336
+ r'نام\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
337
+ r'اسم\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
338
+ ]
339
+
340
+ for pattern in name_patterns:
341
+ matches = re.findall(pattern, text)
342
+ entities.extend(matches)
343
+
344
+ return entities
345
+
346
+ def _extract_keywords(self, text: str) -> List[str]:
347
+ """استخراج کلمات کلیدی"""
348
+ # حذف کلمات توقف فارسی
349
+ stopwords = {'و', 'در', 'با', 'به', 'از', 'که', 'این', 'آن', 'را', 'برای', 'اما', 'یا'}
350
+ words = re.findall(r'\b[\wآ-ی]+\b', text.lower())
351
+ keywords = [w for w in words if w not in stopwords and len(w) > 2]
352
+
353
+ return list(set(keywords))[:10]
354
+
355
+ def _analyze_emotion(self, text: str) -> Dict[EmotionType, float]:
356
+ """تحلیل احساسات متن"""
357
+ emotion_scores = {e: 0.0 for e in EmotionType}
358
+ text_lower = text.lower()
359
+
360
+ for emotion_type, keywords in self.emotion_keywords.items():
361
+ score = 0.0
362
+ for keyword in keywords:
363
+ if keyword in text_lower:
364
+ score += 1.0
365
+ emotion_scores[emotion_type] = min(score / 3.0, 1.0)
366
+
367
+ # تشخیص احساس کلی
368
+ if sum(emotion_scores.values()) == 0:
369
+ emotion_scores[EmotionType.NEUTRAL] = 1.0
370
+
371
+ return emotion_scores
372
+
373
+ def _calculate_importance(self, text: str, role: str) -> float:
374
+ """محاسبه اهمیت پیام"""
375
+ score = 0.0
376
+
377
+ # امتیاز بر اساس نقش
378
+ if role == 'user':
379
+ score += 0.3
380
+
381
+ # امتیاز بر اساس طول
382
+ length = len(text)
383
+ if length > 200:
384
+ score += 0.3
385
+ elif length > 100:
386
+ score += 0.2
387
+ elif length > 50:
388
+ score += 0.1
389
+
390
+ # امتیاز بر اساس سوال بودن
391
+ if '؟' in text or '?' in text:
392
+ score += 0.2
393
+
394
+ # امتیاز بر اساس کلمات کلیدی مهم
395
+ important_words = ['مهم', 'لطفا', 'فوری', 'ضروری', 'لازم', 'حتما']
396
+ for word in important_words:
397
+ if word in text.lower():
398
+ score += 0.2
399
+ break
400
+
401
+ # امتیاز بر اساس اطلاعات شخصی
402
+ if any(pattern in text for pattern in ['نام من', 'سن من', 'اهل']):
403
+ score += 0.3
404
+
405
+ return min(score, 1.0)
406
+
407
+ def _extract_topics(self, text: str) -> List[str]:
408
+ """استخراج موضوعات"""
409
+ topics = []
410
+
411
+ # دسته‌بندی موضوعات بر اساس کلمات کلیدی
412
+ topic_categories = {
413
+ 'ورزش': ['فوتبال', 'ورزش', 'تمرین', 'مسابقه', 'تیم'],
414
+ 'تکنولوژی': ['کامپیوتر', 'برنامه', 'کد', 'پایتون', 'هوش مصنوعی'],
415
+ 'هنر': ['فیلم', 'موسیقی', 'نقاشی', 'کتاب', 'خواننده'],
416
+ 'علم': ['تحقیق', 'دانش', 'کشف', 'آزمایش', 'نظریه'],
417
+ 'غذا': ['غذا', 'رستوران', 'پخت', 'خوراک', 'ناهار'],
418
+ 'سفر': ['سفر', 'مسافرت', 'کشور', 'شهر', 'هتل'],
419
+ 'سلامتی': ['سلامت', 'بیماری', 'درمان', 'دکتر', 'بیمارستان'],
420
+ 'کاری': ['کار', 'شغل', 'شرکت', 'مصاحبه', 'پروژه'],
421
+ 'تحصیل': ['درس', 'دانشگاه', 'مدرسه', 'آموزش', 'یادگیری'],
422
+ }
423
+
424
+ text_lower = text.lower()
425
+ for topic, keywords in topic_categories.items():
426
+ if any(keyword in text_lower for keyword in keywords):
427
+ topics.append(topic)
428
+
429
+ return topics[:3]
430
+
431
+ def _detect_intent(self, text: str) -> str:
432
+ """تشخیص قصد کاربر"""
433
+ text_lower = text.lower()
434
+
435
+ if any(q in text_lower for q in ['چطور', 'چگونه', 'راهنمایی']):
436
+ return 'guidance'
437
+ elif any(q in text_lower for q in ['چه', 'اطلاعات', 'معرفی']):
438
+ return 'information'
439
+ elif any(q in text_lower for q in ['چرا', 'دلیل', 'علت']):
440
+ return 'explanation'
441
+ elif any(q in text_lower for q in ['کمک', 'راه حل', 'مشکل']):
442
+ return 'help'
443
+ elif any(q in text_lower for q in ['توصیه', 'پیشنهاد', 'نظر']):
444
+ return 'advice'
445
+ elif any(q in text_lower for q in ['بحث', 'بحث کنیم', 'نظرت']):
446
+ return 'discussion'
447
+ else:
448
+ return 'general'
449
+
450
+ def _calculate_complexity(self, text: str) -> float:
451
+ """محاسبه پیچیدگی متن"""
452
+ # میانگین طول کلمات
453
+ words = text.split()
454
+ if not words:
455
+ return 0.0
456
+
457
+ avg_word_length = sum(len(w) for w in words) / len(words)
458
+
459
+ # تعداد جملات
460
+ sentences = re.split(r'[.!?]', text)
461
+ num_sentences = max(len(sentences), 1)
462
+
463
+ # نسبت کلمات منحصر به فرد
464
+ unique_words = len(set(words))
465
+ diversity = unique_words / len(words) if words else 0
466
+
467
+ complexity = (avg_word_length / 10.0 + diversity + min(len(words) / 50.0, 1.0)) / 3.0
468
+
469
+ return min(complexity, 1.0)
470
+
471
+ def _extract_personal_info(self, text: str) -> Dict[str, Any]:
472
+ """استخراج اطلاعات شخصی"""
473
+ info = {}
474
+
475
+ for info_type, patterns in self.keyword_patterns.items():
476
+ for pattern in patterns:
477
+ matches = re.findall(pattern, text)
478
+ if matches:
479
+ info[info_type] = matches[0]
480
+ break
481
+
482
+ return info
483
+
484
+ def _extract_preferences(self, text: str) -> Dict[str, Any]:
485
+ """استخراج ترجیحات"""
486
+ preferences = {}
487
+ text_lower = text.lower()
488
+
489
+ # ترجیحات ساده
490
+ if 'دوست دارم' in text_lower:
491
+ parts = text_lower.split('دوست دارم')
492
+ if len(parts) > 1:
493
+ preference = parts[1].split('.')[0].strip()
494
+ if preference:
495
+ preferences['likes'] = preferences.get('likes', []) + [preference]
496
+
497
+ if 'دوست ندارم' in text_lower:
498
+ parts = text_lower.split('دوست ندارم')
499
+ if len(parts) > 1:
500
+ preference = parts[1].split('.')[0].strip()
501
+ if preference:
502
+ preferences['dislikes'] = preferences.get('dislikes', []) + [preference]
503
+
504
+ return preferences
505
+
506
+ # ==================== کلاس Intelligent Context Manager ====================
507
+
508
+ class IntelligentContextManager:
509
+ """مدیر هوشمند context"""
510
+
511
+ def __init__(self, user_id: int):
512
+ self.user_id = user_id
513
+ self.embedding_manager = EmbeddingManager()
514
+ self.analyzer = ContextAnalyzer()
515
+ self.memory_graph = MemoryGraph()
516
+ self.user_profile = UserProfile(user_id=user_id)
517
+
518
+ # لایه‌های حافظه
519
+ self.memory_layers = {
520
+ 'ephemeral': deque(maxlen=20), # حافظه زودگذر (چند دقیقه)
521
+ 'working': deque(maxlen=50), # حافظه فعال (مکالمه جاری)
522
+ 'recent': deque(maxlen=100), # حافظه اخیر (چند روز)
523
+ 'long_term': [], # حافظه بلندمدت (اهمیت بالا)
524
+ 'core': [] # حافظه هسته (اطلاعات حیاتی)
525
+ }
526
+
527
+ # تنظیمات
528
+ self.max_working_tokens = 512
529
+ self.max_context_tokens = 2048
530
+ self.min_importance_threshold = 0.3
531
+ self.semantic_similarity_threshold = 0.7
532
+
533
+ # آمار
534
+ self.stats = {
535
+ 'total_messages': 0,
536
+ 'compressed_messages': 0,
537
+ 'retrieved_memories': 0,
538
+ 'profile_updates': 0,
539
+ 'average_importance': 0.0
540
+ }
541
+
542
+ # بارگذاری داده‌های ذخیره شده
543
+ self._load_saved_data()
544
+
545
+ def _load_saved_data(self):
546
+ """بارگذاری داده‌های ذخیره شده"""
547
+ try:
548
+ # بارگذاری از data_manager
549
+ user_data = data_manager.DATA['users'].get(str(self.user_id), {})
550
+
551
+ if 'smart_context' in user_data:
552
+ saved_data = user_data['smart_context']
553
+
554
+ # بارگذاری پروفایل کاربر
555
+ if 'profile' in saved_data:
556
+ self.user_profile = UserProfile(**saved_data['profile'])
557
+
558
+ # بارگذاری آمار
559
+ if 'stats' in saved_data:
560
+ self.stats.update(saved_data['stats'])
561
+
562
+ logger.info(f"Loaded smart context for user {self.user_id}")
563
+ except Exception as e:
564
+ logger.error(f"Error loading saved context data: {e}")
565
+
566
+ def _save_data(self):
567
+ """ذخیره داده‌ها"""
568
+ try:
569
+ user_id_str = str(self.user_id)
570
+ if user_id_str not in data_manager.DATA['users']:
571
+ data_manager.DATA['users'][user_id_str] = {}
572
+
573
+ # ذخیره داده‌های هوشمند
574
+ data_manager.DATA['users'][user_id_str]['smart_context'] = {
575
+ 'profile': {
576
+ 'user_id': self.user_profile.user_id,
577
+ 'personality_traits': dict(self.user_profile.personality_traits),
578
+ 'interests': list(self.user_profile.interests),
579
+ 'preferences': dict(self.user_profile.preferences),
580
+ 'conversation_style': self.user_profile.conversation_style,
581
+ 'knowledge_level': dict(self.user_profile.knowledge_level),
582
+ 'emotional_patterns': dict(self.user_profile.emotional_patterns),
583
+ 'learning_style': self.user_profile.learning_style
584
+ },
585
+ 'stats': self.stats,
586
+ 'last_updated': datetime.now().isoformat()
587
+ }
588
+
589
+ data_manager.save_data()
590
+ except Exception as e:
591
+ logger.error(f"Error saving smart context data: {e}")
592
+
593
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
594
+ """پرداش کامل یک پیام جدید"""
595
+ start_time = datetime.now()
596
+
597
+ # 1. تحلیل پیام
598
+ analysis = self.analyzer.analyze_message(content, role)
599
+
600
+ # 2. ایجاد گره حافظه
601
+ message_id = self._generate_message_id(content)
602
+
603
+ # ایجاد embedding به صورت غیرهمزمان
604
+ embedding_task = asyncio.create_task(
605
+ self._get_embedding_async(content)
606
+ )
607
+
608
+ node = MessageNode(
609
+ id=message_id,
610
+ content=content,
611
+ role=role,
612
+ timestamp=datetime.now(),
613
+ message_type=analysis['type'],
614
+ importance_score=analysis['importance'],
615
+ emotion_score=analysis['emotion'],
616
+ tokens=data_manager.count_tokens(content),
617
+ embeddings=None, # موقتاً None
618
+ metadata={
619
+ 'analysis': analysis,
620
+ 'topics': analysis['topics'],
621
+ 'intent': analysis['intent'],
622
+ 'complexity': analysis['complexity']
623
+ }
624
+ )
625
+
626
+ # دریافت embedding (اگر موجود باشد)
627
+ try:
628
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
629
+ except asyncio.TimeoutError:
630
+ logger.warning(f"Embedding generation timeout for message {message_id}")
631
+ node.embeddings = self.embedding_manager.get_embedding(content)
632
+
633
+ # 3. افزودن به حافظه و گراف
634
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
635
+ await asyncio.to_thread(self.memory_graph.add_node, node)
636
+
637
+ # 4. ایجاد ارتباطات
638
+ await asyncio.to_thread(self._create_memory_connections, node)
639
+
640
+ # 5. به‌روزرسانی پروفایل کاربر
641
+ if role == 'user':
642
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
643
+
644
+ # 6. بهینه‌سازی حافظه
645
+ await asyncio.to_thread(self._optimize_memory)
646
+
647
+ # 7. به‌روزرسانی آمار
648
+ self.stats['total_messages'] += 1
649
+ self.stats['average_importance'] = (
650
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
651
+ analysis['importance']
652
+ ) / self.stats['total_messages']
653
+
654
+ # 8. ذخیره داده‌ها
655
+ await asyncio.to_thread(self._save_data)
656
+
657
+ processing_time = (datetime.now() - start_time).total_seconds()
658
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
659
+
660
+ return {
661
+ 'node_id': message_id,
662
+ 'analysis': analysis,
663
+ 'processing_time': processing_time
664
+ }
665
+
666
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
667
+ """دریافت embedding به صورت async"""
668
+ loop = asyncio.get_event_loop()
669
+ return await loop.run_in_executor(
670
+ None,
671
+ self.embedding_manager.get_embedding,
672
+ text
673
+ )
674
+
675
+ def _generate_message_id(self, content: str) -> str:
676
+ """تولید شناسه منحصر به فرد برای پیام"""
677
+ timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
678
+ content_hash = hashlib.md5(content.encode()).hexdigest()[:8]
679
+ return f"{self.user_id}_{timestamp}_{content_hash}"
680
+
681
+ def _add_to_memory_layers(self, node: MessageNode, analysis: Dict[str, Any]):
682
+ """افزودن پیام به لایه‌های حافظه مناسب"""
683
+
684
+ # همیشه به حافظه زودگذر و فعال اضافه می‌شود
685
+ self.memory_layers['ephemeral'].append(node)
686
+ self.memory_layers['working'].append(node)
687
+
688
+ # بررسی برای حافظه اخیر
689
+ if analysis['importance'] > 0.2:
690
+ self.memory_layers['recent'].append(node)
691
+
692
+ # بررسی برای حافظه بلندمدت
693
+ if analysis['importance'] > self.min_importance_threshold:
694
+ self.memory_layers['long_term'].append(node)
695
+
696
+ # بررسی برای حافظه هسته (اطلاعات حیاتی)
697
+ if analysis.get('has_personal_info', False) or analysis['importance'] > 0.8:
698
+ core_entry = {
699
+ 'node': node,
700
+ 'info': analysis.get('personal_info', {}),
701
+ 'timestamp': datetime.now()
702
+ }
703
+ self.memory_layers['core'].append(core_entry)
704
+
705
+ def _create_memory_connections(self, node: MessageNode):
706
+ """ایجاد ارتباطات حافظه برای گره جدید"""
707
+
708
+ # اگر گره‌های قبلی وجود دارند، ارتباط ایجاد کن
709
+ if len(self.memory_graph.nodes) > 1:
710
+ # ارتباط زمانی با آخرین گره
711
+ last_nodes = list(self.memory_graph.nodes.values())[-5:]
712
+ for last_node in last_nodes:
713
+ if last_node.id != node.id:
714
+ temporal_conn = MemoryConnection(
715
+ source_id=last_node.id,
716
+ target_id=node.id,
717
+ connection_type='temporal',
718
+ strength=0.8
719
+ )
720
+ self.memory_graph.add_connection(temporal_conn)
721
+
722
+ # ارتباط معنایی با گره‌های مشابه
723
+ if node.embeddings is not None:
724
+ similar_nodes = self.memory_graph.find_similar_nodes(
725
+ node.embeddings,
726
+ threshold=self.semantic_similarity_threshold
727
+ )
728
+
729
+ for similar_id, similarity in similar_nodes:
730
+ semantic_conn = MemoryConnection(
731
+ source_id=node.id,
732
+ target_id=similar_id,
733
+ connection_type='semantic',
734
+ strength=similarity
735
+ )
736
+ self.memory_graph.add_connection(semantic_conn)
737
+
738
+ def _update_user_profile(self, content: str, analysis: Dict[str, Any]):
739
+ """به‌روزرسانی پروفایل کاربر"""
740
+
741
+ # به‌روزرسانی علاقه‌مندی‌ها
742
+ if 'topics' in analysis:
743
+ for topic in analysis['topics']:
744
+ self.user_profile.interests.add(topic)
745
+
746
+ # به‌روزرسانی ترجیحات
747
+ if 'preferences' in analysis:
748
+ self.user_profile.preferences.update(analysis['preferences'])
749
+
750
+ # تشخیص سبک مکالمه
751
+ complexity = analysis.get('complexity', 0.5)
752
+ if complexity > 0.7:
753
+ self.user_profile.conversation_style = "detailed"
754
+ elif complexity < 0.3:
755
+ self.user_profile.conversation_style = "concise"
756
+
757
+ # به‌روزرسانی الگوهای احساسی
758
+ emotion = analysis.get('emotion', {})
759
+ for emotion_type, score in emotion.items():
760
+ if score > 0.3:
761
+ emotion_name = emotion_type.value if hasattr(emotion_type, 'value') else str(emotion_type)
762
+ if emotion_name not in self.user_profile.emotional_patterns:
763
+ self.user_profile.emotional_patterns[emotion_name] = []
764
+ self.user_profile.emotional_patterns[emotion_name].append(score)
765
+
766
+ self.stats['profile_updates'] += 1
767
+
768
+ def _optimize_memory(self):
769
+ """بهینه‌سازی و فشرده‌سازی حافظه"""
770
+
771
+ # فشرده‌سازی حافظه فعال اگر توکن‌ها زیاد شد
772
+ working_tokens = sum(node.tokens for node in self.memory_layers['working'])
773
+ if working_tokens > self.max_working_tokens:
774
+ self._compress_working_memory()
775
+ self.stats['compressed_messages'] += 1
776
+
777
+ # پاکسازی حافظه زودگذر قدیمی
778
+ if len(self.memory_layers['ephemeral']) > 50:
779
+ self.memory_layers['ephemeral'].clear()
780
+
781
+ # مرتب‌سازی حافظه بلندمدت بر اساس اهمیت
782
+ self.memory_layers['long_term'].sort(key=lambda x: x.importance_score, reverse=True)
783
+ if len(self.memory_layers['long_term']) > 100:
784
+ self.memory_layers['long_term'] = self.memory_layers['long_term'][:100]
785
+
786
+ def _compress_working_memory(self):
787
+ """فشرده‌سازی هوشمند حافظه فعال"""
788
+ if len(self.memory_layers['working']) <= 10:
789
+ return
790
+
791
+ working_memory = list(self.memory_layers['working'])
792
+
793
+ # 1. محاسبه امتیاز برای هر پیام
794
+ scored_messages = []
795
+ for i, node in enumerate(working_memory):
796
+ score = self._calculate_compression_score(node, i, len(working_memory))
797
+ scored_messages.append((score, node))
798
+
799
+ # 2. مرتب‌سازی بر اساس امتیاز
800
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
801
+
802
+ # 3. انتخاب پیام‌های برتر تا سقف توکن
803
+ compressed = []
804
+ total_tokens = 0
805
+
806
+ for score, node in scored_messages:
807
+ if total_tokens + node.tokens <= self.max_working_tokens:
808
+ compressed.append(node)
809
+ total_tokens += node.tokens
810
+ else:
811
+ break
812
+
813
+ # 4. مرتب‌سازی دوباره بر اساس زمان
814
+ compressed.sort(key=lambda x: x.timestamp)
815
+
816
+ # 5. جایگزینی حافظه فعال
817
+ self.memory_layers['working'] = deque(compressed, maxlen=50)
818
+
819
+ logger.info(f"Compressed working memory: {len(working_memory)} -> {len(compressed)} messages")
820
+
821
+ def _calculate_compression_score(self, node: MessageNode, index: int, total: int) -> float:
822
+ """محاسبه امتیاز فشرده‌سازی برای یک پیام"""
823
+ score = 0.0
824
+
825
+ # 1. اهمیت پیام
826
+ score += node.importance_score * 0.4
827
+
828
+ # 2. تازگی (پیام‌های جدیدتر مهم‌تر)
829
+ recency = (index / total) * 0.3
830
+ score += recency
831
+
832
+ # 3. تنوع اطلاعات (بر اساس topics)
833
+ topics = node.metadata.get('topics', [])
834
+ topic_diversity = min(len(topics) / 3.0, 0.2)
835
+ score += topic_diversity
836
+
837
+ # 4. نوع پیام
838
+ type_weights = {
839
+ MessageType.QUESTION: 0.2,
840
+ MessageType.PREFERENCE: 0.2,
841
+ MessageType.DECISION: 0.2,
842
+ MessageType.EMOTION: 0.1,
843
+ MessageType.FACT: 0.1,
844
+ MessageType.ANSWER: 0.1,
845
+ MessageType.ACTION: 0.2,
846
+ MessageType.CHITCHAT: 0.05
847
+ }
848
+ score += type_weights.get(node.message_type, 0.1)
849
+
850
+ # 5. اطلاعات شخصی
851
+ if 'has_personal_info' in node.metadata.get('analysis', {}):
852
+ if node.metadata['analysis']['has_personal_info']:
853
+ score += 0.2
854
+
855
+ return score
856
+
857
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
858
+ """بازیابی هوشمند context مرتبط با query"""
859
+ try:
860
+ if max_tokens is None:
861
+ max_tokens = self.max_context_tokens
862
+
863
+ start_time = datetime.now()
864
+
865
+ # دریافت embedding با timeout
866
+ try:
867
+ embedding_task = asyncio.create_task(
868
+ self._get_embedding_async(query)
869
+ )
870
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
871
+ except asyncio.TimeoutError:
872
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
873
+ query_embedding = self.embedding_manager.get_embedding(query)
874
+
875
+ # بازیابی از حافظه‌های مختلف به صورت موازی
876
+ tasks = []
877
+
878
+ # حافظه فعال
879
+ tasks.append(asyncio.create_task(
880
+ asyncio.to_thread(self._retrieve_from_working_memory)
881
+ ))
882
+
883
+ # حافظه معنایی
884
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
885
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
886
+
887
+ # حافظه هسته
888
+ tasks.append(asyncio.create_task(
889
+ asyncio.to_thread(self._retrieve_core_memories, query)
890
+ ))
891
+
892
+ # اجرای موازی همه tasks
893
+ results = await asyncio.gather(*tasks, return_exceptions=True)
894
+
895
+ # جمع‌آوری نتایج
896
+ retrieved_memories = []
897
+ for result in results:
898
+ if isinstance(result, Exception):
899
+ logger.error(f"Error retrieving memory: {result}")
900
+ continue
901
+ retrieved_memories.extend(result)
902
+
903
+ except Exception as e:
904
+ logger.error(f"Error in retrieve_context: {e}")
905
+ # Fallback: برگرداندن حافظه فعال
906
+ return self._retrieve_from_working_memory()
907
+
908
+ # 1. دریافت embedding برای query
909
+ query_embedding = self.embedding_manager.get_embedding(query)
910
+
911
+ # 2. بازیابی از لایه‌های مختلف حافظه
912
+ retrieved_memories = []
913
+
914
+ # از حافظه فعال (همیشه)
915
+ retrieved_memories.extend(self._retrieve_from_working_memory())
916
+
917
+ # از حافظه اخیر (بر اساس شباهت)
918
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
919
+ retrieved_memories.extend(recent_memories)
920
+
921
+ # از حافظه بلندمدت (اطلاعات مهم)
922
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
923
+ retrieved_memories.extend(long_term_memories)
924
+
925
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
926
+ core_memories = self._retrieve_core_memories(query)
927
+ retrieved_memories.extend(core_memories)
928
+
929
+ # 3. حذف تکراری‌ها و مرتب‌سازی
930
+ unique_memories = self._deduplicate_memories(retrieved_memories)
931
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
932
+
933
+ # 4. انتخاب تا سقف توکن
934
+ final_context = []
935
+ total_tokens = 0
936
+
937
+ for memory in prioritized_memories:
938
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
939
+
940
+ if total_tokens + memory_tokens <= max_tokens:
941
+ final_context.append(memory)
942
+ total_tokens += memory_tokens
943
+ else:
944
+ break
945
+
946
+ # 5. به‌روزرسانی آمار
947
+ self.stats['retrieved_memories'] += len(final_context)
948
+
949
+ retrieval_time = (datetime.now() - start_time).total_seconds()
950
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
951
+
952
+ return final_context
953
+
954
+
955
+ def _retrieve_from_working_memory(self) -> List[Dict[str, Any]]:
956
+ """بازیابی از حافظه فعال"""
957
+ memories = []
958
+
959
+ for node in list(self.memory_layers['working'])[-10:]: # 10 پیام آخر
960
+ memories.append({
961
+ 'node': node,
962
+ 'source': 'working',
963
+ 'relevance': 1.0,
964
+ 'recency': 1.0
965
+ })
966
+
967
+ return memories
968
+
969
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
970
+ layer: str) -> List[Dict[str, Any]]:
971
+ """بازیابی حافظه‌های معنایی"""
972
+ memories = []
973
+
974
+ if layer not in self.memory_layers:
975
+ return memories
976
+
977
+ layer_memories = self.memory_layers[layer]
978
+
979
+ for item in layer_memories:
980
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
981
+
982
+ if node and node.embeddings is not None:
983
+ similarity = self.embedding_manager.cosine_similarity(
984
+ query_embedding, node.embeddings
985
+ )
986
+
987
+ if similarity > self.semantic_similarity_threshold:
988
+ recency_weight = 1.0 if layer == 'working' else 0.7
989
+
990
+ memories.append({
991
+ 'node': node,
992
+ 'source': layer,
993
+ 'relevance': similarity,
994
+ 'recency': recency_weight,
995
+ 'importance': node.importance_score
996
+ })
997
+
998
+ return memories
999
+
1000
+ def _retrieve_core_memories(self, query: str) -> List[Dict[str, Any]]:
1001
+ """بازیابی حافظه‌های هسته"""
1002
+ memories = []
1003
+ query_lower = query.lower()
1004
+
1005
+ for core_entry in self.memory_layers['core']:
1006
+ node = core_entry['node']
1007
+ info = core_entry.get('info', {})
1008
+
1009
+ # بررسی تطابق با query
1010
+ relevance = 0.0
1011
+
1012
+ # تطابق با اطلاعات شخصی
1013
+ for key, value in info.items():
1014
+ if isinstance(value, str) and value.lower() in query_lower:
1015
+ relevance = 0.9
1016
+ break
1017
+
1018
+ # تطابق با محتوای پیام
1019
+ if relevance == 0.0 and node.content.lower() in query_lower:
1020
+ relevance = 0.7
1021
+
1022
+ if relevance > 0.5:
1023
+ memories.append({
1024
+ 'node': node,
1025
+ 'source': 'core',
1026
+ 'relevance': relevance,
1027
+ 'recency': 0.8,
1028
+ 'importance': 1.0,
1029
+ 'personal_info': info
1030
+ })
1031
+
1032
+ return memories
1033
+
1034
+ def _deduplicate_memories(self, memories: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1035
+ """حذف حافظه‌های تکراری"""
1036
+ seen_ids = set()
1037
+ unique_memories = []
1038
+
1039
+ for memory in memories:
1040
+ node = memory.get('node')
1041
+ if node and node.id not in seen_ids:
1042
+ seen_ids.add(node.id)
1043
+ unique_memories.append(memory)
1044
+
1045
+ return unique_memories
1046
+
1047
+ def _prioritize_memories(self, memories: List[Dict[str, Any]],
1048
+ query_embedding: np.ndarray) -> List[Dict[str, Any]]:
1049
+ """اولویت‌بندی حافظه‌های بازیابی شده"""
1050
+
1051
+ def calculate_priority(memory: Dict[str, Any]) -> float:
1052
+ """محاسبه اولویت برای یک حافظه"""
1053
+ priority = 0.0
1054
+
1055
+ # 1. ارتباط معنایی
1056
+ priority += memory.get('relevance', 0.0) * 0.4
1057
+
1058
+ # 2. تازگی
1059
+ priority += memory.get('recency', 0.0) * 0.3
1060
+
1061
+ # 3. اهمیت
1062
+ priority += memory.get('importance', 0.5) * 0.2
1063
+
1064
+ # 4. منبع (حافظه هسته اولویت بالاتری دارد)
1065
+ source = memory.get('source', '')
1066
+ if source == 'core':
1067
+ priority += 0.2
1068
+ elif source == 'long_term':
1069
+ priority += 0.1
1070
+
1071
+ return priority
1072
+
1073
+ # محاسبه اولویت و مرتب‌سازی
1074
+ prioritized = []
1075
+ for memory in memories:
1076
+ priority = calculate_priority(memory)
1077
+ prioritized.append((priority, memory))
1078
+
1079
+ prioritized.sort(key=lambda x: x[0], reverse=True)
1080
+
1081
+ return [memory for _, memory in prioritized]
1082
+
1083
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
1084
+ """تهیه context برای ارسال به API"""
1085
+
1086
+ # اگر query داریم، context هوشمند بازیابی کن
1087
+ if query:
1088
+ retrieved = await self.retrieve_context(query)
1089
+
1090
+ # تبدیل به فرمت API
1091
+ api_messages = []
1092
+
1093
+ # ابتدا اطلاعات پروفایل کاربر
1094
+ api_messages.append({
1095
+ 'role': 'system',
1096
+ 'content': f"User profile: {self._format_user_profile()}"
1097
+ })
1098
+
1099
+ # سپس حافظه‌های بازیابی شده
1100
+ for memory in retrieved:
1101
+ node = memory['node']
1102
+ api_messages.append({
1103
+ 'role': node.role,
1104
+ 'content': node.content
1105
+ })
1106
+
1107
+ return api_messages
1108
+
1109
+ else:
1110
+ # حالت ساده: فقط حافظه فعال
1111
+ api_messages = []
1112
+
1113
+ for node in list(self.memory_layers['working'])[-6:]:
1114
+ api_messages.append({
1115
+ 'role': node.role,
1116
+ 'content': node.content
1117
+ })
1118
+
1119
+ return api_messages
1120
+
1121
+ def _format_user_profile(self) -> str:
1122
+ """قالب‌بندی پروفایل کاربر برای سیستم"""
1123
+ profile_parts = []
1124
+
1125
+ if self.user_profile.interests:
1126
+ interests_str = ', '.join(list(self.user_profile.interests)[:5])
1127
+ profile_parts.append(f"Interests: {interests_str}")
1128
+
1129
+ if self.user_profile.preferences:
1130
+ prefs = list(self.user_profile.preferences.items())[:3]
1131
+ prefs_str = ', '.join(f"{k}: {v}" for k, v in prefs)
1132
+ profile_parts.append(f"Preferences: {prefs_str}")
1133
+
1134
+ if self.user_profile.conversation_style:
1135
+ profile_parts.append(f"Conversation style: {self.user_profile.conversation_style}")
1136
+
1137
+ if self.user_profile.learning_style:
1138
+ profile_parts.append(f"Learning style: {self.user_profile.learning_style}")
1139
+
1140
+ if profile_parts:
1141
+ return ' | '.join(profile_parts)
1142
+ else:
1143
+ return "New user, minimal profile information available."
1144
+
1145
+ def get_summary(self) -> Dict[str, Any]:
1146
+ """دریافت خلاصه وضعیت"""
1147
+ return {
1148
+ 'user_id': self.user_id,
1149
+ 'total_messages': self.stats['total_messages'],
1150
+ 'working_memory': len(self.memory_layers['working']),
1151
+ 'recent_memory': len(self.memory_layers['recent']),
1152
+ 'long_term_memory': len(self.memory_layers['long_term']),
1153
+ 'core_memory': len(self.memory_layers['core']),
1154
+ 'profile_interests': list(self.user_profile.interests)[:10],
1155
+ 'average_importance': self.stats['average_importance'],
1156
+ 'compression_ratio': self.stats.get('compressed_messages', 0) / max(self.stats['total_messages'], 1),
1157
+ 'retrieval_efficiency': self.stats.get('retrieved_memories', 0) / max(self.stats['total_messages'], 1)
1158
+ }
1159
+
1160
+ def clear_context(self):
1161
+ """پاک کردن context کاربر"""
1162
+ self.memory_layers['working'].clear()
1163
+ self.memory_layers['ephemeral'].clear()
1164
+
1165
+ # حافظه هسته و بلندمدت پاک نمی‌شوند
1166
+ logger.info(f"Cleared context for user {self.user_id}")
1167
+
1168
+ def export_debug_info(self) -> Dict[str, Any]:
1169
+ """دریافت اطلاعات دیباگ"""
1170
+ return {
1171
+ 'memory_graph_size': len(self.memory_graph.nodes),
1172
+ 'memory_graph_connections': len(self.memory_graph.connections),
1173
+ 'user_profile': {
1174
+ 'interests_count': len(self.user_profile.interests),
1175
+ 'preferences_count': len(self.user_profile.preferences),
1176
+ 'personality_traits': dict(self.user_profile.personality_traits)
1177
+ },
1178
+ 'layer_sizes': {k: len(v) for k, v in self.memory_layers.items()},
1179
+ 'stats': dict(self.stats)
1180
+ }
BOT/2/system_instruction_handlers.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # system_instruction_handlers.py
2
+
3
+ import logging
4
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
5
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
6
+ from datetime import datetime
7
+ import data_manager
8
+ # از admin_panel وارد کردن توابع بررسی ادمین
9
+ from admin_panel import is_admin, is_super_admin, get_admin_ids
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def is_group_admin(update: Update) -> bool:
14
+ """بررسی اینکه آیا کاربر ادمین گروه است یا خیر"""
15
+ if not update.effective_chat.type in ['group', 'supergroup']:
16
+ return False
17
+
18
+ try:
19
+ chat_id = update.effective_chat.id
20
+ user_id = update.effective_user.id
21
+
22
+ # دریافت لیست ادمین‌های گروه
23
+ chat_admins = update.effective_chat.get_administrators()
24
+
25
+ # بررسی اینکه کاربر در لیست ادمین‌ها باشد
26
+ for admin in chat_admins:
27
+ if admin.user.id == user_id:
28
+ return True
29
+
30
+ # بررسی اینکه آیا کاربر ادمین ربات است
31
+ if is_admin(user_id):
32
+ return True
33
+
34
+ return False
35
+
36
+ except Exception as e:
37
+ logger.error(f"Error checking group admin status: {e}")
38
+ return False
39
+
40
+ def check_admin_permission(update: Update) -> tuple:
41
+ """
42
+ بررسی مجوز کاربر برای دسترسی به system instruction
43
+ بازگشت: (is_allowed, is_admin_bot, is_admin_group, message)
44
+ """
45
+ user_id = update.effective_user.id
46
+ chat = update.effective_chat
47
+
48
+ is_admin_bot = is_admin(user_id)
49
+ is_admin_group = is_group_admin(update)
50
+
51
+ if chat.type in ['group', 'supergroup']:
52
+ # در گروه: باید ادمین گروه یا ادمین ربات باشد
53
+ if not (is_admin_bot or is_admin_group):
54
+ return False, False, False, "⛔️ فقط ادمین‌های گروه یا ربات می‌توانند از دستورات System Instruction استفاده کنند."
55
+ else:
56
+ # در چت خصوصی: فقط ادمین ربات مجاز است
57
+ if not is_admin_bot:
58
+ return False, False, False, "⛔️ فقط ادمین‌های ربات می‌توانند از دستورات System Instruction استفاده کنند."
59
+
60
+ return True, is_admin_bot, is_admin_group, ""
61
+
62
+ def check_global_permission(update: Update) -> tuple:
63
+ """
64
+ بررسی مجوز برای دسترسی به global instruction
65
+ فقط ادمین ربات مجاز است
66
+ """
67
+ user_id = update.effective_user.id
68
+
69
+ if not is_admin(user_id):
70
+ return False, False, "⛔️ فقط ادمین‌های ربات می‌توانند به Global System Instruction دسترسی داشته باشند."
71
+
72
+ return True, True, ""
73
+
74
+ async def set_system_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
75
+ """تنظیم system instruction - فقط برای ادمین‌ها"""
76
+ # بررسی مجوز
77
+ allowed, is_admin_bot, is_admin_group, message = check_admin_permission(update)
78
+ if not allowed:
79
+ await update.message.reply_text(message)
80
+ return
81
+
82
+ user_id = update.effective_user.id
83
+ chat = update.effective_chat
84
+
85
+ if not context.args:
86
+ await update.message.reply_text(
87
+ "⚠️ لطفاً دستور system instruction را وارد کنید.\n\n"
88
+ "مثال:\n"
89
+ "/system تو یک دستیار فارسی هستی. همیشه با ادب و مفید پاسخ بده.\n\n"
90
+ "برای حذف:\n"
91
+ "/system clear\n\n"
92
+ "برای مشاهده وضعیت فعلی:\n"
93
+ "/system_status"
94
+ )
95
+ return
96
+
97
+ instruction_text = " ".join(context.args)
98
+
99
+ if instruction_text.lower() == 'clear':
100
+ # حذف system instruction
101
+ if chat.type in ['group', 'supergroup']:
102
+ # حذف برای گروه
103
+ if is_admin_bot or is_admin_group:
104
+ if data_manager.remove_group_system_instruction(chat.id):
105
+ await update.message.reply_text("✅ system instruction گروه حذف شد.")
106
+ else:
107
+ await update.message.reply_text("⚠️ system instruction گروه وجود نداشت.")
108
+ else:
109
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
110
+ else:
111
+ # حذف برای کاربر (فقط ادمین ربات)
112
+ if is_admin_bot:
113
+ if data_manager.remove_user_system_instruction(user_id):
114
+ await update.message.reply_text("✅ system instruction شخصی شما حذف شد.")
115
+ else:
116
+ await update.message.reply_text("⚠️ system instruction شخصی وجود نداشت.")
117
+ else:
118
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی را حذف کنند.")
119
+ return
120
+
121
+ # تنظیم system instruction جدید
122
+ if chat.type in ['group', 'supergroup']:
123
+ # تنظیم برای گروه
124
+ if is_admin_bot or is_admin_group:
125
+ if data_manager.set_group_system_instruction(chat.id, instruction_text, user_id):
126
+ instruction_preview = instruction_text[:500] + "..." if len(instruction_text) > 100 else instruction_text
127
+ await update.message.reply_text(
128
+ f"✅ system instruction گروه تنظیم شد:\n\n"
129
+ f"{instruction_preview}\n\n"
130
+ f"از این پس تمام پاسخ‌های ربات در این گروه با این دستور تنظیم خواهد شد."
131
+ )
132
+ else:
133
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
134
+ else:
135
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
136
+ else:
137
+ # تنظیم برای کاربر (فقط ادمین ربات)
138
+ if is_admin_bot:
139
+ if data_manager.set_user_system_instruction(user_id, instruction_text, user_id):
140
+ instruction_preview = instruction_text[:500] + "..." if len(instruction_text) > 100 else instruction_text
141
+ await update.message.reply_text(
142
+ f"✅ system instruction شخصی تنظیم شد:\n\n"
143
+ f"{instruction_preview}\n\n"
144
+ f"از این پس تمام پاسخ‌های ربات به شما با این دستور تنظیم خواهد شد."
145
+ )
146
+ else:
147
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
148
+ else:
149
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی تنظیم کنند.")
150
+
151
+ async def system_instruction_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
152
+ """نمایش وضعیت system instruction فعلی - با محدودیت دسترسی"""
153
+ user_id = update.effective_user.id
154
+ chat = update.effective_chat
155
+
156
+ is_admin_bot = is_admin(user_id)
157
+ is_admin_group = is_group_admin(update)
158
+
159
+ if chat.type in ['group', 'supergroup']:
160
+ # در گروه
161
+ if not (is_admin_bot or is_admin_group):
162
+ await update.message.reply_text(
163
+ "⚙️ **System Instruction گروه:**\n\n"
164
+ "تنظیمات System Instruction فقط برای ادمین‌های گروه قابل مشاهده است.\n"
165
+ "برای مشاهده وضعیت فعلی، با ادمین‌های گروه تماس بگیرید."
166
+ )
167
+ return
168
+
169
+ # کاربر مجاز است (ادمین ربات یا ادمین گروه)
170
+ if is_admin_bot:
171
+ # ادمین ربات: می‌تواند global و group instruction را ببیند
172
+ await show_admin_bot_status(update, context, chat.id, user_id, in_group=True)
173
+ else:
174
+ # ادمین گروه (نه ادمین ربات): فقط group instruction گروه خودش را می‌بیند
175
+ await show_group_admin_status(update, context, chat.id)
176
+ else:
177
+ # در چت خصوصی
178
+ if not is_admin_bot:
179
+ await update.message.reply_text(
180
+ "⚙️ **System Instruction:**\n\n"
181
+ "تنظیمات System Instruction فقط برای ادمین‌های ربات قابل مشاهده است."
182
+ )
183
+ return
184
+
185
+ # ادمین ربات در چت خصوصی
186
+ await show_admin_bot_status(update, context, None, user_id, in_group=False)
187
+
188
+ async def show_group_admin_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int):
189
+ """نمایش وضعیت برای ادمین گروه (نه ادمین ربات)"""
190
+ # فقط system instruction گروه را نشان بده
191
+ info = data_manager.get_system_instruction_info(chat_id=chat_id)
192
+
193
+ if info['type'] == 'group' and info['has_instruction']:
194
+ # نمایش اطلاعات group instruction
195
+ details = info['details']
196
+ instruction_preview = info['instruction'][:500] + "..." if len(info['instruction']) > 200 else info['instruction']
197
+ set_at = details.get('set_at', 'نامشخص')
198
+ set_by = details.get('set_by', 'نامشخص')
199
+ enabled = details.get('enabled', True)
200
+
201
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
202
+
203
+ status_text = (
204
+ f"👥 **System Instruction گروه شما:**\n\n"
205
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
206
+ f"📅 **زمان تنظیم:** {set_at}\n"
207
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
208
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
209
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
210
+ )
211
+
212
+ # دکمه‌های مدیریت فقط برای group instruction
213
+ keyboard = [
214
+ [
215
+ InlineKeyboardButton("✏️ ویرایش", callback_data=f"system_edit:group:{chat_id}"),
216
+ InlineKeyboardButton("🗑️ حذف", callback_data=f"system_delete:group:{chat_id}")
217
+ ]
218
+ ]
219
+
220
+ if enabled:
221
+ keyboard.append([
222
+ InlineKeyboardButton("🚫 غیرفعال", callback_data=f"system_toggle:group:{chat_id}")
223
+ ])
224
+ else:
225
+ keyboard.append([
226
+ InlineKeyboardButton("✅ فعال", callback_data=f"system_toggle:group:{chat_id}")
227
+ ])
228
+
229
+ reply_markup = InlineKeyboardMarkup(keyboard)
230
+ else:
231
+ # هیچ system instruction برای گروه تنظیم نشده
232
+ status_text = (
233
+ f"👥 **System Instruction گروه شما:**\n\n"
234
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
235
+ f"برای تنظیم از دستور زیر استفاده کنید:\n"
236
+ f"`/system [متن دستور]`\n\n"
237
+ f"در حال حاضر از تنظیمات global ربات استفاده می‌شود."
238
+ )
239
+
240
+ # فقط دکمه تنظیم
241
+ keyboard = [
242
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")]
243
+ ]
244
+ reply_markup = InlineKeyboardMarkup(keyboard)
245
+
246
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
247
+
248
+ async def show_admin_bot_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int = None, user_id: int = None, in_group: bool = False):
249
+ """نمایش وضعیت برای ادمین ربات"""
250
+ if in_group and chat_id:
251
+ # ادمین ربات در گروه
252
+ group_info = data_manager.get_system_instruction_info(chat_id=chat_id)
253
+ global_info = data_manager.get_system_instruction_info()
254
+
255
+ if group_info['type'] == 'group' and group_info['has_instruction']:
256
+ # گروه system instruction دارد
257
+ details = group_info['details']
258
+ instruction_preview = group_info['instruction'][:500] + "..." if len(group_info['instruction']) > 200 else group_info['instruction']
259
+ set_at = details.get('set_at', 'نامشخص')
260
+ set_by = details.get('set_by', 'نامشخص')
261
+ enabled = details.get('enabled', True)
262
+
263
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
264
+
265
+ status_text = (
266
+ f"👥 **System Instruction گروه:**\n\n"
267
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
268
+ f"📅 **زمان تنظیم:** {set_at}\n"
269
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
270
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
271
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
272
+ )
273
+
274
+ # دکمه‌های مدیریت برای group instruction
275
+ keyboard = [
276
+ [
277
+ InlineKeyboardButton("✏️ ویرایش گروه", callback_data=f"system_edit:group:{chat_id}"),
278
+ InlineKeyboardButton("🗑️ حذف گروه", callback_data=f"system_delete:group:{chat_id}")
279
+ ]
280
+ ]
281
+
282
+ if enabled:
283
+ keyboard.append([
284
+ InlineKeyboardButton("🚫 غیرفعال گروه", callback_data=f"system_toggle:group:{chat_id}")
285
+ ])
286
+ else:
287
+ keyboard.append([
288
+ InlineKeyboardButton("✅ فعال گروه", callback_data=f"system_toggle:group:{chat_id}")
289
+ ])
290
+
291
+ # دکمه برای مشاهده global instruction
292
+ keyboard.append([
293
+ InlineKeyboardButton("🌐 مشاهده Global", callback_data="system_show_global")
294
+ ])
295
+
296
+ reply_markup = InlineKeyboardMarkup(keyboard)
297
+ else:
298
+ # گروه system instruction ندارد
299
+ global_preview = global_info['instruction'][:500] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
300
+
301
+ status_text = (
302
+ f"👥 **System Instruction گروه:**\n\n"
303
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
304
+ f"🌐 **در حال استفاده از Global:**\n"
305
+ f"{global_preview}\n\n"
306
+ f"برای تنظیم system instruction مخصوص این گروه از دستور `/system [متن]` استفاده کنید."
307
+ )
308
+
309
+ keyboard = [
310
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")],
311
+ [InlineKeyboardButton("🌐 مشاهده کامل Global", callback_data="system_show_global")]
312
+ ]
313
+ reply_markup = InlineKeyboardMarkup(keyboard)
314
+ else:
315
+ # ادمین ربات در چت خصوصی
316
+ global_info = data_manager.get_system_instruction_info()
317
+ global_preview = global_info['instruction'][:500] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
318
+
319
+ status_text = (
320
+ f"🌐 **Global System Instruction:**\n\n"
321
+ f"📝 **محتوا:**\n{global_preview}\n\n"
322
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
323
+ )
324
+
325
+ keyboard = [
326
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
327
+ ]
328
+ reply_markup = InlineKeyboardMarkup(keyboard)
329
+
330
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
331
+
332
+ async def show_global_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
333
+ """نمایش کامل global instruction - فقط برای ادمین ربات"""
334
+ query = update.callback_query
335
+ if query:
336
+ await query.answer()
337
+ user_id = query.from_user.id
338
+ else:
339
+ user_id = update.effective_user.id
340
+
341
+ # بررسی مجوز
342
+ if not is_admin(user_id):
343
+ if query:
344
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
345
+ else:
346
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
347
+ return
348
+
349
+ global_info = data_manager.get_system_instruction_info()
350
+ global_preview = global_info['instruction']
351
+
352
+ if len(global_preview) > 1000:
353
+ global_preview = global_preview[:1000] + "...\n\n(متن کامل به دلیل طولانی بودن نمایش داده نشد)"
354
+
355
+ status_text = (
356
+ f"🌐 **Global System Instruction (کامل):**\n\n"
357
+ f"📝 **محتوا:**\n{global_preview}\n\n"
358
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
359
+ )
360
+
361
+ keyboard = [
362
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
363
+ ]
364
+ reply_markup = InlineKeyboardMarkup(keyboard)
365
+
366
+ if query:
367
+ await query.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
368
+ else:
369
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
370
+
371
+ async def system_instruction_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
372
+ """نمایش راهنمای system instruction - با محدودیت دسترسی"""
373
+ user_id = update.effective_user.id
374
+ chat = update.effective_chat
375
+
376
+ is_admin_bot = is_admin(user_id)
377
+ is_admin_group = is_group_admin(update)
378
+
379
+ if chat.type in ['group', 'supergroup']:
380
+ # در گروه
381
+ if not (is_admin_bot or is_admin_group):
382
+ await update.message.reply_text(
383
+ "🤖 **راهنمای System Instruction**\n\n"
384
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
385
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های گروه یا ربات در دسترس است.\n\n"
386
+ "برای تنظیم System Instruction در این گروه، با ادمین‌های گروه تماس بگیرید."
387
+ )
388
+ return
389
+
390
+ # کاربر مجاز است
391
+ help_text = (
392
+ "🤖 **راهنمای System Instruction**\n\n"
393
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
394
+ "📋 **دستورات:**\n"
395
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
396
+ "• `/system clear` - حذف system instruction این گروه\n"
397
+ "• `/system_status` - نمایش وضعیت فعلی\n"
398
+ "• `/system_help` - نمایش این راهنما\n\n"
399
+ )
400
+
401
+ if is_admin_bot:
402
+ help_text += (
403
+ "🎯 **دسترسی ادمین ربات:**\n"
404
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
405
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
406
+ "• برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n\n"
407
+ )
408
+ else:
409
+ help_text += (
410
+ "🎯 **دسترسی ادمین گروه:**\n"
411
+ "• فقط می‌توانید system instruction همین گروه را مشاهده و تنظیم کنید\n"
412
+ "• نمی‌توانید Global System Instruction را مشاهده کنید\n\n"
413
+ )
414
+
415
+ help_text += (
416
+ "💡 **مثال‌ها:**\n"
417
+ "• `/system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n"
418
+ "• `/system تو یک ربات جوک‌گو هستی. به هر سوالی با یک جوک پاسخ بده.`\n\n"
419
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
420
+ )
421
+ else:
422
+ # در چت خصوصی
423
+ if not is_admin_bot:
424
+ await update.message.reply_text(
425
+ "🤖 **راهنمای System Instruction**\n\n"
426
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
427
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های ربات در دسترس است."
428
+ )
429
+ return
430
+
431
+ # ادمین ربات
432
+ help_text = (
433
+ "🤖 **راهنمای System Instruction**\n\n"
434
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
435
+ "📋 **دستورات:**\n"
436
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
437
+ "• `/system_help` - نمایش این راهنما\n\n"
438
+ "🎯 **دسترسی ادمین ربات:**\n"
439
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
440
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
441
+ "• می‌توانید برای هر کاربر system instruction تنظیم کنید\n\n"
442
+ "🔧 **دستورات ادمین پنل برای System Instruction:**\n"
443
+ "• `/set_global_system [متن]` - تنظیم Global System Instruction\n"
444
+ "• `/set_group_system [آیدی گروه] [متن]` - تنظیم برای گروه\n"
445
+ "• `/set_user_system [آیدی کاربر] [متن]` - تنظیم برای کاربر\n"
446
+ "• `/list_system_instructions` - نمایش لیست تمام system instruction‌ها\n\n"
447
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
448
+ )
449
+
450
+ await update.message.reply_text(help_text, parse_mode='Markdown')
451
+
452
+ async def system_callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
453
+ """پردازش کلیک‌های دکمه‌های system instruction"""
454
+ query = update.callback_query
455
+ await query.answer()
456
+
457
+ data_parts = query.data.split(":")
458
+ action = data_parts[0]
459
+ user_id = query.from_user.id
460
+
461
+ if action == 'system_show_global':
462
+ # نمایش global instruction
463
+ await show_global_instruction(update, context)
464
+ return
465
+
466
+ if len(data_parts) < 3:
467
+ await query.message.reply_text("❌ خطا در پردازش درخواست.")
468
+ return
469
+
470
+ entity_type = data_parts[1]
471
+ entity_id = data_parts[2]
472
+
473
+ # بررسی مجوزها
474
+ if entity_type == 'global':
475
+ # فقط ادمین ربات می‌تواند global را مدیریت کند
476
+ if not is_admin(user_id):
477
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مدیریت کنند.")
478
+ return
479
+
480
+ entity_id_int = 0 # global entity
481
+ elif entity_type == 'group':
482
+ # بررسی اینکه آیا کاربر ادمین گروه یا ادمین ربات است
483
+ chat = query.message.chat
484
+ is_admin_bot = is_admin(user_id)
485
+ is_admin_group = is_group_admin(update)
486
+
487
+ if not (is_admin_bot or is_admin_group):
488
+ await query.message.reply_text("⛔️ شما مجوز لازم برای این کار را ندارید.")
489
+ return
490
+
491
+ try:
492
+ entity_id_int = int(entity_id)
493
+ except ValueError:
494
+ await query.message.reply_text("❌ شناسه گروه نامعتبر است.")
495
+ return
496
+ else: # user
497
+ # فقط ادمین ربات می‌تواند system instruction کاربران را تغییر دهد
498
+ if not is_admin(user_id):
499
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را تغییر دهند.")
500
+ return
501
+
502
+ try:
503
+ entity_id_int = int(entity_id)
504
+ except ValueError:
505
+ await query.message.reply_text("❌ شناسه کاربر نامعتبر است.")
506
+ return
507
+
508
+ if action == 'system_delete':
509
+ # حذف system instruction
510
+ if entity_type == 'global':
511
+ # حذف global (در واقع تنظیم مجدد به پیش‌فرض)
512
+ default_instruction = "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد."
513
+ if data_manager.set_global_system_instruction(default_instruction):
514
+ await query.message.reply_text("✅ Global System Instruction به حالت پیش‌فرض بازگردانده شد.")
515
+ else:
516
+ await query.message.reply_text("❌ خطا در بازگرداندن Global System Instruction.")
517
+ elif entity_type == 'group':
518
+ success = data_manager.remove_group_system_instruction(entity_id_int)
519
+ message = "✅ system instruction گروه حذف شد." if success else "⚠️ system instruction گروه وجود نداشت."
520
+ else:
521
+ success = data_manager.remove_user_system_instruction(entity_id_int)
522
+ message = "✅ system instruction کاربر حذف شد." if success else "⚠️ system instruction کاربر وجود نداشت."
523
+
524
+ if entity_type != 'global':
525
+ await query.message.reply_text(message)
526
+
527
+ await query.message.delete()
528
+
529
+ elif action == 'system_toggle':
530
+ # فعال/غیرفعال کردن system instruction
531
+ if entity_type == 'global':
532
+ await query.message.reply_text("⚠️ Global System Instruction را نمی‌توان غیرفعال کرد.")
533
+ return
534
+
535
+ info = data_manager.get_system_instruction_info(
536
+ user_id=entity_id_int if entity_type == 'user' else None,
537
+ chat_id=entity_id_int if entity_type == 'group' else None
538
+ )
539
+
540
+ if info['type'] == entity_type and info['details']:
541
+ current_enabled = info['details'].get('enabled', True)
542
+ new_enabled = not current_enabled
543
+
544
+ if entity_type == 'group':
545
+ success = data_manager.toggle_group_system_instruction(entity_id_int, new_enabled)
546
+ else:
547
+ success = data_manager.toggle_user_system_instruction(entity_id_int, new_enabled)
548
+
549
+ if success:
550
+ status = "✅ فعال شد" if new_enabled else "🚫 غیرفعال شد"
551
+ await query.message.reply_text(f"system instruction {status}.")
552
+
553
+ # به‌روزرسانی پیام اصلی
554
+ if entity_type == 'group':
555
+ await show_group_admin_status(update, context, entity_id_int)
556
+ else:
557
+ await system_instruction_status(update, context)
558
+ else:
559
+ await query.message.reply_text("❌ خطا در تغییر وضعیت system instruction.")
560
+
561
+ elif action == 'system_edit':
562
+ # ویرایش system instruction
563
+ if entity_type == 'global':
564
+ instruction_type = "Global"
565
+ elif entity_type == 'group':
566
+ instruction_type = "گروه"
567
+ else:
568
+ instruction_type = "کاربر"
569
+
570
+ await query.message.reply_text(
571
+ f"لطفاً system instruction جدید برای {instruction_type} را وارد کنید:\n\n"
572
+ "برای لغو: /cancel"
573
+ )
574
+
575
+ # ذخیره اطلاعات برای مرحله بعد
576
+ context.user_data['system_edit'] = {
577
+ 'entity_type': entity_type,
578
+ 'entity_id': entity_id_int,
579
+ 'message_id': query.message.message_id
580
+ }
581
+
582
+ async def handle_system_edit(update: Update, context: ContextTypes.DEFAULT_TYPE):
583
+ """پردازش ویرایش system instruction"""
584
+ # بررسی مجوز اولیه
585
+ user_id = update.effective_user.id
586
+ chat = update.effective_chat
587
+
588
+ if 'system_edit' not in context.user_data:
589
+ return
590
+
591
+ if update.message.text.lower() == '/cancel':
592
+ del context.user_data['system_edit']
593
+ await update.message.reply_text("ویرایش system instruction لغو شد.")
594
+ return
595
+
596
+ edit_data = context.user_data['system_edit']
597
+ entity_type = edit_data['entity_type']
598
+ entity_id = edit_data['entity_id']
599
+
600
+ # بررسی مجوزهای خاص
601
+ if entity_type == 'global':
602
+ if not is_admin(user_id):
603
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را ویرایش کنند.")
604
+ del context.user_data['system_edit']
605
+ return
606
+ elif entity_type == 'group':
607
+ is_admin_bot = is_admin(user_id)
608
+ is_admin_group = is_group_admin(update)
609
+
610
+ if not (is_admin_bot or is_admin_group):
611
+ await update.message.reply_text("⛔️ شما مجوز لازم برای ویرایش system instruction این گروه را ندارید.")
612
+ del context.user_data['system_edit']
613
+ return
614
+ else: # user
615
+ if not is_admin(user_id):
616
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را ویرایش کنند.")
617
+ del context.user_data['system_edit']
618
+ return
619
+
620
+ instruction_text = update.message.text
621
+
622
+ if entity_type == 'global':
623
+ success = data_manager.set_global_system_instruction(instruction_text)
624
+ message = "✅ Global System Instruction به‌روزرسانی شد."
625
+ elif entity_type == 'group':
626
+ success = data_manager.set_group_system_instruction(entity_id, instruction_text, user_id)
627
+ message = "✅ system instruction گروه به‌روزرسانی شد."
628
+ else:
629
+ success = data_manager.set_user_system_instruction(entity_id, instruction_text, user_id)
630
+ message = "✅ system instruction کاربر به‌روزرسانی شد."
631
+
632
+ if success:
633
+ await update.message.reply_text(message)
634
+ del context.user_data['system_edit']
635
+
636
+ # نمایش وضعیت جدید
637
+ await system_instruction_status(update, context)
638
+ else:
639
+ await update.message.reply_text("❌ خطا در به‌روزرسانی system instruction.")
640
+
641
+ def setup_system_instruction_handlers(application):
642
+ """تنظیم هندلرهای system instruction"""
643
+ application.add_handler(CommandHandler("system", set_system_instruction))
644
+ application.add_handler(CommandHandler("system_status", system_instruction_status))
645
+ application.add_handler(CommandHandler("system_help", system_instruction_help))
646
+
647
+ # هندلر برای نمایش global instruction
648
+ application.add_handler(CommandHandler("show_global", show_global_instruction))
649
+
650
+ application.add_handler(CallbackQueryHandler(system_callback_handler, pattern="^system_"))
651
+
652
+ # هندلر برای ویرایش system instruction
653
+ application.add_handler(MessageHandler(
654
+ filters.TEXT & ~filters.COMMAND,
655
+ handle_system_edit
656
+ ))
657
+
658
+ logger.info("System instruction handlers have been set up.")
BOT/render-main (4).zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91ba6e7769c8bfdb807a5b999dd262cf94f6e09aaa69d5d3c15923d7ab89e176
3
+ size 50840
BOT/render-main/FIXES/STORED.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py - اصلاح تابع retrieve_context
2
+
3
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
4
+ """بازیابی هوشمند context مرتبط با query"""
5
+
6
+ if max_tokens is None:
7
+ max_tokens = self.max_context_tokens
8
+
9
+ start_time = datetime.now()
10
+
11
+ # 1. دریافت embedding برای query
12
+ query_embedding = self.embedding_manager.get_embedding(query)
13
+
14
+ # 2. بازیابی از لایه‌های مختلف حافظه
15
+ retrieved_memories = []
16
+
17
+ # از حافظه فعال (همیشه)
18
+ retrieved_memories.extend(self._retrieve_from_working_memory())
19
+
20
+ # از حافظه اخیر (بر اساس شباهت)
21
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
22
+ retrieved_memories.extend(recent_memories)
23
+
24
+ # از حافظه بلندمدت (اطلاعات مهم)
25
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
26
+ retrieved_memories.extend(long_term_memories)
27
+
28
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
29
+ core_memories = self._retrieve_core_memories(query)
30
+ retrieved_memories.extend(core_memories)
31
+
32
+ # 3. حذف تکراری‌ها و مرتب‌سازی
33
+ unique_memories = self._deduplicate_memories(retrieved_memories)
34
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
35
+
36
+ # 4. انتخاب تا سقف توکن
37
+ final_context = []
38
+ total_tokens = 0
39
+
40
+ for memory in prioritized_memories:
41
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
42
+
43
+ if total_tokens + memory_tokens <= max_tokens:
44
+ final_context.append(memory)
45
+ total_tokens += memory_tokens
46
+ else:
47
+ break
48
+
49
+ # 5. به‌روزرسانی آمار
50
+ self.stats['retrieved_memories'] += len(final_context)
51
+
52
+ retrieval_time = (datetime.now() - start_time).total_seconds()
53
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
54
+
55
+ return final_context
56
+
57
+ # اصلاح تابع get_context_for_api
58
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
59
+ """تهیه context برای ارسال به API"""
60
+
61
+ # اگر query داریم، context هوشمند بازیابی کن
62
+ if query:
63
+ retrieved = await self.retrieve_context(query)
64
+
65
+ # تبدیل به فرمت API
66
+ api_messages = []
67
+
68
+ # ابتدا اطلاعات پروفایل کاربر
69
+ api_messages.append({
70
+ 'role': 'system',
71
+ 'content': f"User profile: {self._format_user_profile()}"
72
+ })
73
+
74
+ # سپس حافظه‌های بازیابی شده
75
+ for memory in retrieved:
76
+ node = memory['node']
77
+ api_messages.append({
78
+ 'role': node.role,
79
+ 'content': node.content
80
+ })
81
+
82
+ return api_messages
83
+
84
+ else:
85
+ # حالت ساده: فقط حافظه فعال
86
+ api_messages = []
87
+
88
+ for node in list(self.memory_layers['working'])[-6:]:
89
+ api_messages.append({
90
+ 'role': node.role,
91
+ 'content': node.content
92
+ })
93
+
94
+ return api_messages
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ # main.py - اصلاح تابع _process_user_request
114
+
115
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
116
+ chat_id = update.effective_chat.id
117
+ user_message = update.message.text
118
+ user_id = update.effective_user.id
119
+
120
+ start_time = time.time()
121
+
122
+ try:
123
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
124
+
125
+ # استفاده از Context هوشمند اگر فعال باشد
126
+ if HAS_SMART_CONTEXT:
127
+ smart_context = _get_or_create_smart_context(user_id)
128
+
129
+ # پردازش پیام کاربر با سیستم هوشمند
130
+ await smart_context.process_message("user", user_message)
131
+
132
+ # بازیابی context مرتبط
133
+ retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)
134
+
135
+ # آماده‌سازی پیام‌ها برای API
136
+ messages = await smart_context.get_context_for_api(user_message)
137
+
138
+ logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")
139
+ else:
140
+ # استفاده از سیستم قدیمی
141
+ user_context = data_manager.get_context_for_api(user_id)
142
+ data_manager.add_to_user_context(user_id, "user", user_message)
143
+ messages = user_context.copy()
144
+ messages.append({"role": "user", "content": user_message})
145
+
146
+ # ارسال به API
147
+ response = await client.chat.completions.create(
148
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
149
+ messages=messages,
150
+ temperature=1.0,
151
+ top_p=0.95,
152
+ stream=False,
153
+ )
154
+
155
+ end_time = time.time()
156
+ response_time = end_time - start_time
157
+ data_manager.update_response_stats(response_time)
158
+
159
+ ai_response = response.choices[0].message.content
160
+
161
+ # ذخیره پاسخ در سیستم مناسب
162
+ if HAS_SMART_CONTEXT:
163
+ await smart_context.process_message("assistant", ai_response)
164
+ else:
165
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
166
+
167
+ await update.message.reply_text(ai_response)
168
+ data_manager.update_user_stats(user_id, update.effective_user)
169
+
170
+ except httpx.TimeoutException:
171
+ logger.warning(f"Request timed out for user {user_id}.")
172
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
173
+ except Exception as e:
174
+ logger.error(f"Error while processing message for user {user_id}: {e}")
175
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+ # smart_context.py - اصلاح توابع async
194
+
195
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
196
+ layer: str) -> List[Dict[str, Any]]:
197
+ """بازیابی حافظه‌های معنایی"""
198
+ memories = []
199
+
200
+ if layer not in self.memory_layers:
201
+ return memories
202
+
203
+ layer_memories = self.memory_layers[layer]
204
+
205
+ for item in layer_memories:
206
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
207
+
208
+ if node and node.embeddings is not None:
209
+ similarity = self.embedding_manager.cosine_similarity(
210
+ query_embedding, node.embeddings
211
+ )
212
+
213
+ if similarity > self.semantic_similarity_threshold:
214
+ recency_weight = 1.0 if layer == 'working' else 0.7
215
+
216
+ memories.append({
217
+ 'node': node,
218
+ 'source': layer,
219
+ 'relevance': similarity,
220
+ 'recency': recency_weight,
221
+ 'importance': node.importance_score
222
+ })
223
+
224
+ return memories
225
+
226
+ # اصلاح تابع process_message برای جلوگیری از block کردن
227
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
228
+ """پرداش کامل یک پیام جدید"""
229
+ start_time = datetime.now()
230
+
231
+ # 1. تحلیل پیام
232
+ analysis = self.analyzer.analyze_message(content, role)
233
+
234
+ # 2. ایجاد گره حافظه
235
+ message_id = self._generate_message_id(content)
236
+
237
+ # ایجاد embedding به صورت غیرهمزمان
238
+ embedding_task = asyncio.create_task(
239
+ self._get_embedding_async(content)
240
+ )
241
+
242
+ node = MessageNode(
243
+ id=message_id,
244
+ content=content,
245
+ role=role,
246
+ timestamp=datetime.now(),
247
+ message_type=analysis['type'],
248
+ importance_score=analysis['importance'],
249
+ emotion_score=analysis['emotion'],
250
+ tokens=data_manager.count_tokens(content),
251
+ embeddings=None, # موقتاً None
252
+ metadata={
253
+ 'analysis': analysis,
254
+ 'topics': analysis['topics'],
255
+ 'intent': analysis['intent'],
256
+ 'complexity': analysis['complexity']
257
+ }
258
+ )
259
+
260
+ # دریافت embedding (اگر موجود باشد)
261
+ try:
262
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
263
+ except asyncio.TimeoutError:
264
+ logger.warning(f"Embedding generation timeout for message {message_id}")
265
+ node.embeddings = self.embedding_manager.get_embedding(content)
266
+
267
+ # 3. افزودن به حافظه و گراف
268
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
269
+ await asyncio.to_thread(self.memory_graph.add_node, node)
270
+
271
+ # 4. ایجاد ارتباطات
272
+ await asyncio.to_thread(self._create_memory_connections, node)
273
+
274
+ # 5. به‌روزرسانی پروفایل کاربر
275
+ if role == 'user':
276
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
277
+
278
+ # 6. بهینه‌سازی حافظه
279
+ await asyncio.to_thread(self._optimize_memory)
280
+
281
+ # 7. به‌روزرسانی آمار
282
+ self.stats['total_messages'] += 1
283
+ self.stats['average_importance'] = (
284
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
285
+ analysis['importance']
286
+ ) / self.stats['total_messages']
287
+
288
+ # 8. ذخیره داده‌ها
289
+ await asyncio.to_thread(self._save_data)
290
+
291
+ processing_time = (datetime.now() - start_time).total_seconds()
292
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
293
+
294
+ return {
295
+ 'node_id': message_id,
296
+ 'analysis': analysis,
297
+ 'processing_time': processing_time
298
+ }
299
+
300
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
301
+ """دریافت embedding به صورت async"""
302
+ loop = asyncio.get_event_loop()
303
+ return await loop.run_in_executor(
304
+ None,
305
+ self.embedding_manager.get_embedding,
306
+ text
307
+ )
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+ # admin_panel.py - اصلاح توابع async در smart_context
338
+
339
+ @admin_only
340
+ async def admin_smart_context_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
341
+ """نمایش آمار context هوشمند برای کاربران"""
342
+ if not HAS_SMART_CONTEXT:
343
+ await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
344
+ return
345
+
346
+ if not context.args:
347
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/smart_stats 123456789`")
348
+ return
349
+
350
+ user_id = int(context.args[0])
351
+
352
+ # بررسی وجود مدیر context
353
+ if user_id not in smart_context_managers:
354
+ smart_context_managers[user_id] = IntelligentContextManager(user_id)
355
+
356
+ smart_context = smart_context_managers[user_id]
357
+ summary = await asyncio.to_thread(smart_context.get_summary)
358
+
359
+ # ... بقیه کد بدون تغییر
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+ # smart_context.py - اضافه کردن خطاگیری بهتر
388
+
389
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
390
+ """بازیابی هوشمند context مرتبط با query"""
391
+ try:
392
+ if max_tokens is None:
393
+ max_tokens = self.max_context_tokens
394
+
395
+ start_time = datetime.now()
396
+
397
+ # دریافت embedding با timeout
398
+ try:
399
+ embedding_task = asyncio.create_task(
400
+ self._get_embedding_async(query)
401
+ )
402
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
403
+ except asyncio.TimeoutError:
404
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
405
+ query_embedding = self.embedding_manager.get_embedding(query)
406
+
407
+ # بازیابی از حافظه‌های مختلف به صورت موازی
408
+ tasks = []
409
+
410
+ # حافظه فعال
411
+ tasks.append(asyncio.create_task(
412
+ asyncio.to_thread(self._retrieve_from_working_memory)
413
+ ))
414
+
415
+ # حافظه معنایی
416
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
417
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
418
+
419
+ # حافظه هسته
420
+ tasks.append(asyncio.create_task(
421
+ asyncio.to_thread(self._retrieve_core_memories, query)
422
+ ))
423
+
424
+ # اجرای موازی همه tasks
425
+ results = await asyncio.gather(*tasks, return_exceptions=True)
426
+
427
+ # جمع‌آوری نتایج
428
+ retrieved_memories = []
429
+ for result in results:
430
+ if isinstance(result, Exception):
431
+ logger.error(f"Error retrieving memory: {result}")
432
+ continue
433
+ retrieved_memories.extend(result)
434
+
435
+ # ادامه پردازش...
436
+ # ... بقیه کد بدون تغییر
437
+
438
+ except Exception as e:
439
+ logger.error(f"Error in retrieve_context: {e}")
440
+ # Fallback: برگرداندن حافظه فعال
441
+ return self._retrieve_from_working_memory()
BOT/render-main/FIXES/admin_panel.py ADDED
@@ -0,0 +1,1837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin_panel.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import csv
7
+ import io
8
+ import asyncio
9
+ from datetime import datetime, timedelta
10
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
11
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler
12
+ from telegram.error import TelegramError
13
+
14
+ import matplotlib
15
+ matplotlib.use('Agg')
16
+ import matplotlib.pyplot as plt
17
+ import pandas as pd
18
+ import tempfile
19
+ import psutil
20
+ import platform
21
+ import time
22
+
23
+ # --- تنظیمات ---
24
+ # خواندن ADMIN_IDS از محیط
25
+ ENV_ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
26
+
27
+ import data_manager
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # تابع برای دریافت لیست کامل ادمین‌ها
32
+ def get_admin_ids():
33
+ """دریافت لیست کامل ادمین‌ها"""
34
+ env_admins = ENV_ADMIN_IDS
35
+ added_admins = data_manager.DATA.get('added_admins', [])
36
+ all_admins = list(set(env_admins + added_admins))
37
+ return all_admins
38
+
39
+ # تابع برای بررسی ادمین ارشد بودن
40
+ def is_super_admin(user_id: int) -> bool:
41
+ """بررسی اینکه آیا کاربر ادمین ارشد است"""
42
+ return user_id in ENV_ADMIN_IDS
43
+
44
+ # تابع برای بررسی اینکه کاربر ادمین است
45
+ def is_admin(user_id: int) -> bool:
46
+ """بررسی اینکه آیا کاربر ادمین است"""
47
+ return user_id in get_admin_ids()
48
+
49
+ # --- دکوراتور برای دسترسی ادمین ---
50
+ def admin_only(func):
51
+ async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
52
+ if update.effective_user.id not in get_admin_ids():
53
+ await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
54
+ return
55
+ return await func(update, context, *args, **kwargs)
56
+ return wrapped
57
+
58
+
59
+ # --- هندلرهای جدید برای Hybrid پیشرفته ---
60
+ @admin_only
61
+ async def admin_set_hybrid_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
62
+ """تنظیم حالت Hybrid پیشرفته"""
63
+ if not context.args:
64
+ await update.message.reply_text(
65
+ "⚠️ فرمت صحیح: `/set_hybrid_mode [basic|advanced]`\n\n"
66
+ "🎯 **مزایای حالت Advanced:**\n"
67
+ "✅ مدیریت همزمان چند کاربر\n"
68
+ "✅ حفظ تاریخچه شخصی هر کاربر\n"
69
+ "✅ آگاهی از تاریخچه گروه\n"
70
+ "✅ در نظر گرفتن اطلاعات شخصی کاربران دیگر\n"
71
+ "✅ پاسخ‌های دقیق و شخصی‌سازی شده\n\n"
72
+ "🎯 **حالت Basic:**\n"
73
+ "✅ تاریخچه شخصی + تاریخچه گروه\n"
74
+ "✅ پاسخ‌های ترکیبی\n\n"
75
+ "پیش‌فرض: advanced"
76
+ )
77
+ return
78
+
79
+ mode = context.args[0].lower()
80
+
81
+ if mode not in ['basic', 'advanced']:
82
+ await update.message.reply_text("⚠️ حالت نامعتبر. گزینه‌های موجود: basic, advanced")
83
+ return
84
+
85
+ if data_manager.set_hybrid_mode(mode):
86
+ if mode == 'advanced':
87
+ await update.message.reply_text(
88
+ "✅ **حالت Hybrid پیشرفته فعال شد!**\n\n"
89
+ "🎯 **ویژگی‌های فعال:**\n"
90
+ "• مدیریت همزمان چند کاربر\n"
91
+ "• حفظ تاریخچه شخصی هر کاربر\n"
92
+ "• آگاهی از تاریخچه گروه\n"
93
+ "• در نظر گرفتن اطلاعات شخصی کاربران دیگر\n"
94
+ "• پاسخ‌های دقیق و شخصی‌سازی شده\n\n"
95
+ "ربات اکنون می‌تواند به طور همزمان با چند کاربر کار کند و هر کاربر را به طور جداگانه تشخیص دهد."
96
+ )
97
+ else:
98
+ await update.message.reply_text("✅ حالت Hybrid ساده فعال شد.")
99
+ else:
100
+ await update.message.reply_text("❌ خطا در تنظیم حالت Hybrid.")
101
+
102
+
103
+
104
+ @admin_only
105
+ async def admin_hybrid_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
106
+ """نمایش وضعیت Hybrid"""
107
+ hybrid_settings = data_manager.DATA.get('hybrid_settings', {})
108
+ context_mode = data_manager.get_context_mode()
109
+
110
+ status_text = (
111
+ f"🎯 **وضعیت سیستم Hybrid**\n\n"
112
+ f"📊 **حالت کلی:** {context_mode}\n"
113
+ f"⚙️ **حالت Hybrid:** {hybrid_settings.get('mode', 'advanced')}\n\n"
114
+ f"📈 **تنظیمات فعلی:**\n"
115
+ f"• ردیابی کاربران: {'✅ فعال' if hybrid_settings.get('enable_user_tracking', True) else '❌ غیرفعال'}\n"
116
+ f"• حداکثر کاربران دیگر: {hybrid_settings.get('max_other_users', 5)}\n"
117
+ f"• وزن تاریخچه شخصی: {hybrid_settings.get('personal_context_weight', 1.0)}\n"
118
+ f"• وزن تاریخچه گروه: {hybrid_settings.get('group_context_weight', 0.8)}\n"
119
+ f"• ارجاع به کاربران دیگر: {'✅ فعال' if hybrid_settings.get('enable_cross_user_references', True) else '❌ غیرفعال'}\n"
120
+ f"• حداکثر توکن ترکیبی: {hybrid_settings.get('max_combined_tokens', 30000)}\n\n"
121
+ )
122
+
123
+ # آمار کاربران در گروه‌های Hybrid
124
+ groups = data_manager.DATA['groups']
125
+ hybrid_groups = []
126
+
127
+ for chat_id_str, group_info in groups.items():
128
+ chat_id = int(chat_id_str)
129
+ recent_users = group_info.get('recent_users', [])
130
+ if recent_users:
131
+ hybrid_groups.append({
132
+ 'chat_id': chat_id,
133
+ 'title': group_info.get('title', 'بدون عنوان'),
134
+ 'user_count': len(set(recent_users)),
135
+ 'recent_users': recent_users[:5]
136
+ })
137
+
138
+ if hybrid_groups:
139
+ status_text += f"👥 **گروه‌های فعال در Hybrid:**\n"
140
+ for group in hybrid_groups[:5]: # فقط 5 گروه اول
141
+ status_text += f"• {group['title']}: {group['user_count']} کاربر فعال\n"
142
+
143
+ await update.message.reply_text(status_text, parse_mode='Markdown')
144
+
145
+
146
+
147
+ @admin_only
148
+ async def admin_view_hybrid_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
149
+ """مشاهده context Hybrid یک کاربر در گروه"""
150
+ if len(context.args) < 2:
151
+ await update.message.reply_text(
152
+ "⚠️ فرمت صحیح: `/view_hybrid_context [آیدی کاربر] [آیدی گروه]`\n"
153
+ "مثال: `/view_hybrid_context 123456789 -1001234567890`"
154
+ )
155
+ return
156
+
157
+ try:
158
+ user_id = int(context.args[0])
159
+ chat_id = int(context.args[1])
160
+ except ValueError:
161
+ await update.message.reply_text("⚠️ آیدی‌ها باید عددی باشند.")
162
+ return
163
+
164
+ # بررسی وجود کاربر و گروه
165
+ user_info = data_manager.DATA['users'].get(str(user_id))
166
+ group_info = data_manager.DATA['groups'].get(str(chat_id))
167
+
168
+ if not user_info:
169
+ await update.message.reply_text(f"⚠️ کاربر با آیدی {user_id} وجود ندارد.")
170
+ return
171
+
172
+ if not group_info:
173
+ await update.message.reply_text(f"⚠️ گروه با آیدی {chat_id} وجود ندارد.")
174
+ return
175
+
176
+ # دریافت context ترکیبی
177
+ hybrid_context = data_manager.get_advanced_hybrid_context_for_api(user_id, chat_id)
178
+
179
+ if not hybrid_context:
180
+ await update.message.reply_text("⚠️ context ترکیبی برای این کاربر و گروه وجود ندارد.")
181
+ return
182
+
183
+ # ایجاد گزارش
184
+ report = f"📊 **گزارش Hybrid برای کاربر {user_id} در گروه {chat_id}**\n\n"
185
+ report += f"👤 **کاربر:** {user_info.get('first_name', 'نامشخص')}\n"
186
+ report += f"👥 **گروه:** {group_info.get('title', 'بدون عنوان')}\n"
187
+ report += f"📝 **تعداد پیام‌ها در context:** {len(hybrid_context)}\n\n"
188
+
189
+ # محاسبه توکن‌ها
190
+ total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in hybrid_context)
191
+ report += f"🔢 **کل توکن‌ها:** {total_tokens}\n\n"
192
+
193
+ # نمایش 10 پیام اول
194
+ report += "📋 **10 پیام اول در context:**\n"
195
+ for i, msg in enumerate(hybrid_context[:10], 1):
196
+ role_icon = "👤" if msg['role'] == 'user' else "🤖" if msg['role'] == 'assistant' else "⚙️"
197
+ content_preview = msg['content'][:80] + "..." if len(msg['content']) > 80 else msg['content']
198
+ report += f"{i}. {role_icon} **{msg['role']}**: {content_preview}\n"
199
+
200
+ if len(hybrid_context) > 10:
201
+ report += f"\n... و {len(hybrid_context) - 10} پیام دیگر"
202
+
203
+ await update.message.reply_text(report, parse_mode='Markdown')
204
+
205
+
206
+ # --- هندلرهای دستورات ادمین ---
207
+ @admin_only
208
+ async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
209
+ """نمایش تمام دستورات موجود ادمین."""
210
+ commands_text = (
211
+ "📋 **دستورات ادمین ربات:**\n\n"
212
+ "👑 `/add_admin_bot [آیدی]` - اضافه کردن ادمین جدید\n"
213
+ "👑 `/remove_admin_bot [آیدی]` - حذف ادمین\n"
214
+ "👑 `/list_admins` - نمایش لیست ادمین‌ها\n\n"
215
+ "🎯 **دستورات Hybrid پیشرفته:**\n"
216
+ "🔄 `/set_hybrid_mode [basic|advanced]` - تنظیم حالت Hybrid\n"
217
+ "📊 `/hybrid_status` - نمایش وضعیت Hybrid\n"
218
+ "👁️ `/view_hybrid_context [آیدی کاربر] [آیدی گروه]` - مشاهده context Hybrid\n\n"
219
+ "📊 `/stats` - نمایش آمار ربات\n"
220
+ "📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
221
+ "🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
222
+ "📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامه‌ریزی شده\n"
223
+ "📋 `/list_scheduled` - نمایش لیست ارسال‌های برنامه‌ریزی شده\n"
224
+ "🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامه‌ریزی شده\n"
225
+ "🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
226
+ "✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
227
+ "💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
228
+ "ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
229
+ "📝 `/logs` - نمایش آخرین لاگ‌ها\n"
230
+ "📂 `/logs_file` - دانلود فایل کامل لاگ‌ها\n"
231
+ "👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
232
+ "🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
233
+ "💾 `/backup` - ایجاد نسخه پشتیبان از داده‌ها\n"
234
+ "📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
235
+ "🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
236
+ "👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
237
+ "👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
238
+ "📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
239
+ "⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
240
+ "🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
241
+ "✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
242
+ "📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
243
+ "💻 `/system_info` - نمایش اطلاعات سیستم\n"
244
+ "🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
245
+ "🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
246
+ "📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
247
+ "📋 `/view_replies [user|group] [آیدی]` - مشاهده ریپلای‌ها\n"
248
+ "🔄 `/set_context_mode [separate|group_shared|hybrid]` - تغییر حالت context\n"
249
+ "📊 `/group_info [آیدی]` - نمایش اطلاعات گروه\n"
250
+ "🗑️ `/clear_group_context [آیدی]` - پاک کردن context گروه\n"
251
+ "💾 `/memory_status` - نمایش وضعیت حافظه\n"
252
+ "⚙️ `/set_global_system [متن]` - تنظیم system instruction سراسری\n"
253
+ "👥 `/set_group_system [آیدی گروه] [متن]` - تنظیم system instruction برای گروه\n"
254
+ "👤 `/set_user_system [آیدی کاربر] [متن]` - تنظیم system instruction برای کاربر\n"
255
+ "📋 `/list_system_instructions` - نمایش لیست system instruction‌ها\n"
256
+ "📋 `/commands` - نمایش این لیست دستورات"
257
+ )
258
+ await update.message.reply_text(commands_text, parse_mode='Markdown')
259
+
260
+ @admin_only
261
+ async def admin_add_admin_bot(update: Update, context: ContextTypes.DEFAULT_TYPE):
262
+ """اضافه کردن کاربر به لیست ادمین‌های ربات"""
263
+ if not context.args or not context.args[0].isdigit():
264
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/add_admin_bot 123456789`")
265
+ return
266
+
267
+ user_id_to_add = int(context.args[0])
268
+ current_user_id = update.effective_user.id
269
+
270
+ # بررسی اینکه کاربر فعلی ادمین ارشد است
271
+ if not is_super_admin(current_user_id):
272
+ await update.message.reply_text("⛔️ فقط ادمین‌های ارشد می‌توانند ادمین جدید اضافه کنند.")
273
+ return
274
+
275
+ # بررسی اینکه کاربر از قبل ادمین است
276
+ if is_admin(user_id_to_add):
277
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_add}` از قبل ادمین است.")
278
+ return
279
+
280
+ # افزودن کاربر به لیست ادمین‌های اضافه شده
281
+ if 'added_admins' not in data_manager.DATA:
282
+ data_manager.DATA['added_admins'] = []
283
+
284
+ if user_id_to_add not in data_manager.DATA['added_admins']:
285
+ data_manager.DATA['added_admins'].append(user_id_to_add)
286
+ data_manager.save_data()
287
+
288
+ # تلاش برای اطلاع دادن به کاربر جدید
289
+ try:
290
+ await context.bot.send_message(
291
+ chat_id=user_id_to_add,
292
+ text=f"🎉 شما توسط ادمین ربات به عنوان ادمین جدید ربات منصوب شدید!\n\n"
293
+ f"اکنون می‌توانید از دستورات مدیریتی ربات استفاده کنید.\n"
294
+ f"برای مشاهده دستورات از /help استفاده کنید."
295
+ )
296
+ except TelegramError as e:
297
+ logger.warning(f"Could not send admin notification to user {user_id_to_add}: {e}")
298
+
299
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_add}` با موفقیت به لیست ادمین‌های ربات اضافه شد.", parse_mode='Markdown')
300
+
301
+ # لاگ کردن عمل
302
+ admin_name = update.effective_user.first_name
303
+ logger.info(f"Super admin {admin_name} ({current_user_id}) added user {user_id_to_add} as admin.")
304
+ else:
305
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_add}` از قبل در لیست ادمین‌های اضافه شده است.")
306
+
307
+ @admin_only
308
+ async def admin_remove_admin_bot(update: Update, context: ContextTypes.DEFAULT_TYPE):
309
+ """حذف کاربر از لیست ادمین‌های ربات (فقط برای ادمین‌های ارشد)"""
310
+ if not context.args or not context.args[0].isdigit():
311
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/remove_admin_bot 123456789`")
312
+ return
313
+
314
+ user_id_to_remove = int(context.args[0])
315
+ current_user_id = update.effective_user.id
316
+
317
+ # بررسی اینکه کاربر فعلی ادمین ارشد است
318
+ if not is_super_admin(current_user_id):
319
+ await update.message.reply_text("⛔️ فقط ادمین‌های ارشد می‌توانند ادمین‌ها را حذف کنند.")
320
+ return
321
+
322
+ # بررسی اینکه کاربر در لیست ادمین‌های ارشد نیست
323
+ if is_super_admin(user_id_to_remove):
324
+ await update.message.reply_text("⛔️ نمی‌توان ادمین‌های ارشد را حذف کرد.")
325
+ return
326
+
327
+ # بررسی اینکه کاربر در لیست ادمین‌های اضافه شده است
328
+ if 'added_admins' not in data_manager.DATA or user_id_to_remove not in data_manager.DATA['added_admins']:
329
+ await update.message.reply_text(f"⚠️ کاربر `{user_id_to_remove}` در لیست ادمین‌های اضافه شده وجود ندارد.")
330
+ return
331
+
332
+ # حذف کاربر از لیست ادمین‌های اضافه شده
333
+ data_manager.DATA['added_admins'].remove(user_id_to_remove)
334
+ data_manager.save_data()
335
+
336
+ # اطلاع دادن به کاربر حذف شده
337
+ try:
338
+ await context.bot.send_message(
339
+ chat_id=user_id_to_remove,
340
+ text="⛔️ دسترسی ادمین شما از ربات برداشته شد.\n\n"
341
+ "شما دیگر نمی‌توانید از دستورات مدیریتی استفاده کنید."
342
+ )
343
+ except TelegramError as e:
344
+ logger.warning(f"Could not send removal notification to user {user_id_to_remove}: {e}")
345
+
346
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_remove}` از لیست ادمین‌های ربات حذف شد.", parse_mode='Markdown')
347
+
348
+ # لاگ کردن عمل
349
+ admin_name = update.effective_user.first_name
350
+ logger.info(f"Super admin {admin_name} ({current_user_id}) removed user {user_id_to_remove} from admin list.")
351
+
352
+ @admin_only
353
+ async def admin_list_admins(update: Update, context: ContextTypes.DEFAULT_TYPE):
354
+ """نمایش لیست ادمین‌های ربات"""
355
+ env_admins = ENV_ADMIN_IDS
356
+ added_admins = data_manager.DATA.get('added_admins', [])
357
+ all_admins = get_admin_ids()
358
+
359
+ # جمع‌آوری اطلاعات ادمین‌ها
360
+ admin_info = []
361
+
362
+ # ادمین‌های ارشد (از محیط)
363
+ for admin_id in env_admins:
364
+ admin_data = data_manager.DATA['users'].get(str(admin_id), {})
365
+ name = admin_data.get('first_name', 'نامشخص')
366
+ username = admin_data.get('username', 'نامشخص')
367
+ admin_info.append({
368
+ 'id': admin_id,
369
+ 'name': name,
370
+ 'username': username,
371
+ 'type': 'ارشد 🔥',
372
+ 'last_seen': admin_data.get('last_seen', 'نامشخص')
373
+ })
374
+
375
+ # ادمین‌های اضافه شده
376
+ for admin_id in added_admins:
377
+ admin_data = data_manager.DATA['users'].get(str(admin_id), {})
378
+ name = admin_data.get('first_name', 'نامشخص')
379
+ username = admin_data.get('username', 'نامشخص')
380
+ admin_info.append({
381
+ 'id': admin_id,
382
+ 'name': name,
383
+ 'username': username,
384
+ 'type': 'عادی 👤',
385
+ 'last_seen': admin_data.get('last_seen', 'نامشخص')
386
+ })
387
+
388
+ if not admin_info:
389
+ await update.message.reply_text("⚠️ لیست ادمین‌ها خالی است.")
390
+ return
391
+
392
+ # ایجاد متن خروجی
393
+ text = "👑 **لیست ادمین‌های ربات:**\n\n"
394
+
395
+ for i, admin in enumerate(admin_info, 1):
396
+ text += f"{i}. {admin['type']} `{admin['id']}` - {admin['name']} (@{admin['username']})\n"
397
+ text += f" ⏰ آخرین فعالیت: {admin['last_seen']}\n\n"
398
+
399
+ text += f"\n📊 **آمار:**\n"
400
+ text += f"• ادمین‌های ارشد: {len(env_admins)}\n"
401
+ text += f"• ادمین‌های عادی: {len(added_admins)}\n"
402
+ text += f"• کل ادمین‌ها: {len(all_admins)}"
403
+
404
+ await update.message.reply_text(text, parse_mode='Markdown')
405
+
406
+ @admin_only
407
+ async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
408
+ """آمار ربات را نمایش می‌دهد."""
409
+ total_users = len(data_manager.DATA['users'])
410
+ total_groups = len(data_manager.DATA['groups'])
411
+ total_messages = data_manager.DATA['stats']['total_messages']
412
+ banned_count = len(data_manager.DATA['banned_users'])
413
+
414
+ # تعداد ادمین‌ها
415
+ env_admins = ENV_ADMIN_IDS
416
+ added_admins = data_manager.DATA.get('added_admins', [])
417
+ total_admins = len(env_admins) + len(added_admins)
418
+
419
+ now = datetime.now()
420
+ active_24h = sum(1 for user in data_manager.DATA['users'].values()
421
+ if 'last_seen' in user and
422
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
423
+
424
+ active_7d = sum(1 for user in data_manager.DATA['users'].values()
425
+ if 'last_seen' in user and
426
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
427
+
428
+ active_users = sorted(
429
+ data_manager.DATA['users'].items(),
430
+ key=lambda item: item[1].get('last_seen', ''),
431
+ reverse=True
432
+ )[:5]
433
+
434
+ active_users_text = "\n".join(
435
+ [f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
436
+ for user_id, info in active_users]
437
+ )
438
+
439
+ # اطلاعات context
440
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values()
441
+ if user.get('context') and len(user['context']) > 0)
442
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
443
+
444
+ # اطلاعات ریپلای‌ها
445
+ total_replies = 0
446
+ for user in data_manager.DATA['users'].values():
447
+ if 'context' in user:
448
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
449
+
450
+ # آمار گروه‌ها
451
+ groups_with_context = sum(1 for group in data_manager.DATA['groups'].values()
452
+ if group.get('context') and len(group['context']) > 0)
453
+
454
+ # آمار system instructions
455
+ system_stats = data_manager.DATA['system_instructions']
456
+ group_system_count = len(system_stats.get('groups', {}))
457
+ user_system_count = len(system_stats.get('users', {}))
458
+
459
+ text = (
460
+ f"📊 **آمار ربات**\n\n"
461
+ f"👥 **تعداد کل کاربران:** `{total_users}`\n"
462
+ f"👥 **تعداد کل گروه‌ها:** `{total_groups}`\n"
463
+ f"📝 **تعداد کل پیام‌ها:** `{total_messages}`\n"
464
+ f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
465
+ f"👑 **تعداد ادمین‌ها:** `{total_admins}`\n"
466
+ f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
467
+ f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
468
+ f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
469
+ f"💬 **گروه‌های با context فعال:** `{groups_with_context}`\n"
470
+ f"📝 **کل پیام‌های context:** `{total_context_messages}`\n"
471
+ f"📎 **کل ریپلای‌های ثبت شده:** `{total_replies}`\n"
472
+ f"🔄 **حالت context فعلی:** `{data_manager.get_context_mode()}`\n"
473
+ f"⚙️ **System Instructions گروه‌ها:** `{group_system_count}`\n"
474
+ f"⚙️ **System Instructions کاربران:** `{user_system_count}`\n\n"
475
+ f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
476
+ )
477
+ await update.message.reply_text(text, parse_mode='Markdown')
478
+
479
+ @admin_only
480
+ async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
481
+ """یک پیام را به تمام کاربران ارسال می‌کند."""
482
+ if not context.args:
483
+ await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
484
+ return
485
+
486
+ message_text = " ".join(context.args)
487
+ user_ids = list(data_manager.DATA['users'].keys())
488
+ total_sent = 0
489
+ total_failed = 0
490
+
491
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
492
+
493
+ for user_id_str in user_ids:
494
+ try:
495
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
496
+ total_sent += 1
497
+ await asyncio.sleep(0.05)
498
+ except TelegramError as e:
499
+ logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
500
+ total_failed += 1
501
+
502
+ result_text = (
503
+ f"✅ **ارسال همگانی تمام شد**\n\n"
504
+ f"✅ موفق: `{total_sent}`\n"
505
+ f"❌ ناموفق: `{total_failed}`"
506
+ )
507
+ await update.message.reply_text(result_text, parse_mode='Markdown')
508
+
509
+ @admin_only
510
+ async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
511
+ """ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
512
+ if len(context.args) < 3:
513
+ await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
514
+ "معیارهای موجود: `active_days`, `message_count`, `banned`")
515
+ return
516
+
517
+ criteria = context.args[0].lower()
518
+ value = context.args[1]
519
+ message_text = " ".join(context.args[2:])
520
+
521
+ target_users = []
522
+
523
+ if criteria == "active_days":
524
+ try:
525
+ days = int(value)
526
+ target_users = data_manager.get_active_users(days)
527
+ except ValueError:
528
+ await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
529
+ return
530
+
531
+ elif criteria == "message_count":
532
+ try:
533
+ min_count = int(value)
534
+ target_users = data_manager.get_users_by_message_count(min_count)
535
+ except ValueError:
536
+ await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
537
+ return
538
+
539
+ elif criteria == "banned":
540
+ if value.lower() == "true":
541
+ target_users = list(data_manager.DATA['banned_users'])
542
+ elif value.lower() == "false":
543
+ for user_id in data_manager.DATA['users']:
544
+ if int(user_id) not in data_manager.DATA['banned_users']:
545
+ target_users.append(int(user_id))
546
+ else:
547
+ await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
548
+ return
549
+
550
+ else:
551
+ await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
552
+ return
553
+
554
+ if not target_users:
555
+ await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
556
+ return
557
+
558
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
559
+
560
+ total_sent, total_failed = 0, 0
561
+ for user_id in target_users:
562
+ try:
563
+ await context.bot.send_message(chat_id=user_id, text=message_text)
564
+ total_sent += 1
565
+ await asyncio.sleep(0.05)
566
+ except TelegramError as e:
567
+ logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
568
+ total_failed += 1
569
+
570
+ result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
571
+ await update.message.reply_text(result_text, parse_mode='Markdown')
572
+
573
+ @admin_only
574
+ async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
575
+ """تنظیم ارسال برنامه‌ریزی شده پیام به همه کاربران."""
576
+ if len(context.args) < 3:
577
+ await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
578
+ return
579
+
580
+ try:
581
+ date_str, time_str = context.args[0], context.args[1]
582
+ message_text = " ".join(context.args[2:])
583
+
584
+ scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
585
+
586
+ if scheduled_time <= datetime.now():
587
+ await update.message.reply_text("⚠️ زمان برنامه‌ریزی شده باید در آینده باشد.")
588
+ return
589
+
590
+ data_manager.DATA['scheduled_broadcasts'].append({
591
+ 'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
592
+ 'message': message_text,
593
+ 'status': 'pending'
594
+ })
595
+ data_manager.save_data()
596
+
597
+ await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامه‌ریزی شد.")
598
+
599
+ except ValueError:
600
+ await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
601
+
602
+ @admin_only
603
+ async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
604
+ """نمایش لیست ارسال‌های برنامه‌ریزی شده."""
605
+ if not data_manager.DATA['scheduled_broadcasts']:
606
+ await update.message.reply_text("هیچ ارسال برنامه‌ریزی شده‌ای وجود ندارد.")
607
+ return
608
+
609
+ broadcasts_text = "📅 **لیست ارسال‌های برنامه‌ریزی شده:**\n\n"
610
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
611
+ status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
612
+ broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
613
+
614
+ await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
615
+
616
+ @admin_only
617
+ async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
618
+ """حذف یک ارسال برنامه‌ریزی شده."""
619
+ if not context.args or not context.args[0].isdigit():
620
+ await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامه‌ریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
621
+ return
622
+
623
+ index = int(context.args[0]) - 1
624
+
625
+ if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
626
+ await update.message.reply_text("⚠️ شماره ارسال برنامه‌ریزی شده نامعتبر است.")
627
+ return
628
+
629
+ removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
630
+ data_manager.save_data()
631
+
632
+ await update.message.reply_text(f"✅ ارسال برنامه‌ریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
633
+
634
+ @admin_only
635
+ async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
636
+ """یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع می‌دهد."""
637
+ if not context.args or not context.args[0].isdigit():
638
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
639
+ return
640
+
641
+ user_id_to_ban = int(context.args[0])
642
+
643
+ if is_admin(user_id_to_ban):
644
+ await update.message.reply_text("🛡️ شما نمی‌توانید یک ادمین را مسدود کنید!")
645
+ return
646
+
647
+ if data_manager.is_user_banned(user_id_to_ban):
648
+ await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
649
+ return
650
+
651
+ data_manager.ban_user(user_id_to_ban)
652
+
653
+ # ارسال پیام به کاربر مسدود شده
654
+ try:
655
+ await context.bot.send_message(
656
+ chat_id=user_id_to_ban,
657
+ text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمی‌توانید از خدمات ربات استفاده کنید."
658
+ )
659
+ except TelegramError as e:
660
+ logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
661
+
662
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
663
+
664
+ @admin_only
665
+ async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
666
+ """مسدودیت یک کاربر را برمی‌دارد و به او اطلاع می‌دهد."""
667
+ if not context.args or not context.args[0].isdigit():
668
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
669
+ return
670
+
671
+ user_id_to_unban = int(context.args[0])
672
+
673
+ if not data_manager.is_user_banned(user_id_to_unban):
674
+ await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شده‌ها وجود ندارد.")
675
+ return
676
+
677
+ data_manager.unban_user(user_id_to_unban)
678
+
679
+ # ارسال پیام به کاربر برای رفع مسدودیت
680
+ try:
681
+ await context.bot.send_message(
682
+ chat_id=user_id_to_unban,
683
+ text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. می‌توانید دوباره از ربات استفاده کنید."
684
+ )
685
+ except TelegramError as e:
686
+ logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
687
+
688
+ await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
689
+
690
+ @admin_only
691
+ async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
692
+ """ارسال پیام مستقیم به یک کاربر خاص."""
693
+ if len(context.args) < 2:
694
+ await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
695
+ return
696
+
697
+ user_id_str = context.args[0]
698
+ if not user_id_str.isdigit():
699
+ await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
700
+ return
701
+
702
+ message_text = " ".join(context.args[1:])
703
+ user_id = int(user_id_str)
704
+
705
+ try:
706
+ await context.bot.send_message(chat_id=user_id, text=message_text)
707
+ await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
708
+ except TelegramError as e:
709
+ await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
710
+
711
+ @admin_only
712
+ async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
713
+ """اطلاعات یک کاربر خاص را نمایش می‌دهد."""
714
+ if not context.args or not context.args[0].isdigit():
715
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
716
+ return
717
+
718
+ user_id = int(context.args[0])
719
+ user_info = data_manager.DATA['users'].get(str(user_id))
720
+
721
+ if not user_info:
722
+ await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
723
+ return
724
+
725
+ is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
726
+ is_admin_user = "بله 🔥" if is_super_admin(user_id) else "بله 👤" if is_admin(user_id) else "خیر"
727
+
728
+ if 'first_seen' in user_info and 'last_seen' in user_info:
729
+ try:
730
+ first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
731
+ last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
732
+ days_active = max(1, (last_date - first_date).days)
733
+ avg_messages = user_info.get('message_count', 0) / days_active
734
+ except:
735
+ avg_messages = user_info.get('message_count', 0)
736
+ else:
737
+ avg_messages = user_info.get('message_count', 0)
738
+
739
+ # اطلاعات context
740
+ context_messages = len(user_info.get('context', []))
741
+ context_tokens = data_manager.get_context_token_count(user_id)
742
+
743
+ # اطلاعات ریپلای‌ها
744
+ reply_count = 0
745
+ if 'context' in user_info:
746
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
747
+
748
+ # اطلاعات system instruction
749
+ system_info = data_manager.get_system_instruction_info(user_id=user_id)
750
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'user' else "❌"
751
+ system_type = system_info['type']
752
+
753
+ text = (
754
+ f"ℹ️ **اطلاعات کاربر**\n\n"
755
+ f"🆔 **آیدی:** `{user_id}`\n"
756
+ f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
757
+ f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
758
+ f"👑 **ادمین:** {is_admin_user}\n"
759
+ f"📊 **تعداد پیام‌ها:** `{user_info.get('message_count', 0)}`\n"
760
+ f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
761
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
762
+ f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
763
+ f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
764
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
765
+ f"🔢 **توکن‌های context:** `{context_tokens}`\n"
766
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
767
+ f"🚫 **وضعیت مسدودیت:** {is_banned}"
768
+ )
769
+ await update.message.reply_text(text, parse_mode='Markdown')
770
+
771
+ @admin_only
772
+ async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
773
+ """آخرین خطوط لاگ ربات را ارسال می‌کند."""
774
+ try:
775
+ with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
776
+ lines = f.readlines()
777
+ last_lines = lines[-30:]
778
+ log_text = "".join(last_lines)
779
+ if not log_text:
780
+ await update.message.reply_text("فایل لاگ خالی است.")
781
+ return
782
+
783
+ if len(log_text) > 4096:
784
+ for i in range(0, len(log_text), 4096):
785
+ await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
786
+ else:
787
+ await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
788
+
789
+ except FileNotFoundError:
790
+ await update.message.reply_text("فایل لاگ یافت نشد.")
791
+ except Exception as e:
792
+ await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
793
+
794
+ @admin_only
795
+ async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
796
+ """فایل کامل لاگ ربات را ارسال می‌کند."""
797
+ try:
798
+ await update.message.reply_document(
799
+ document=open(data_manager.LOG_FILE, 'rb'),
800
+ caption="📂 فایل کامل لاگ‌های ربات"
801
+ )
802
+ except FileNotFoundError:
803
+ await update.message.reply_text("فایل لاگ یافت نشد.")
804
+ except Exception as e:
805
+ await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
806
+
807
+ @admin_only
808
+ async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
809
+ """نمایش لیست کامل کاربران با صفحه‌بندی."""
810
+ users = data_manager.DATA['users']
811
+
812
+ page = 1
813
+ if context.args and context.args[0].isdigit():
814
+ page = int(context.args[0])
815
+ if page < 1: page = 1
816
+
817
+ users_per_page = 20
818
+ total_users = len(users)
819
+ total_pages = (total_users + users_per_page - 1) // users_per_page
820
+
821
+ if page > total_pages: page = total_pages
822
+
823
+ start_idx = (page - 1) * users_per_page
824
+ end_idx = min(start_idx + users_per_page, total_users)
825
+
826
+ sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
827
+
828
+ users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
829
+
830
+ for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
831
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
832
+
833
+ # بررسی ادمین بودن
834
+ is_admin_user = ""
835
+ if is_super_admin(int(user_id)):
836
+ is_admin_user = "🔥"
837
+ elif is_admin(int(user_id)):
838
+ is_admin_user = "👑"
839
+
840
+ username = user_info.get('username', 'N/A')
841
+ first_name = user_info.get('first_name', 'N/A')
842
+ last_seen = user_info.get('last_seen', 'N/A')
843
+ message_count = user_info.get('message_count', 0)
844
+ context_count = len(user_info.get('context', []))
845
+
846
+ # تعداد ریپلای‌ها
847
+ reply_count = 0
848
+ if 'context' in user_info:
849
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
850
+
851
+ # system instruction
852
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
853
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
854
+
855
+ users_text += f"{i}. {is_banned} {is_admin_user} {has_system} `{user_id}` - {first_name} (@{username})\n"
856
+ users_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
857
+ users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
858
+
859
+ keyboard = []
860
+ if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
861
+ if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
862
+
863
+ reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
864
+ await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
865
+
866
+ @admin_only
867
+ async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
868
+ """جستجوی کاربر بر اساس نام یا نام کاربری."""
869
+ if not context.args:
870
+ await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
871
+ return
872
+
873
+ search_term = " ".join(context.args).lower()
874
+ users = data_manager.DATA['users']
875
+
876
+ matching_users = []
877
+ for user_id, user_info in users.items():
878
+ first_name = (user_info.get('first_name') or '').lower()
879
+ username = (user_info.get('username') or '').lower()
880
+
881
+ if search_term in first_name or search_term in username:
882
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
883
+
884
+ # بررسی ادمین بودن
885
+ is_admin_user = ""
886
+ if is_super_admin(int(user_id)):
887
+ is_admin_user = "🔥"
888
+ elif is_admin(int(user_id)):
889
+ is_admin_user = "👑"
890
+
891
+ matching_users.append((user_id, user_info, is_banned, is_admin_user))
892
+
893
+ if not matching_users:
894
+ await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
895
+ return
896
+
897
+ results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
898
+
899
+ for user_id, user_info, is_banned, is_admin_user in matching_users:
900
+ username_display = user_info.get('username', 'N/A')
901
+ first_name_display = user_info.get('first_name', 'N/A')
902
+ last_seen = user_info.get('last_seen', 'N/A')
903
+ message_count = user_info.get('message_count', 0)
904
+ context_count = len(user_info.get('context', []))
905
+
906
+ # تعداد ریپلای‌ها
907
+ reply_count = 0
908
+ if 'context' in user_info:
909
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
910
+
911
+ # system instruction
912
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
913
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
914
+
915
+ results_text += f"{is_banned} {is_admin_user} {has_system} `{user_id}` - {first_name_display} (@{username_display})\n"
916
+ results_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
917
+ results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
918
+
919
+ await update.message.reply_text(results_text, parse_mode='Markdown')
920
+
921
+ @admin_only
922
+ async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
923
+ """ایجاد نسخه پشتیبان از داده‌های ربات."""
924
+ try:
925
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
926
+ backup_file = f"bot_backup_{timestamp}.json"
927
+
928
+ data_to_backup = data_manager.DATA.copy()
929
+ data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
930
+
931
+ with open(backup_file, 'w', encoding='utf-8') as f:
932
+ json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
933
+
934
+ await update.message.reply_document(
935
+ document=open(backup_file, 'rb'),
936
+ caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
937
+ )
938
+
939
+ logger.info(f"Backup created: {backup_file}")
940
+ os.remove(backup_file)
941
+ except Exception as e:
942
+ await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
943
+ logger.error(f"Error creating backup: {e}")
944
+
945
+ @admin_only
946
+ async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
947
+ """ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
948
+ users = data_manager.DATA['users']
949
+
950
+ df_data = []
951
+ for user_id, user_info in users.items():
952
+ user_id_int = int(user_id)
953
+ is_banned = "بله" if user_id_int in data_manager.DATA['banned_users'] else "خیر"
954
+
955
+ # وضعیت ادمین
956
+ admin_status = ""
957
+ if is_super_admin(user_id_int):
958
+ admin_status = "ارشد"
959
+ elif is_admin(user_id_int):
960
+ admin_status = "عادی"
961
+ else:
962
+ admin_status = "کاربر"
963
+
964
+ context_count = len(user_info.get('context', []))
965
+ context_tokens = data_manager.get_context_token_count(user_id_int)
966
+
967
+ # تعداد ریپلای‌ها
968
+ reply_count = 0
969
+ if 'context' in user_info:
970
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
971
+
972
+ # system instruction
973
+ system_info = data_manager.get_system_instruction_info(user_id=user_id_int)
974
+ has_system = "بله" if system_info['has_instruction'] and system_info['type'] == 'user' else "خیر"
975
+ system_type = system_info['type']
976
+
977
+ df_data.append({
978
+ 'User ID': user_id,
979
+ 'First Name': user_info.get('first_name', 'N/A'),
980
+ 'Username': user_info.get('username', 'N/A'),
981
+ 'Admin Status': admin_status,
982
+ 'Message Count': user_info.get('message_count', 0),
983
+ 'Context Messages': context_count,
984
+ 'Context Tokens': context_tokens,
985
+ 'Reply Count': reply_count,
986
+ 'Has System Instruction': has_system,
987
+ 'System Type': system_type,
988
+ 'First Seen': user_info.get('first_seen', 'N/A'),
989
+ 'Last Seen': user_info.get('last_seen', 'N/A'),
990
+ 'Banned': is_banned
991
+ })
992
+
993
+ df = pd.DataFrame(df_data)
994
+
995
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
996
+ df.to_csv(f.name, index=False)
997
+ temp_file_path = f.name
998
+
999
+ await update.message.reply_document(
1000
+ document=open(temp_file_path, 'rb'),
1001
+ caption="📊 فایل CSV اطلاعات کاربران"
1002
+ )
1003
+
1004
+ os.unlink(temp_file_path)
1005
+
1006
+ @admin_only
1007
+ async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
1008
+ """حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع می‌دهد."""
1009
+ if not context.args or context.args[0].lower() not in ['on', 'off']:
1010
+ await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
1011
+ return
1012
+
1013
+ status = context.args[0].lower()
1014
+
1015
+ if status == 'on':
1016
+ if data_manager.DATA.get('maintenance_mode', False):
1017
+ await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
1018
+ return
1019
+
1020
+ data_manager.DATA['maintenance_mode'] = True
1021
+ data_manager.save_data()
1022
+
1023
+ await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاع‌رسانی به کاربران...")
1024
+
1025
+ user_ids = list(data_manager.DATA['users'].keys())
1026
+ for user_id_str in user_ids:
1027
+ try:
1028
+ if int(user_id_str) not in get_admin_ids():
1029
+ await context.bot.send_message(
1030
+ chat_id=int(user_id_str),
1031
+ text="🔧 ربات در حال حاضر در حالت به��روزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
1032
+ )
1033
+ await asyncio.sleep(0.05)
1034
+ except TelegramError:
1035
+ continue
1036
+
1037
+ elif status == 'off':
1038
+ if not data_manager.DATA.get('maintenance_mode', False):
1039
+ await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
1040
+ return
1041
+
1042
+ data_manager.DATA['maintenance_mode'] = False
1043
+ data_manager.save_data()
1044
+
1045
+ await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاع‌رسانی به کاربران...")
1046
+
1047
+ user_ids = list(data_manager.DATA['users'].keys())
1048
+ for user_id_str in user_ids:
1049
+ try:
1050
+ if int(user_id_str) not in get_admin_ids():
1051
+ await context.bot.send_message(
1052
+ chat_id=int(user_id_str),
1053
+ text="✅ به‌روزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! می‌توانید دوباره از ربات استفاده کنید."
1054
+ )
1055
+ await asyncio.sleep(0.05)
1056
+ except TelegramError:
1057
+ continue
1058
+
1059
+ @admin_only
1060
+ async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
1061
+ """تنظیم پیام خوشامدگویی جدید."""
1062
+ if not context.args:
1063
+ await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
1064
+ "مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
1065
+ return
1066
+
1067
+ new_message = " ".join(context.args)
1068
+ data_manager.DATA['welcome_message'] = new_message
1069
+ data_manager.save_data()
1070
+
1071
+ await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت به‌روزرسانی شد.")
1072
+
1073
+ @admin_only
1074
+ async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
1075
+ """تنظیم پیام خداحافظی جدید."""
1076
+ if not context.args:
1077
+ await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
1078
+ "مثال: `/set_goodbye {user_mention}، خداحافظ!`")
1079
+ return
1080
+
1081
+ new_message = " ".join(context.args)
1082
+ data_manager.DATA['goodbye_message'] = new_message
1083
+ data_manager.save_data()
1084
+
1085
+ await update.message.reply_text("✅ پیام خداحافظی با موفقیت به‌روزرسانی شد.")
1086
+
1087
+ @admin_only
1088
+ async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
1089
+ """ایجاد و ارسال نمودار فعالیت کاربران."""
1090
+ users = data_manager.DATA['users']
1091
+ activity_hours = [0] * 24
1092
+
1093
+ for user_info in users.values():
1094
+ if 'last_seen' in user_info:
1095
+ try:
1096
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
1097
+ activity_hours[last_seen.hour] += 1
1098
+ except ValueError:
1099
+ continue
1100
+
1101
+ plt.figure(figsize=(12, 6))
1102
+ plt.bar(range(24), activity_hours, color='skyblue')
1103
+ plt.title('نمودار فعالیت کاربران بر اساس ساعت')
1104
+ plt.xlabel('ساعت')
1105
+ plt.ylabel('تعداد کاربران فعال')
1106
+ plt.xticks(range(24))
1107
+ plt.grid(axis='y', alpha=0.3)
1108
+
1109
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
1110
+ plt.savefig(f.name, bbox_inches='tight')
1111
+ temp_file_path = f.name
1112
+
1113
+ plt.close()
1114
+
1115
+ await update.message.reply_photo(
1116
+ photo=open(temp_file_path, 'rb'),
1117
+ caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
1118
+ )
1119
+
1120
+ os.unlink(temp_file_path)
1121
+
1122
+ @admin_only
1123
+ async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
1124
+ """نمایش آمار زمان پاسخگویی ربات."""
1125
+ stats = data_manager.DATA['stats']
1126
+ await update.message.reply_text(
1127
+ "📈 **آمار زمان پاسخگویی ربات**\n\n"
1128
+ f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
1129
+ f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
1130
+ f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
1131
+ f"📊 کل پاسخ‌های ثبت شده: `{stats.get('total_responses', 0)}`"
1132
+ )
1133
+
1134
+ @admin_only
1135
+ async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
1136
+ """افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
1137
+ if not context.args:
1138
+ await update.message.reply_text("⚠️ لطفاً کلمه ��ا عبارت مورد نظر را وارد کنید.\n"
1139
+ "مثال: `/add_blocked_word کلمه_نامناسب`")
1140
+ return
1141
+
1142
+ word = " ".join(context.args).lower()
1143
+
1144
+ if word in data_manager.DATA['blocked_words']:
1145
+ await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
1146
+ return
1147
+
1148
+ data_manager.DATA['blocked_words'].append(word)
1149
+ data_manager.save_data()
1150
+
1151
+ await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
1152
+
1153
+ @admin_only
1154
+ async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
1155
+ """حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
1156
+ if not context.args:
1157
+ await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
1158
+ "مثال: `/remove_blocked_word کلمه_نامناسب`")
1159
+ return
1160
+
1161
+ word = " ".join(context.args).lower()
1162
+
1163
+ if word not in data_manager.DATA['blocked_words']:
1164
+ await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
1165
+ return
1166
+
1167
+ data_manager.DATA['blocked_words'].remove(word)
1168
+ data_manager.save_data()
1169
+
1170
+ await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
1171
+
1172
+ @admin_only
1173
+ async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
1174
+ """نمایش لیست کلمات مسدود شده."""
1175
+ if not data_manager.DATA['blocked_words']:
1176
+ await update.message.reply_text("هیچ کلمه مسدود شده‌ای در لیست وجود ندارد.")
1177
+ return
1178
+
1179
+ words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
1180
+ await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
1181
+
1182
+ @admin_only
1183
+ async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
1184
+ """نمایش اطلاعات سیستم و منابع."""
1185
+ bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
1186
+ try:
1187
+ bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
1188
+ uptime = datetime.now() - bot_start_time
1189
+ uptime_str = f"{uptime.days} روز, {uptime.seconds // 3600} ساعت, {(uptime.seconds % 3600) // 60} دقیقه"
1190
+ except:
1191
+ uptime_str = "نامشخص"
1192
+
1193
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
1194
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
1195
+
1196
+ # تعداد کل ریپلای‌ها
1197
+ total_replies = 0
1198
+ for user in data_manager.DATA['users'].values():
1199
+ if 'context' in user:
1200
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
1201
+
1202
+ # آمار system instructions
1203
+ system_stats = data_manager.DATA['system_instructions']
1204
+ group_system_count = len(system_stats.get('groups', {}))
1205
+ user_system_count = len(system_stats.get('users', {}))
1206
+
1207
+ # آمار ادمین‌ها
1208
+ env_admins = ENV_ADMIN_IDS
1209
+ added_admins = data_manager.DATA.get('added_admins', [])
1210
+ total_admins = len(env_admins) + len(added_admins)
1211
+
1212
+ system_info = (
1213
+ f"💻 **اطلاعات سیستم:**\n\n"
1214
+ f"🖥️ سیستم‌عامل: {platform.system()} {platform.release()}\n"
1215
+ f"🐍 نسخه پایتون: {platform.python_version()}\n"
1216
+ f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
1217
+ f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
1218
+ f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
1219
+ f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
1220
+ f"⏱️ زمان اجرای ربات: {uptime_str}\n"
1221
+ f"👑 تعداد ادمین‌ها: {total_admins}\n"
1222
+ f"💭 کاربران با context: {users_with_context}\n"
1223
+ f"💬 کل پیام‌های context: {total_context_messages}\n"
1224
+ f"📎 کل ریپلای‌های ثبت شده: {total_replies}\n"
1225
+ f"⚙️ System Instructions گروه‌ها: {group_system_count}\n"
1226
+ f"⚙️ System Instructions کاربران: {user_system_count}"
1227
+ )
1228
+
1229
+ await update.message.reply_text(system_info, parse_mode='Markdown')
1230
+
1231
+ @admin_only
1232
+ async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
1233
+ """ریست کردن آمار ربات."""
1234
+ if not context.args:
1235
+ await update.message.reply_text("⚠️ لطفاً نوع آماری که می‌خواهید ریست کنید را مشخص کنید.\n"
1236
+ "مثال: `/reset_stats messages` یا `/reset_stats all`")
1237
+ return
1238
+
1239
+ stat_type = context.args[0].lower()
1240
+
1241
+ if stat_type == "messages":
1242
+ data_manager.DATA['stats']['total_messages'] = 0
1243
+ for user_id in data_manager.DATA['users']:
1244
+ data_manager.DATA['users'][user_id]['message_count'] = 0
1245
+ await update.message.reply_text("✅ آمار پیام‌ها با موفقیت ریست شد.")
1246
+
1247
+ elif stat_type == "all":
1248
+ data_manager.DATA['stats'] = {
1249
+ 'total_messages': 0,
1250
+ 'total_users': len(data_manager.DATA['users']),
1251
+ 'total_groups': len(data_manager.DATA['groups']),
1252
+ 'avg_response_time': 0,
1253
+ 'max_response_time': 0,
1254
+ 'min_response_time': 0,
1255
+ 'total_responses': 0
1256
+ }
1257
+ for user_id in data_manager.DATA['users']:
1258
+ data_manager.DATA['users'][user_id]['message_count'] = 0
1259
+ await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
1260
+
1261
+ else:
1262
+ await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینه‌های موجود: messages, all")
1263
+ return
1264
+
1265
+ data_manager.save_data()
1266
+
1267
+ # --- دستورات مدیریت context ---
1268
+ @admin_only
1269
+ async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1270
+ """پاک کردن context یک کاربر"""
1271
+ if not context.args or not context.args[0].isdigit():
1272
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
1273
+ return
1274
+
1275
+ user_id = int(context.args[0])
1276
+ data_manager.clear_user_context(user_id)
1277
+
1278
+ await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
1279
+
1280
+ @admin_only
1281
+ async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1282
+ """مشاهده context یک کاربر"""
1283
+ if not context.args or not context.args[0].isdigit():
1284
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
1285
+ return
1286
+
1287
+ user_id = int(context.args[0])
1288
+ user_context = data_manager.get_user_context(user_id)
1289
+
1290
+ if not user_context:
1291
+ await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
1292
+ return
1293
+
1294
+ context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
1295
+ total_tokens = 0
1296
+ reply_count = 0
1297
+
1298
+ for i, msg in enumerate(user_context, 1):
1299
+ role_emoji = "👤" if msg['role'] == 'user' else "🤖"
1300
+ tokens = data_manager.count_tokens(msg['content'])
1301
+ total_tokens += tokens
1302
+
1303
+ # بررسی ریپلای
1304
+ has_reply = msg.get('has_reply', False)
1305
+ if has_reply:
1306
+ reply_count += 1
1307
+ reply_emoji = "📎"
1308
+ else:
1309
+ reply_emoji = ""
1310
+
1311
+ content_preview = msg['content']
1312
+ if len(content_preview) > 100:
1313
+ content_preview = content_preview[:500] + "..."
1314
+
1315
+ context_text += f"{i}. {role_emoji} {reply_emoji} **{msg['role']}** ({tokens} توکن)\n"
1316
+ context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
1317
+
1318
+ if has_reply:
1319
+ context_text += f" 📎 ریپلای به: {msg.get('reply_to_user_name', 'Unknown')}\n"
1320
+
1321
+ context_text += f" 📝 {content_preview}\n\n"
1322
+
1323
+ context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن، {reply_count} ریپلای"
1324
+
1325
+ await update.message.reply_text(context_text, parse_mode='Markdown')
1326
+
1327
+ @admin_only
1328
+ async def admin_view_replies(update: Update, context: ContextTypes.DEFAULT_TYPE):
1329
+ """مشاهده ریپلای‌های یک کاربر یا گروه"""
1330
+ if len(context.args) < 2:
1331
+ await update.message.reply_text(
1332
+ "⚠️ فرمت صحیح: `/view_replies [user|group] [آیدی]`\n"
1333
+ "مثال: `/view_replies user 123456789`\n"
1334
+ "مثال: `/view_replies group -1001234567890`"
1335
+ )
1336
+ return
1337
+
1338
+ entity_type = context.args[0].lower()
1339
+ entity_id = context.args[1]
1340
+
1341
+ if entity_type == 'user':
1342
+ try:
1343
+ user_id = int(entity_id)
1344
+ user_context = data_manager.get_user_context(user_id)
1345
+ if not user_context:
1346
+ await update.message.reply_text(f"کاربر `{entity_id}` context ندارد.")
1347
+ return
1348
+
1349
+ replies = [msg for msg in user_context if msg.get('has_reply', False)]
1350
+
1351
+ if not replies:
1352
+ await update.message.reply_text(f"کاربر `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
1353
+ return
1354
+
1355
+ text = f"📋 **ریپلای‌های کاربر `{entity_id}`**\n\n"
1356
+ for i, msg in enumerate(replies, 1):
1357
+ text += f"{i}. **زمان:** {msg.get('timestamp', 'N/A')}\n"
1358
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
1359
+ if msg.get('is_reply_to_bot', False):
1360
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
1361
+ else:
1362
+ text += f" **نوع:** ریپلای به کاربر\n"
1363
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1364
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1365
+
1366
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1367
+
1368
+ await update.message.reply_text(text, parse_mode='Markdown')
1369
+ except ValueError:
1370
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1371
+
1372
+ elif entity_type == 'group':
1373
+ try:
1374
+ chat_id = int(entity_id)
1375
+ group_context = data_manager.get_group_context(chat_id)
1376
+ if not group_context:
1377
+ await update.message.reply_text(f"گروه `{entity_id}` context ندارد.")
1378
+ return
1379
+
1380
+ replies = [msg for msg in group_context if msg.get('has_reply', False)]
1381
+
1382
+ if not replies:
1383
+ await update.message.reply_text(f"گروه `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
1384
+ return
1385
+
1386
+ text = f"📋 **ریپلای‌های گروه `{entity_id}`**\n\n"
1387
+ for i, msg in enumerate(replies, 1):
1388
+ user_name = msg.get('user_name', 'Unknown')
1389
+ text += f"{i}. **کاربر:** {user_name}\n"
1390
+ text += f" **زمان:** {msg.get('timestamp', 'N/A')}\n"
1391
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
1392
+ if msg.get('is_reply_to_bot', False):
1393
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
1394
+ else:
1395
+ text += f" **نوع:** ریپلای به کاربر\n"
1396
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1397
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1398
+
1399
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1400
+
1401
+ await update.message.reply_text(text, parse_mode='Markdown')
1402
+ except ValueError:
1403
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1404
+
1405
+ else:
1406
+ await update.message.reply_text("⚠️ نوع نامعتبر. فقط 'user' یا 'group' مجاز است.")
1407
+
1408
+ # --- دستورات جدید برای مدیریت گروه‌ها ---
1409
+ @admin_only
1410
+ async def admin_set_context_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
1411
+ """تنظیم حالت context ربات"""
1412
+ if not context.args or context.args[0].lower() not in ['separate', 'group_shared', 'hybrid']:
1413
+ await update.message.reply_text(
1414
+ "⚠️ فرمت صحیح: `/set_context_mode [separate|group_shared|hybrid]`\n\n"
1415
+ "• **separate**: هر کاربر context جداگانه دارد (16384 توکن)\n"
1416
+ "• **group_shared**: همه کاربران در یک گروه context مشترک دارند (32768 توکن)\n"
1417
+ "• **hybrid**: ترکیبی از context شخصی و گروهی - بهترین برای بحث‌های گروهی\n\n"
1418
+ "💡 **مزایای Hybrid:**\n"
1419
+ "✅ هر کاربر تاریخچه شخصی خود را دارد\n"
1420
+ "✅ ربات از مکالمات گروه نیز مطلع است\n"
1421
+ "✅ پاسخ‌های دقیق‌تر و شخصی‌سازی شده\n"
1422
+ "✅ برای کار تیمی و بحث‌های پیچیده ایده‌آل\n\n"
1423
+ "🎯 **پیشنهاد:**\n"
1424
+ "- گروه‌های کوچک: Separate\n"
1425
+ "- گروه‌های بحث و تبادل نظر: Hybrid\n"
1426
+ "- گروه‌های آموزشی: Group Shared"
1427
+ )
1428
+ return
1429
+
1430
+ mode = context.args[0].lower()
1431
+ if data_manager.set_context_mode(mode):
1432
+ description = {
1433
+ 'separate': 'هر کاربر تاریخچه جداگانه خود را دارد (16384 توکن). ایده‌آل برای گروه‌های کوچک.',
1434
+ 'group_shared': 'همه کاربران تاریخچه مشترک دارند (32768 توکن). برای بحث‌های گروهی ساده.',
1435
+ 'hybrid': 'ترکیب هوشمند تاریخچه شخصی و گروهی. بهترین انتخاب برای کار تیمی و بحث‌های پیچیده.'
1436
+ }
1437
+
1438
+ await update.message.reply_text(
1439
+ f"✅ حالت context به `{mode}` تغییر یافت.\n\n"
1440
+ f"📝 **توضیحات:**\n{description[mode]}\n\n"
1441
+ f"🔄 تغییرات از پیام بعدی کاربران اعمال خواهد شد."
1442
+ )
1443
+ else:
1444
+ await update.message.reply_text("❌ خطا در تغییر حالت context.")
1445
+
1446
+ @admin_only
1447
+ async def admin_group_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
1448
+ """نمایش اطلاعات یک گروه"""
1449
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1450
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی گروه را وارد کنید.\nمثال: `/group_info -1001234567890`")
1451
+ return
1452
+
1453
+ chat_id = int(context.args[0])
1454
+ group_info = data_manager.DATA['groups'].get(str(chat_id))
1455
+
1456
+ if not group_info:
1457
+ await update.message.reply_text(f"گروهی با آیدی `{chat_id}` در دیتابیس یافت نشد.")
1458
+ return
1459
+
1460
+ # تبدیل set اعضا به لیست برای نمایش
1461
+ members = list(group_info.get('members', set()))
1462
+ members_count = len(members)
1463
+
1464
+ # اطلاعات context گروه
1465
+ context_messages = len(group_info.get('context', []))
1466
+ total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info.get('context', []))
1467
+
1468
+ # تعداد ریپلای‌ها در گروه
1469
+ reply_count = 0
1470
+ if 'context' in group_info:
1471
+ reply_count = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1472
+
1473
+ # system instruction
1474
+ system_info = data_manager.get_system_instruction_info(chat_id=chat_id)
1475
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'group' else "❌"
1476
+ system_type = system_info['type']
1477
+
1478
+ text = (
1479
+ f"📊 **اطلاعات گروه**\n\n"
1480
+ f"🆔 **آیدی:** `{chat_id}`\n"
1481
+ f"🏷️ **عنوان:** {group_info.get('title', 'N/A')}\n"
1482
+ f"📝 **تعداد پیام‌ها:** `{group_info.get('message_count', 0)}`\n"
1483
+ f"👥 **تعداد اعضا:** `{members_count}`\n"
1484
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
1485
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
1486
+ f"🔢 **توکن‌های context:** `{total_tokens}`\n"
1487
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
1488
+ f"📅 **اولین فعالیت:** {group_info.get('first_seen', 'N/A')}\n"
1489
+ f"🕒 **آخرین فعالیت:** {group_info.get('last_seen', 'N/A')}"
1490
+ )
1491
+
1492
+ await update.message.reply_text(text, parse_mode='Markdown')
1493
+
1494
+ @admin_only
1495
+ async def admin_clear_group_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1496
+ """پاک کردن context یک گروه"""
1497
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1498
+ await update.message.reply_text("⚠️ لطفاً آیدی گروه را وارد کنید.\nمثال: `/clear_group_context -1001234567890`")
1499
+ return
1500
+
1501
+ chat_id = int(context.args[0])
1502
+ data_manager.clear_group_context(chat_id)
1503
+
1504
+ await update.message.reply_text(f"✅ context گروه `{chat_id}` با موفقیت پاک شد.")
1505
+
1506
+ @admin_only
1507
+ async def admin_memory_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
1508
+ """نمایش وضعیت حافظه و context گروه‌ها"""
1509
+ groups = data_manager.DATA['groups']
1510
+
1511
+ if not groups:
1512
+ await update.message.reply_text("هیچ گروهی در دیتابیس وجود ندارد.")
1513
+ return
1514
+
1515
+ # محاسبه آمار
1516
+ total_groups = len(groups)
1517
+ groups_with_context = sum(1 for g in groups.values() if g.get('context'))
1518
+ total_context_messages = sum(len(g.get('context', [])) for g in groups.values())
1519
+ total_context_tokens = 0
1520
+ total_replies = 0
1521
+ groups_with_system = 0
1522
+
1523
+ # آمار کاربران در حالت Hybrid
1524
+ users_in_hybrid = 0
1525
+ if data_manager.get_context_mode() == 'hybrid':
1526
+ users_in_hybrid = len(data_manager.DATA['users'])
1527
+
1528
+ for group_id, group_info in groups.items():
1529
+ if 'context' in group_info:
1530
+ total_context_tokens += sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1531
+ total_replies += sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1532
+
1533
+ # بررسی system instruction
1534
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1535
+ if system_info['has_instruction'] and system_info['type'] == 'group':
1536
+ groups_with_system += 1
1537
+
1538
+ # لیست گروه‌هایی که بیشترین استفاده از حافظه را دارند
1539
+ groups_by_tokens = []
1540
+ for group_id, group_info in groups.items():
1541
+ if 'context' in group_info:
1542
+ tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1543
+ messages = len(group_info['context'])
1544
+ replies = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1545
+
1546
+ # system instruction
1547
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1548
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'group' else ""
1549
+
1550
+ groups_by_tokens.append((group_id, tokens, messages, replies, has_system))
1551
+
1552
+ # مرتب‌سازی بر اساس تعداد توکن
1553
+ groups_by_tokens.sort(key=lambda x: x[1], reverse=True)
1554
+
1555
+ context_mode = data_manager.get_context_mode()
1556
+ mode_info = {
1557
+ 'separate': 'جداگانه (هر کاربر 16384 توکن)',
1558
+ 'group_shared': 'مشترک گروهی (32768 توکن)',
1559
+ 'hybrid': 'ترکیبی (شخصی + گروهی)'
1560
+ }
1561
+
1562
+ status_text = (
1563
+ f"💾 **وضعیت حافظه گروه‌ها**\n\n"
1564
+ f"🎯 **حالت فعلی:** {context_mode} - {mode_info[context_mode]}\n\n"
1565
+ f"📊 **آمار کلی:**\n"
1566
+ f"• تعداد کل گروه‌ها: `{total_groups}`\n"
1567
+ f"• گروه‌های دارای context: `{groups_with_context}`\n"
1568
+ f"• گروه‌های دارای system instruction: `{groups_with_system}`\n"
1569
+ )
1570
+
1571
+ if context_mode == 'hybrid':
1572
+ status_text += f"• کاربران فعال در حالت Hybrid: `{users_in_hybrid}`\n"
1573
+
1574
+ status_text += (
1575
+ f"• کل پیام‌های context: `{total_context_messages}`\n"
1576
+ f"• کل ریپلای‌ها: `{total_replies}`\n"
1577
+ f"• کل توکن‌های استفاده شده: `{total_context_tokens}`\n"
1578
+ f"• میانگین توکن per گروه: `{total_context_tokens/max(1, groups_with_context):.0f}`\n\n"
1579
+ )
1580
+
1581
+ if groups_by_tokens:
1582
+ status_text += f"🏆 **گروه‌های با بیشترین استفاده از حافظه:**\n"
1583
+
1584
+ for i, (group_id, tokens, messages, replies, has_system) in enumerate(groups_by_tokens[:10], 1):
1585
+ usage_percent = (tokens / 32768) * 100
1586
+ status_text += f"{i}. {has_system} گروه `{group_id}`: {messages} پیام، {replies} ریپلای، {tokens} توکن ({usage_percent:.1f}%)\n"
1587
+
1588
+ await update.message.reply_text(status_text, parse_mode='Markdown')
1589
+
1590
+ # --- دستورات مدیریت system instructions ---
1591
+ @admin_only
1592
+ async def admin_set_global_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1593
+ """تنظیم system instruction سراسری"""
1594
+ if not context.args:
1595
+ await update.message.reply_text(
1596
+ "⚠️ لطفاً system instruction سراسری را وارد کنید.\n\n"
1597
+ "مثال: `/set_global_system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n\n"
1598
+ "برای مشاهده وضعیت فعلی: `/system_status`"
1599
+ )
1600
+ return
1601
+
1602
+ instruction_text = " ".join(context.args)
1603
+
1604
+ if data_manager.set_global_system_instruction(instruction_text):
1605
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1606
+ await update.message.reply_text(
1607
+ f"✅ system instruction سراسری تنظیم شد:\n\n"
1608
+ f"{instruction_preview}\n\n"
1609
+ f"این دستور برای تمام کاربران و گروه‌هایی که دستور خاصی ندارند اعمال خواهد شد."
1610
+ )
1611
+ else:
1612
+ await update.message.reply_text("❌ خطا در تنظیم system instruction سراسری.")
1613
+
1614
+ @admin_only
1615
+ async def admin_set_group_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1616
+ """تنظیم system instruction برای گروه"""
1617
+ if len(context.args) < 2:
1618
+ await update.message.reply_text(
1619
+ "⚠️ فرمت صحیح: `/set_group_system [آیدی گروه] [متن]`\n\n"
1620
+ "مثال: `/set_group_system -1001234567890 تو در این گروه فقط باید به سوالات فنی پاسخ بدهی.`"
1621
+ )
1622
+ return
1623
+
1624
+ chat_id_str = context.args[0]
1625
+ if not chat_id_str.lstrip('-').isdigit():
1626
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1627
+ return
1628
+
1629
+ chat_id = int(chat_id_str)
1630
+ instruction_text = " ".join(context.args[1:])
1631
+ user_id = update.effective_user.id
1632
+
1633
+ if data_manager.set_group_system_instruction(chat_id, instruction_text, user_id):
1634
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1635
+ await update.message.reply_text(
1636
+ f"✅ system instruction برای گروه `{chat_id}` تنظیم شد:\n\n"
1637
+ f"{instruction_preview}"
1638
+ )
1639
+ else:
1640
+ await update.message.reply_text("❌ خطا در تنظیم system instruction گروه.")
1641
+
1642
+ @admin_only
1643
+ async def admin_set_user_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1644
+ """تنظیم system instruction برای کاربر"""
1645
+ if len(context.args) < 2:
1646
+ await update.message.reply_text(
1647
+ "⚠️ فرمت صحیح: `/set_user_system [آیدی کاربر] [متن]`\n\n"
1648
+ "مثال: `/set_user_system 123456789 تو برای این کاربر باید به زبان ساده و با مثال پاسخ بدهی.`"
1649
+ )
1650
+ return
1651
+
1652
+ user_id_str = context.args[0]
1653
+ if not user_id_str.isdigit():
1654
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1655
+ return
1656
+
1657
+ user_id = int(user_id_str)
1658
+ instruction_text = " ".join(context.args[1:])
1659
+ admin_id = update.effective_user.id
1660
+
1661
+ if data_manager.set_user_system_instruction(user_id, instruction_text, admin_id):
1662
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1663
+ await update.message.reply_text(
1664
+ f"✅ system instruction برای کاربر `{user_id}` تنظیم شد:\n\n"
1665
+ f"{instruction_preview}"
1666
+ )
1667
+ else:
1668
+ await update.message.reply_text("❌ خطا در تنظیم system instruction کاربر.")
1669
+
1670
+ @admin_only
1671
+ async def admin_list_system_instructions(update: Update, context: ContextTypes.DEFAULT_TYPE):
1672
+ """نمایش لیست system instruction‌ها - فقط برای ادمین‌های ربات"""
1673
+ system_data = data_manager.DATA['system_instructions']
1674
+
1675
+ # نمایش system instruction سراسری
1676
+ global_instruction = system_data.get('global', '')
1677
+ global_preview = global_instruction[:150] + "..." if len(global_instruction) > 150 else global_instruction
1678
+
1679
+ text = (
1680
+ f"🌐 **Global System Instruction:**\n{global_preview}\n\n"
1681
+ f"⚠️ **توجه:** این اطلاعات فقط برای ادمین‌های ربات نمایش داده می‌شود.\n"
1682
+ f"ادمین‌های گروه فقط می‌توانند system instruction گروه خودشان را مشاهده کنند.\n\n"
1683
+ )
1684
+
1685
+ # نمایش system instruction گروه‌ها
1686
+ groups = system_data.get('groups', {})
1687
+ if groups:
1688
+ text += f"👥 **System Instruction گروه‌ها ({len(groups)}):**\n"
1689
+
1690
+ for i, (chat_id, group_data) in enumerate(groups.items(), 1):
1691
+ instruction = group_data.get('instruction', '')
1692
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1693
+ set_by = group_data.get('set_by', 'نامشخص')
1694
+ enabled = "✅" if group_data.get('enabled', True) else "❌"
1695
+
1696
+ text += f"{i}. گروه `{chat_id}` {enabled}\n"
1697
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1698
+ text += f" 📝 {preview}\n\n"
1699
+
1700
+ # نمایش system instruction کاربران
1701
+ users = system_data.get('users', {})
1702
+ if users:
1703
+ text += f"👤 **System Instruction کاربران ({len(users)}):**\n"
1704
+
1705
+ for i, (user_id, user_data) in enumerate(users.items(), 1):
1706
+ instruction = user_data.get('instruction', '')
1707
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1708
+ set_by = user_data.get('set_by', 'نامشخص')
1709
+ enabled = "✅" if user_data.get('enabled', True) else "❌"
1710
+
1711
+ text += f"{i}. کاربر `{user_id}` {enabled}\n"
1712
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1713
+ text += f" 📝 {preview}\n\n"
1714
+
1715
+ if not groups and not users:
1716
+ text += "⚠️ هیچ system instruction خاصی (گروهی یا کاربری) تنظیم شده است."
1717
+
1718
+ await update.message.reply_text(text, parse_mode='Markdown')
1719
+
1720
+ # --- هندلر برای دکمه‌های صفحه‌بندی ---
1721
+ async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
1722
+ """پردازش دکمه‌های صفحه‌بندی لیست کاربران."""
1723
+ query = update.callback_query
1724
+ await query.answer()
1725
+
1726
+ if query.data.startswith("users_list:"):
1727
+ page = int(query.data.split(":")[1])
1728
+ context.args = [str(page)]
1729
+ await admin_users_list(update, context)
1730
+
1731
+ # --- تابع برای پردازش ارسال‌های برنامه‌ریزی شده ---
1732
+ async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
1733
+ """پردازش ارسال‌های برنامه‌ریزی شده و ارسال پیام‌ها در زمان مقرر."""
1734
+ now = datetime.now()
1735
+ broadcasts_to_send_indices = []
1736
+
1737
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
1738
+ if broadcast['status'] == 'pending':
1739
+ broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
1740
+ if broadcast_time <= now:
1741
+ broadcasts_to_send_indices.append(i)
1742
+
1743
+ if not broadcasts_to_send_indices:
1744
+ return
1745
+
1746
+ user_ids = list(data_manager.DATA['users'].keys())
1747
+
1748
+ for index in broadcasts_to_send_indices:
1749
+ broadcast = data_manager.DATA['scheduled_broadcasts'][index]
1750
+ message_text = broadcast['message']
1751
+ total_sent, total_failed = 0, 0
1752
+
1753
+ for user_id_str in user_ids:
1754
+ try:
1755
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
1756
+ total_sent += 1
1757
+ await asyncio.sleep(0.05)
1758
+ except TelegramError as e:
1759
+ logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
1760
+ total_failed += 1
1761
+
1762
+ # به‌روزرسانی وضعیت ارسال
1763
+ data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
1764
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
1765
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
1766
+ data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
1767
+
1768
+ logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
1769
+
1770
+ data_manager.save_data()
1771
+
1772
+ # --- تابع راه‌اندازی هندلرها ---
1773
+ def setup_admin_handlers(application):
1774
+ """هندلرهای پنل ادمین را به اپلیکیشن اضافه می‌کند."""
1775
+ # هندلرهای اصلی
1776
+ application.add_handler(CommandHandler("commands", admin_commands))
1777
+ application.add_handler(CommandHandler("stats", admin_stats))
1778
+ application.add_handler(CommandHandler("broadcast", admin_broadcast))
1779
+ application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
1780
+ application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
1781
+ application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
1782
+ application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
1783
+ application.add_handler(CommandHandler("ban", admin_ban))
1784
+ application.add_handler(CommandHandler("unban", admin_unban))
1785
+ application.add_handler(CommandHandler("direct_message", admin_direct_message))
1786
+ application.add_handler(CommandHandler("user_info", admin_userinfo))
1787
+ application.add_handler(CommandHandler("logs", admin_logs))
1788
+ application.add_handler(CommandHandler("logs_file", admin_logs_file))
1789
+ application.add_handler(CommandHandler("users_list", admin_users_list))
1790
+ application.add_handler(CommandHandler("user_search", admin_user_search))
1791
+ application.add_handler(CommandHandler("backup", admin_backup))
1792
+ application.add_handler(CommandHandler("export_csv", admin_export_csv))
1793
+ application.add_handler(CommandHandler("maintenance", admin_maintenance))
1794
+ application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
1795
+ application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
1796
+ application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
1797
+ application.add_handler(CommandHandler("response_stats", admin_response_stats))
1798
+ application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
1799
+ application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
1800
+ application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
1801
+ application.add_handler(CommandHandler("system_info", admin_system_info))
1802
+ application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
1803
+
1804
+ # هندلرهای مدیریت context
1805
+ application.add_handler(CommandHandler("clear_context", admin_clear_context))
1806
+ application.add_handler(CommandHandler("view_context", admin_view_context))
1807
+ application.add_handler(CommandHandler("view_replies", admin_view_replies))
1808
+
1809
+ # هندلرهای مدیریت گروه‌ها
1810
+ application.add_handler(CommandHandler("set_context_mode", admin_set_context_mode))
1811
+ application.add_handler(CommandHandler("group_info", admin_group_info))
1812
+ application.add_handler(CommandHandler("clear_group_context", admin_clear_group_context))
1813
+ application.add_handler(CommandHandler("memory_status", admin_memory_status))
1814
+
1815
+ # هندلرهای system instruction
1816
+ application.add_handler(CommandHandler("set_global_system", admin_set_global_system))
1817
+ application.add_handler(CommandHandler("set_group_system", admin_set_group_system))
1818
+ application.add_handler(CommandHandler("set_user_system", admin_set_user_system))
1819
+ application.add_handler(CommandHandler("list_system_instructions", admin_list_system_instructions))
1820
+
1821
+ # هندلرهای مدیریت ادمین‌ها
1822
+ application.add_handler(CommandHandler("add_admin_bot", admin_add_admin_bot))
1823
+ application.add_handler(CommandHandler("remove_admin_bot", admin_remove_admin_bot))
1824
+ application.add_handler(CommandHandler("list_admins", admin_list_admins))
1825
+
1826
+ # هندلرهای جدید Hybrid
1827
+ application.add_handler(CommandHandler("set_hybrid_mode", admin_set_hybrid_mode))
1828
+ application.add_handler(CommandHandler("hybrid_status", admin_hybrid_status))
1829
+ application.add_handler(CommandHandler("view_hybrid_context", admin_view_hybrid_context))
1830
+
1831
+ # هندلر برای دکمه‌های صفحه‌بندی
1832
+ application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
1833
+
1834
+ # شروع وظیفه دوره‌ای برای بررسی ارسال‌های برنامه‌ریزی شده
1835
+ application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
1836
+
1837
+ logger.info("Admin panel handlers have been set up with Hybrid support.")
BOT/render-main/FIXES/data_manager.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # data_manager.py - سیستم Hybrid پیشرفته کامل
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ from datetime import datetime, timedelta
7
+ import tiktoken
8
+ import threading
9
+ import time
10
+
11
+ # --- افزودن قفل برای ایمنی thread-safe ---
12
+ DATA_LOCK = threading.Lock()
13
+
14
+ # --- تنظیمات مسیر فایل‌ها ---
15
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
16
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
17
+ LOG_FILE = os.path.join(BASE_DIR, "bot.log")
18
+
19
+ # --- کش داده‌های گلوبال ---
20
+ DATA = {
21
+ "users": {},
22
+ "groups": {},
23
+ "banned_users": set(),
24
+ "stats": {
25
+ "total_messages": 0,
26
+ "total_users": 0,
27
+ "total_groups": 0,
28
+ "avg_response_time": 0.0,
29
+ "max_response_time": 0.0,
30
+ "min_response_time": float('inf'),
31
+ "total_responses": 0
32
+ },
33
+ "welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
34
+ "group_welcome_message": "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید",
35
+ "goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
36
+ "maintenance_mode": False,
37
+ "blocked_words": [],
38
+ "scheduled_broadcasts": [],
39
+ "bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
40
+ "context_mode": "hybrid", # تغییر پیش‌فرض به hybrid
41
+ "system_instructions": {
42
+ "global": "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد. از کلمات فارسی صحیح استفاده کنید و در صورت نیاز توضیحات کامل ارائه دهید.",
43
+ "groups": {},
44
+ "users": {}
45
+ },
46
+ "hybrid_settings": { # تنظیمات جدید برای Hybrid پیشرفته
47
+ "mode": "advanced", # basic یا advanced
48
+ "enable_user_tracking": True,
49
+ "max_other_users": 5,
50
+ "personal_context_weight": 1.0,
51
+ "group_context_weight": 0.8,
52
+ "other_users_weight": 0.6,
53
+ "max_combined_tokens": 30000,
54
+ "enable_cross_user_references": True
55
+ }
56
+ }
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ # --- توابع کمکی ---
61
+ def count_tokens(text: str) -> int:
62
+ """شمارش تعداد توکن‌های متن با استفاده از tokenizer"""
63
+ try:
64
+ encoding = tiktoken.get_encoding("cl100k_base")
65
+ return len(encoding.encode(text))
66
+ except Exception as e:
67
+ logger.warning(f"Error counting tokens: {e}, using fallback")
68
+ return max(1, len(text) // 4)
69
+
70
+ def load_data():
71
+ """داده‌ها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره می‌کند."""
72
+ global DATA
73
+ with DATA_LOCK:
74
+ try:
75
+ if not os.path.exists(DATA_FILE):
76
+ logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد می‌شود.")
77
+ save_data()
78
+ return
79
+
80
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
81
+ loaded_data = json.load(f)
82
+ loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
83
+
84
+ # اطمینان از وجود کلیدهای جدید
85
+ if 'groups' not in loaded_data: loaded_data['groups'] = {}
86
+ if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'hybrid'
87
+ if 'group_welcome_message' not in loaded_data:
88
+ loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..."
89
+ if 'total_groups' not in loaded_data.get('stats', {}):
90
+ if 'stats' not in loaded_data: loaded_data['stats'] = {}
91
+ loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {}))
92
+
93
+ # اطمینان از وجود hybrid_settings
94
+ if 'hybrid_settings' not in loaded_data:
95
+ loaded_data['hybrid_settings'] = DATA['hybrid_settings']
96
+
97
+ # تبدیل اعضای گروه از list به set
98
+ for group_id in loaded_data.get('groups', {}):
99
+ if 'members' in loaded_data['groups'][group_id]:
100
+ if isinstance(loaded_data['groups'][group_id]['members'], list):
101
+ loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members'])
102
+ elif not isinstance(loaded_data['groups'][group_id]['members'], set):
103
+ loaded_data['groups'][group_id]['members'] = set()
104
+ else:
105
+ loaded_data['groups'][group_id]['members'] = set()
106
+
107
+ # اطمینان از وجود context برای گروه‌های قدیمی
108
+ for group_id in loaded_data.get('groups', {}):
109
+ if 'context' not in loaded_data['groups'][group_id]:
110
+ loaded_data['groups'][group_id]['context'] = []
111
+
112
+ # اطمینان از وجود context برای کاربران قدیمی
113
+ for user_id in loaded_data.get('users', {}):
114
+ if 'context' not in loaded_data['users'][user_id]:
115
+ loaded_data['users'][user_id]['context'] = []
116
+
117
+ # اطمینان از وجود کلیدهای آمار پاسخگویی
118
+ if 'stats' in loaded_data:
119
+ stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses']
120
+ for key in stats_keys:
121
+ if key not in loaded_data['stats']:
122
+ if key == 'min_response_time':
123
+ loaded_data['stats'][key] = float('inf')
124
+ else:
125
+ loaded_data['stats'][key] = 0.0
126
+
127
+ # اطمینان از وجود system_instructions
128
+ if 'system_instructions' not in loaded_data:
129
+ loaded_data['system_instructions'] = DATA['system_instructions']
130
+
131
+ if 'added_admins' not in loaded_data:
132
+ loaded_data['added_admins'] = []
133
+
134
+ DATA.update(loaded_data)
135
+ logger.info(f"داده‌ها با موفقیت از {DATA_FILE} بارگذاری شدند.")
136
+
137
+ except json.JSONDecodeError as e:
138
+ logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
139
+ except Exception as e:
140
+ logger.error(f"خطای غیرمنتظره هنگام بارگذاری داده‌ها: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
141
+
142
+ def save_data():
143
+ """کش گلوبال داده‌ها را در فایل JSON ذخیره می‌کند."""
144
+ global DATA
145
+ with DATA_LOCK:
146
+ try:
147
+ data_to_save = DATA.copy()
148
+ data_to_save['banned_users'] = list(DATA['banned_users'])
149
+
150
+ # تبدیل set اعضای گروه به list برای ذخیره JSON
151
+ for group_id in data_to_save.get('groups', {}):
152
+ if 'members' in data_to_save['groups'][group_id]:
153
+ if isinstance(data_to_save['groups'][group_id]['members'], set):
154
+ data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members'])
155
+ elif not isinstance(data_to_save['groups'][group_id]['members'], list):
156
+ data_to_save['groups'][group_id]['members'] = []
157
+
158
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
159
+ json.dump(data_to_save, f, indent=4, ensure_ascii=False)
160
+ logger.debug(f"داده‌ها با موفقیت در {DATA_FILE} ذخیره شدند.")
161
+ except Exception as e:
162
+ logger.error(f"خطای مهلک: امکان ذخیره داده‌ها در {DATA_FILE} وجود ندارد. خطا: {e}")
163
+
164
+ # --- توابع مدیریت کاربران ---
165
+ def update_user_stats(user_id: int, user):
166
+ """آمار کاربر را پس از هر پیام به‌روز کرده و داده‌ها را ذخیره می‌کند."""
167
+ global DATA
168
+ with DATA_LOCK:
169
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
170
+ user_id_str = str(user_id)
171
+
172
+ if user_id_str not in DATA['users']:
173
+ DATA['users'][user_id_str] = {
174
+ 'first_name': user.first_name,
175
+ 'username': user.username,
176
+ 'first_seen': now_str,
177
+ 'message_count': 0,
178
+ 'context': [],
179
+ 'last_group_activity': {},
180
+ 'user_profile': {
181
+ 'language_preference': 'fa',
182
+ 'interaction_style': 'normal'
183
+ }
184
+ }
185
+ DATA['stats']['total_users'] += 1
186
+ logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
187
+
188
+ DATA['users'][user_id_str]['last_seen'] = now_str
189
+ DATA['users'][user_id_str]['message_count'] += 1
190
+ DATA['stats']['total_messages'] += 1
191
+
192
+ save_data()
193
+
194
+ def update_response_stats(response_time: float):
195
+ """آمار زمان پاسخگویی را به‌روز می‌کند."""
196
+ global DATA
197
+ with DATA_LOCK:
198
+ if DATA['stats']['total_responses'] == 0:
199
+ DATA['stats']['min_response_time'] = response_time
200
+
201
+ DATA['stats']['total_responses'] += 1
202
+
203
+ # محاسبه میانگین جدید
204
+ current_avg = DATA['stats']['avg_response_time']
205
+ total_responses = DATA['stats']['total_responses']
206
+ new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
207
+ DATA['stats']['avg_response_time'] = new_avg
208
+
209
+ # به‌روزرسانی حداکثر و حداقل زمان پاسخگویی
210
+ if response_time > DATA['stats']['max_response_time']:
211
+ DATA['stats']['max_response_time'] = response_time
212
+
213
+ if response_time < DATA['stats']['min_response_time']:
214
+ DATA['stats']['min_response_time'] = response_time
215
+
216
+ save_data()
217
+
218
+ # --- توابع مدیریت مسدودیت ---
219
+ def is_user_banned(user_id: int) -> bool:
220
+ """بررسی می‌کند آیا کاربر مسدود شده است یا خیر."""
221
+ return user_id in DATA['banned_users']
222
+
223
+ def ban_user(user_id: int):
224
+ """کاربر را مسدود کرده و ذخیره می‌کند."""
225
+ with DATA_LOCK:
226
+ DATA['banned_users'].add(user_id)
227
+ save_data()
228
+
229
+ def unban_user(user_id: int):
230
+ """مسدودیت کاربر را برداشته و ذخیره می‌کند."""
231
+ with DATA_LOCK:
232
+ DATA['banned_users'].discard(user_id)
233
+ save_data()
234
+
235
+ def contains_blocked_words(text: str) -> bool:
236
+ """بررسی می‌کند آیا متن حاوی کلمات مسدود شده است یا خیر."""
237
+ if not DATA['blocked_words']:
238
+ return False
239
+
240
+ text_lower = text.lower()
241
+ for word in DATA['blocked_words']:
242
+ if word in text_lower:
243
+ return True
244
+
245
+ return False
246
+
247
+ # --- توابع مدیریت کاربران و گروه‌ها ---
248
+ def get_active_users(days: int) -> list:
249
+ """لیست کاربران فعال در بازه زمانی مشخص را برمی‌گرداند."""
250
+ now = datetime.now()
251
+ cutoff_date = now - timedelta(days=days)
252
+
253
+ active_users = []
254
+ for user_id, user_info in DATA['users'].items():
255
+ if 'last_seen' in user_info:
256
+ try:
257
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
258
+ if last_seen >= cutoff_date:
259
+ active_users.append(int(user_id))
260
+ except ValueError:
261
+ continue
262
+
263
+ return active_users
264
+
265
+ def get_users_by_message_count(min_count: int) -> list:
266
+ """لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمی‌گرداند."""
267
+ users = []
268
+ for user_id, user_info in DATA['users'].items():
269
+ if user_info.get('message_count', 0) >= min_count:
270
+ users.append(int(user_id))
271
+
272
+ return users
273
+
274
+ # --- توابع مدیریت context کاربران ---
275
+ def add_to_user_context(user_id: int, role: str, content: str):
276
+ """اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن"""
277
+ add_to_user_context_with_reply(user_id, role, content, None)
278
+
279
+ def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None):
280
+ """اضافه کردن پیام به context کاربر با اطلاعات ریپلای"""
281
+ with DATA_LOCK:
282
+ user_id_str = str(user_id)
283
+
284
+ if user_id_str not in DATA['users']:
285
+ return
286
+
287
+ if 'context' not in DATA['users'][user_id_str]:
288
+ DATA['users'][user_id_str]['context'] = []
289
+
290
+ # اضافه کردن پیام جدید
291
+ message = {
292
+ 'role': role,
293
+ 'content': content,
294
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
295
+ 'has_reply': False
296
+ }
297
+
298
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
299
+ message['has_reply'] = True
300
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
301
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
302
+ message['reply_to_content'] = reply_info['replied_text']
303
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
304
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
305
+
306
+ DATA['users'][user_id_str]['context'].append(message)
307
+
308
+ # محدود کردن context به 16384 توکن
309
+ trim_user_context(user_id, max_tokens=16384)
310
+
311
+ save_data()
312
+
313
+ def trim_user_context(user_id: int, max_tokens: int = 16384):
314
+ """کوتاه کردن context کاربر به تعداد توکن مشخص"""
315
+ user_id_str = str(user_id)
316
+
317
+ if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
318
+ return
319
+
320
+ context = DATA['users'][user_id_str]['context']
321
+
322
+ if not context:
323
+ return
324
+
325
+ # محاسبه توکن‌های کل
326
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
327
+
328
+ # حذف قدیمی‌ترین پیام‌ها تا زمانی که توکن‌ها زیر حد مجاز باشد
329
+ while total_tokens > max_tokens and len(context) > 1:
330
+ removed_message = context.pop(0)
331
+ total_tokens -= count_tokens(removed_message['content'])
332
+
333
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
334
+ if total_tokens > max_tokens and context:
335
+ last_message = context[-1]
336
+ content = last_message['content']
337
+
338
+ tokens = count_tokens(content)
339
+ if tokens > max_tokens:
340
+ context.pop()
341
+ else:
342
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
343
+ words = content.split()
344
+ if len(words) > 1:
345
+ content = ' '.join(words[:-1])
346
+ else:
347
+ content = content[:-1] if len(content) > 1 else ''
348
+ tokens = count_tokens(content)
349
+
350
+ if content:
351
+ context[-1]['content'] = content
352
+ else:
353
+ context.pop()
354
+
355
+ save_data()
356
+
357
+ def get_user_context(user_id: int) -> list:
358
+ """دریافت context کاربر"""
359
+ user_id_str = str(user_id)
360
+
361
+ if user_id_str not in DATA['users']:
362
+ return []
363
+
364
+ return DATA['users'][user_id_str].get('context', []).copy()
365
+
366
+ def clear_user_context(user_id: int):
367
+ """پاک کردن context کاربر"""
368
+ with DATA_LOCK:
369
+ user_id_str = str(user_id)
370
+
371
+ if user_id_str in DATA['users']:
372
+ if 'context' in DATA['users'][user_id_str]:
373
+ DATA['users'][user_id_str]['context'] = []
374
+ save_data()
375
+ logger.info(f"Context cleared for user {user_id}")
376
+
377
+ def get_context_summary(user_id: int) -> str:
378
+ """خلاصه‌ای از context کاربر"""
379
+ context = get_user_context(user_id)
380
+ if not context:
381
+ return "بدون تاریخچه"
382
+
383
+ total_messages = len(context)
384
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
385
+
386
+ # تعداد ریپلای‌ها
387
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
388
+
389
+ # نمایش آخرین پیام
390
+ last_message = context[-1] if context else {}
391
+ last_content = last_message.get('content', '')[:50]
392
+ if len(last_message.get('content', '')) > 50:
393
+ last_content += "..."
394
+
395
+ return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}"
396
+
397
+ def get_context_for_api(user_id: int) -> list:
398
+ """فرمت context برای ارسال به API"""
399
+ context = get_user_context(user_id)
400
+
401
+ api_context = []
402
+ for msg in context:
403
+ api_context.append({
404
+ 'role': msg['role'],
405
+ 'content': msg['content']
406
+ })
407
+
408
+ return api_context
409
+
410
+ def get_context_token_count(user_id: int) -> int:
411
+ """تعداد کل توکن‌های context کاربر"""
412
+ context = get_user_context(user_id)
413
+ return sum(count_tokens(msg['content']) for msg in context)
414
+
415
+ # --- توابع مدیریت گروه‌ها ---
416
+ def update_group_stats(chat_id: int, chat, user_id: int = None):
417
+ """آمار گروه را به‌روز کرده و داده‌ها را ذخیره می‌کند."""
418
+ global DATA
419
+ with DATA_LOCK:
420
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
421
+ chat_id_str = str(chat_id)
422
+
423
+ if chat_id_str not in DATA['groups']:
424
+ DATA['groups'][chat_id_str] = {
425
+ 'title': chat.title if hasattr(chat, 'title') else 'Private Group',
426
+ 'type': chat.type,
427
+ 'first_seen': now_str,
428
+ 'message_count': 0,
429
+ 'members': set(),
430
+ 'context': [],
431
+ 'recent_users': [],
432
+ 'last_activity': now_str
433
+ }
434
+ DATA['stats']['total_groups'] += 1
435
+ logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})")
436
+
437
+ DATA['groups'][chat_id_str]['last_seen'] = now_str
438
+ DATA['groups'][chat_id_str]['last_activity'] = now_str
439
+ DATA['groups'][chat_id_str]['message_count'] += 1
440
+
441
+ # اضافه کردن کاربر به لیست اعضای گروه
442
+ if user_id is not None:
443
+ if 'members' not in DATA['groups'][chat_id_str]:
444
+ DATA['groups'][chat_id_str]['members'] = set()
445
+ elif isinstance(DATA['groups'][chat_id_str]['members'], list):
446
+ DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members'])
447
+
448
+ DATA['groups'][chat_id_str]['members'].add(user_id)
449
+
450
+ # به‌روزرسانی لیست کاربران اخیر
451
+ if 'recent_users' not in DATA['groups'][chat_id_str]:
452
+ DATA['groups'][chat_id_str]['recent_users'] = []
453
+
454
+ # حذف کاربر از لیست اگر وجود دارد
455
+ recent_users = DATA['groups'][chat_id_str]['recent_users']
456
+ recent_users = [uid for uid in recent_users if uid != user_id]
457
+
458
+ # اضافه کردن کاربر به ابتدای لیست
459
+ recent_users.insert(0, user_id)
460
+
461
+ # محدود کردن به 20 کاربر اخیر
462
+ if len(recent_users) > 20:
463
+ recent_users = recent_users[:20]
464
+
465
+ DATA['groups'][chat_id_str]['recent_users'] = recent_users
466
+
467
+ save_data()
468
+
469
+ def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None):
470
+ """اضافه کردن پیام به context گروه و محدود کردن به 16384 توکن"""
471
+ add_to_group_context_with_reply(chat_id, role, content, user_name, None, None)
472
+
473
+ def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None,
474
+ reply_info: dict = None, user_id: int = None):
475
+ """اضافه کردن پیام به context گروه با اطلاعات ریپلای"""
476
+ with DATA_LOCK:
477
+ chat_id_str = str(chat_id)
478
+
479
+ if chat_id_str not in DATA['groups']:
480
+ return
481
+
482
+ if 'context' not in DATA['groups'][chat_id_str]:
483
+ DATA['groups'][chat_id_str]['context'] = []
484
+
485
+ # اضافه کردن نام کاربر به محتوا اگر مشخص باشد
486
+ if user_name and role == 'user':
487
+ content_with_name = f"{user_name}: {content}"
488
+ else:
489
+ content_with_name = content
490
+
491
+ # اضافه کردن پیام جدید با اطلاعات کامل
492
+ message = {
493
+ 'role': role,
494
+ 'content': content_with_name if role == 'user' else content,
495
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
496
+ 'user_name': user_name if role == 'user' else None,
497
+ 'user_id': user_id, # ذخیره user_id برای مدیریت Hybrid
498
+ 'has_reply': False,
499
+ 'message_type': 'group'
500
+ }
501
+
502
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
503
+ message['has_reply'] = True
504
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
505
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
506
+ message['reply_to_content'] = reply_info['replied_text']
507
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
508
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
509
+
510
+ DATA['groups'][chat_id_str]['context'].append(message)
511
+
512
+ # محدود کردن context گروه
513
+ trim_group_context(chat_id, max_tokens=32768)
514
+
515
+ save_data()
516
+
517
+ def optimize_group_context(chat_id: int):
518
+ """بهینه‌سازی context گروه برای حفظ مهم‌ترین پیام‌ها"""
519
+ chat_id_str = str(chat_id)
520
+
521
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
522
+ return
523
+
524
+ context = DATA['groups'][chat_id_str]['context']
525
+ if len(context) <= 10:
526
+ return
527
+
528
+ # محاسبه اهمیت هر پیام
529
+ scored_messages = []
530
+ for i, msg in enumerate(context):
531
+ score = 0
532
+
533
+ # امتیاز بر اساس طول
534
+ content_length = len(msg['content'])
535
+ score += min(content_length / 100, 10)
536
+
537
+ # امتیاز بر اساس تازگی
538
+ recency = len(context) - i
539
+ score += min(recency / 10, 20)
540
+
541
+ # امتیاز بیشتر برای پاسخ‌های هوش مصنوعی
542
+ if msg['role'] == 'assistant':
543
+ score += 15
544
+
545
+ # امتیاز بیشتر برای پیام‌های دارای ریپلای
546
+ if msg.get('has_reply', False):
547
+ score += 10
548
+
549
+ # امتیاز منفی برای پیام‌های کوتاه
550
+ if content_length < 20:
551
+ score -= 5
552
+
553
+ scored_messages.append((score, msg))
554
+
555
+ # مرتب‌سازی بر اساس امتیاز
556
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
557
+
558
+ # حفظ 90% از پیام‌های با بالاترین امتیاز
559
+ keep_count = int(len(scored_messages) * 0.9)
560
+ kept_messages = [msg for _, msg in scored_messages[:keep_count]]
561
+
562
+ # مرتب‌سازی مجدد بر اساس زمان
563
+ kept_messages.sort(key=lambda x: x.get('timestamp', ''))
564
+
565
+ DATA['groups'][chat_id_str]['context'] = kept_messages
566
+ save_data()
567
+
568
+ logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages")
569
+
570
+ def trim_group_context(chat_id: int, max_tokens: int = 32768):
571
+ """کوتاه کردن context گروه به تعداد توکن مشخص"""
572
+ chat_id_str = str(chat_id)
573
+
574
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
575
+ return
576
+
577
+ context = DATA['groups'][chat_id_str]['context']
578
+
579
+ if not context:
580
+ return
581
+
582
+ # محاسبه توکن‌های کل
583
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
584
+
585
+ # اگر تعداد توکن‌ها بیش از حد مجاز است، ابتدا بهینه‌سازی کن
586
+ if total_tokens > max_tokens * 1.5:
587
+ optimize_group_context(chat_id)
588
+ context = DATA['groups'][chat_id_str]['context']
589
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
590
+
591
+ # حذف قدیمی‌ترین پیام‌ها
592
+ while total_tokens > max_tokens and len(context) > 1:
593
+ removed_message = context.pop(0)
594
+ total_tokens -= count_tokens(removed_message['content'])
595
+
596
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
597
+ if total_tokens > max_tokens and context:
598
+ last_message = context[-1]
599
+ content = last_message['content']
600
+
601
+ tokens = count_tokens(content)
602
+ if tokens > max_tokens:
603
+ context.pop()
604
+ else:
605
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
606
+ words = content.split()
607
+ if len(words) > 1:
608
+ content = ' '.join(words[:-1])
609
+ else:
610
+ content = content[:-1] if len(content) > 1 else ''
611
+ tokens = count_tokens(content)
612
+
613
+ if content:
614
+ context[-1]['content'] = content
615
+ else:
616
+ context.pop()
617
+
618
+ save_data()
619
+
620
+ def get_group_context(chat_id: int) -> list:
621
+ """دریافت context گروه"""
622
+ chat_id_str = str(chat_id)
623
+
624
+ if chat_id_str not in DATA['groups']:
625
+ return []
626
+
627
+ return DATA['groups'][chat_id_str].get('context', []).copy()
628
+
629
+ def get_context_for_api_group(chat_id: int) -> list:
630
+ """فرمت context گروه برای ارسال به API"""
631
+ context = get_group_context(chat_id)
632
+
633
+ api_context = []
634
+ for msg in context:
635
+ api_context.append({
636
+ 'role': msg['role'],
637
+ 'content': msg['content']
638
+ })
639
+
640
+ return api_context
641
+
642
+ def clear_group_context(chat_id: int):
643
+ """پاک کردن context گروه"""
644
+ with DATA_LOCK:
645
+ chat_id_str = str(chat_id)
646
+
647
+ if chat_id_str in DATA['groups']:
648
+ if 'context' in DATA['groups'][chat_id_str]:
649
+ DATA['groups'][chat_id_str]['context'] = []
650
+ save_data()
651
+ logger.info(f"Context cleared for group {chat_id}")
652
+
653
+ def get_group_context_summary(chat_id: int) -> str:
654
+ """خلاصه‌ای از context گروه"""
655
+ context = get_group_context(chat_id)
656
+ if not context:
657
+ return "بدون تاریخچه"
658
+
659
+ total_messages = len(context)
660
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
661
+
662
+ # تعداد ریپلای‌ها
663
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
664
+
665
+ # شمارش کاربران منحصربه‌فرد
666
+ unique_users = set()
667
+ for msg in context:
668
+ if msg.get('user_id'):
669
+ unique_users.add(msg['user_id'])
670
+
671
+ last_message = context[-1] if context else {}
672
+ last_content = last_message.get('content', '')[:50]
673
+ if len(last_message.get('content', '')) > 50:
674
+ last_content += "..."
675
+
676
+ return f"{total_messages} پیام ({total_tokens} توکن) - {len(unique_users)} کاربر - {reply_count} ریپلای - آخرین: {last_content}"
677
+
678
+ # --- توابع سیستم Hybrid پیشرفته ---
679
+ def add_to_hybrid_context_advanced(user_id: int, chat_id: int, role: str, content: str,
680
+ user_name: str = None, reply_info: dict = None):
681
+ """
682
+ ذخیره پیشرفته در context ترکیبی
683
+ هم در تاریخچه شخصی و هم در تاریخچه گروه ذخیره می‌شود
684
+ """
685
+ # ذخیره در تاریخچه شخصی کاربر
686
+ add_to_user_context_with_reply(user_id, role, content, reply_info)
687
+
688
+ # ذخیره در تاریخچه گروه با اطلاعات کامل
689
+ add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info, user_id)
690
+
691
+ def get_advanced_hybrid_context_for_api(user_id: int, chat_id: int) -> list:
692
+ """
693
+ دریافت context ترکیبی پیشرفته برای ارسال به API
694
+ ترکیب هوشمندانه:
695
+ 1. تاریخچه شخصی کاربر
696
+ 2. تاریخچه گروه (بدون تکراری‌ها)
697
+ 3. اطلاعات کاربران دیگر فعال در گروه
698
+ """
699
+ # 1. دریافت system instruction
700
+ system_instruction = get_system_instruction(user_id=user_id, chat_id=chat_id)
701
+
702
+ # 2. دریافت تاریخچه شخصی کاربر
703
+ user_context = get_context_for_api(user_id)
704
+
705
+ # 3. دریافت تاریخچه گروه
706
+ group_context_raw = get_group_context(chat_id)
707
+
708
+ # 4. فیلتر کردن: حذف پیام‌های تکراری کاربر فعلی از تاریخچه گروه
709
+ user_messages_in_personal = set()
710
+ for msg in user_context:
711
+ if msg['role'] == 'user':
712
+ # استخراج متن اصلی (بدون نام کاربر)
713
+ content = msg['content']
714
+ user_messages_in_personal.add(content[:100]) # ذخیره 100 کاراکتر اول
715
+
716
+ filtered_group_context = []
717
+ for msg in group_context_raw:
718
+ if msg.get('user_id') == user_id and msg['role'] == 'user':
719
+ # بررسی اینکه آیا این پیام در تاریخچه شخصی کاربر هست
720
+ content_snippet = msg['content'][:100]
721
+ if content_snippet in user_messages_in_personal:
722
+ continue # حذف پیام تکراری
723
+ filtered_group_context.append(msg)
724
+
725
+ # 5. دریافت اطلاعات کاربران دیگر در گروه
726
+ other_users_info = get_other_users_summary_in_group(user_id, chat_id)
727
+
728
+ # 6. ترکیب پیام‌ها
729
+ combined_context = []
730
+
731
+ # اضافه کردن system instruction
732
+ if system_instruction:
733
+ combined_context.append({"role": "system", "content": system_instruction})
734
+
735
+ # اضافه کردن دستور ویژه برای حالت Hybrid
736
+ hybrid_instruction = f"""
737
+ شما در حال پاسخ به کاربر {user_id} ({get_user_name(user_id)}) در یک گروه هستید.
738
+
739
+ اطلاعات وضعیت:
740
+ - حالت: Hybrid پیشرفته
741
+ - کاربر فعلی: {get_user_name(user_id)} (آیدی: {user_id})
742
+ - گروه: {get_group_name(chat_id)}
743
+ - کاربران دیگر فعال در گروه: {len(other_users_info)} کاربر
744
+
745
+ دستورالعمل‌ها:
746
+ 1. پاسخ‌های شما باید مخصوص کاربر فعلی ({get_user_name(user_id)}) باشد.
747
+ 2. می‌توانید به کاربران دیگر نیز در پاسخ اشاره کنید اگر مرتبط است.
748
+ 3. از تاریخچه شخصی کاربر و تاریخچه گروه استفاده کنید.
749
+ 4. پاسخ‌های دقیق و مرتبط بدهید.
750
+ """
751
+
752
+ combined_context.append({"role": "system", "content": hybrid_instruction})
753
+
754
+ # اضافه کردن اطلاعات خلاصه کاربران دیگر
755
+ if other_users_info and DATA['hybrid_settings']['enable_cross_user_references']:
756
+ other_users_summary = "📋 **اطلاعات کاربران دیگر در گروه:**\n"
757
+ for info in other_users_info:
758
+ other_users_summary += f"- {info['name']}: {info['summary']}\n"
759
+
760
+ combined_context.append({
761
+ "role": "system",
762
+ "content": other_users_summary[:500] + "..." if len(other_users_summary) > 500 else other_users_summary
763
+ })
764
+
765
+ # اضافه کردن تاریخچه شخصی کاربر
766
+ combined_context.extend(user_context[-10:]) # فقط 10 پیام آخر شخصی
767
+
768
+ # اضافه کردن تاریخچه گروه فیلتر شده
769
+ for msg in filtered_group_context[-20:]: # فقط 20 پیام آخر گروه
770
+ combined_context.append({
771
+ 'role': msg['role'],
772
+ 'content': msg['content']
773
+ })
774
+
775
+ # محدود کردن کل توکن‌ها
776
+ return limit_context_tokens(combined_context, DATA['hybrid_settings']['max_combined_tokens'])
777
+
778
+ def get_other_users_summary_in_group(current_user_id: int, chat_id: int) -> list:
779
+ """دریافت خلاصه اطلاعات کاربران دیگر در گروه"""
780
+ chat_id_str = str(chat_id)
781
+
782
+ if chat_id_str not in DATA['groups']:
783
+ return []
784
+
785
+ group_info = DATA['groups'][chat_id_str]
786
+ recent_users = group_info.get('recent_users', [])
787
+
788
+ other_users_info = []
789
+
790
+ for other_user_id in recent_users[:DATA['hybrid_settings']['max_other_users']]:
791
+ if other_user_id == current_user_id:
792
+ continue
793
+
794
+ user_info = DATA['users'].get(str(other_user_id), {})
795
+ if not user_info:
796
+ continue
797
+
798
+ user_name = user_info.get('first_name', 'کاربر')
799
+ message_count = user_info.get('message_count', 0)
800
+ last_seen = user_info.get('last_seen', 'نامشخص')
801
+
802
+ # دریافت آخرین پیام در گروه از این کاربر
803
+ last_group_message = None
804
+ for msg in reversed(group_info.get('context', [])):
805
+ if msg.get('user_id') == other_user_id and msg['role'] == 'user':
806
+ last_group_message = msg['content'][:100]
807
+ if len(msg['content']) > 100:
808
+ last_group_message += "..."
809
+ break
810
+
811
+ # ایجاد خلاصه
812
+ summary = f"{message_count} پیام"
813
+ if last_group_message:
814
+ summary += f" - آخرین: {last_group_message}"
815
+
816
+ other_users_info.append({
817
+ 'user_id': other_user_id,
818
+ 'name': user_name,
819
+ 'message_count': message_count,
820
+ 'last_seen': last_seen,
821
+ 'last_message': last_group_message,
822
+ 'summary': summary
823
+ })
824
+
825
+ return other_users_info
826
+
827
+ def get_recent_users_in_group(chat_id: int, limit: int = 5) -> list:
828
+ """دریافت لیست کاربران اخیراً فعال در گروه"""
829
+ chat_id_str = str(chat_id)
830
+
831
+ if chat_id_str not in DATA['groups']:
832
+ return []
833
+
834
+ group_info = DATA['groups'][chat_id_str]
835
+ recent_users = group_info.get('recent_users', [])
836
+
837
+ return recent_users[:limit]
838
+
839
+ def get_user_name(user_id: int) -> str:
840
+ """دریافت نام کاربر"""
841
+ user_id_str = str(user_id)
842
+ user_info = DATA['users'].get(user_id_str, {})
843
+ return user_info.get('first_name', f"کاربر {user_id}")
844
+
845
+ def get_group_name(chat_id: int) -> str:
846
+ """دریافت نام گروه"""
847
+ chat_id_str = str(chat_id)
848
+ group_info = DATA['groups'].get(chat_id_str, {})
849
+ return group_info.get('title', f"گروه {chat_id}")
850
+
851
+ def limit_context_tokens(context: list, max_tokens: int) -> list:
852
+ """محدود کردن context به تعداد توکن مشخص"""
853
+ if not context:
854
+ return context
855
+
856
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
857
+
858
+ if total_tokens <= max_tokens:
859
+ return context
860
+
861
+ # حذف پیام‌ها از ابتدا تا زمانی که توکن‌ها زیر حد مجاز باشد
862
+ limited_context = context.copy()
863
+ while total_tokens > max_tokens and len(limited_context) > 1:
864
+ # سعی نکنیم system instructions را حذف کنیم
865
+ if limited_context[0]['role'] == 'system':
866
+ # سیستم را حذف نکن، پیام بعدی را حذف کن
867
+ if len(limited_context) > 2:
868
+ removed = limited_context.pop(1)
869
+ total_tokens -= count_tokens(removed['content'])
870
+ else:
871
+ break
872
+ else:
873
+ removed = limited_context.pop(0)
874
+ total_tokens -= count_tokens(removed['content'])
875
+
876
+ return limited_context
877
+
878
+ def get_hybrid_context_summary(user_id: int, chat_id: int) -> str:
879
+ """خلاصه‌ای از context ترکیبی پیشرفته"""
880
+ personal_summary = get_context_summary(user_id)
881
+ group_summary = get_group_context_summary(chat_id)
882
+
883
+ # اطلاعات کاربران دیگر
884
+ other_users = get_recent_users_in_group(chat_id, limit=5)
885
+ other_users_count = len([uid for uid in other_users if uid != user_id])
886
+
887
+ hybrid_mode = DATA['hybrid_settings']['mode']
888
+
889
+ return (
890
+ f"📊 **حالت Hybrid {hybrid_mode} فعال**\n\n"
891
+ f"👤 **شخصی شما:** {personal_summary}\n"
892
+ f"👥 **گروه:** {group_summary}\n"
893
+ f"👥 **کاربران فعال دیگر در گروه:** {other_users_count} کاربر\n"
894
+ f"⚙️ **تنظیمات:**\n"
895
+ f"• وزن تاریخچه شخصی: {DATA['hybrid_settings']['personal_context_weight']}\n"
896
+ f"• وزن تاریخچه گروه: {DATA['hybrid_settings']['group_context_weight']}\n"
897
+ f"• ارجاع به کاربران دیگر: {'فعال ✅' if DATA['hybrid_settings']['enable_cross_user_references'] else 'غیرفعال ❌'}"
898
+ )
899
+
900
+ # --- توابع مدیریت حالت context ---
901
+ def get_context_mode() -> str:
902
+ """دریافت حالت فعلی context"""
903
+ return DATA.get('context_mode', 'hybrid')
904
+
905
+ def set_context_mode(mode: str):
906
+ """تنظیم حالت context"""
907
+ valid_modes = ['separate', 'group_shared', 'hybrid']
908
+ if mode in valid_modes:
909
+ DATA['context_mode'] = mode
910
+ save_data()
911
+ logger.info(f"Context mode changed to: {mode}")
912
+ return True
913
+ return False
914
+
915
+ def set_hybrid_mode(mode: str):
916
+ """تنظیم حالت Hybrid"""
917
+ if mode in ['basic', 'advanced']:
918
+ if 'hybrid_settings' not in DATA:
919
+ DATA['hybrid_settings'] = {}
920
+
921
+ DATA['hybrid_settings']['mode'] = mode
922
+
923
+ if mode == 'advanced':
924
+ # تنظیمات پیشرفته
925
+ DATA['hybrid_settings']['enable_user_tracking'] = True
926
+ DATA['hybrid_settings']['max_other_users'] = 5
927
+ DATA['hybrid_settings']['personal_context_weight'] = 1.0
928
+ DATA['hybrid_settings']['group_context_weight'] = 0.8
929
+ DATA['hybrid_settings']['other_users_weight'] = 0.6
930
+ DATA['hybrid_settings']['max_combined_tokens'] = 30000
931
+ DATA['hybrid_settings']['enable_cross_user_references'] = True
932
+ else:
933
+ # تنظیمات ساده
934
+ DATA['hybrid_settings']['enable_user_tracking'] = True
935
+ DATA['hybrid_settings']['max_other_users'] = 3
936
+ DATA['hybrid_settings']['personal_context_weight'] = 1.0
937
+ DATA['hybrid_settings']['group_context_weight'] = 0.7
938
+ DATA['hybrid_settings']['other_users_weight'] = 0.4
939
+ DATA['hybrid_settings']['max_combined_tokens'] = 25000
940
+ DATA['hybrid_settings']['enable_cross_user_references'] = False
941
+
942
+ save_data()
943
+ logger.info(f"Hybrid mode set to: {mode}")
944
+ return True
945
+ return False
946
+
947
+ # --- توابع مدیریت system instructions ---
948
+ def get_system_instruction(user_id: int = None, chat_id: int = None) -> str:
949
+ """دریافت system instruction مناسب برای کاربر/گروه"""
950
+ user_id_str = str(user_id) if user_id else None
951
+ chat_id_str = str(chat_id) if chat_id else None
952
+
953
+ # بررسی برای کاربر
954
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
955
+ instruction_data = DATA['system_instructions']['users'][user_id_str]
956
+ if instruction_data.get('enabled', True):
957
+ return instruction_data.get('instruction', '')
958
+
959
+ # بررسی برای گروه
960
+ if chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
961
+ instruction_data = DATA['system_instructions']['groups'][chat_id_str]
962
+ if instruction_data.get('enabled', True):
963
+ return instruction_data.get('instruction', '')
964
+
965
+ # بازگشت به حالت سراسری
966
+ return DATA['system_instructions'].get('global', '')
967
+
968
+ def set_global_system_instruction(instruction: str) -> bool:
969
+ """تنظیم system instruction سراسری"""
970
+ DATA['system_instructions']['global'] = instruction
971
+ save_data()
972
+ return True
973
+
974
+ def set_group_system_instruction(chat_id: int, instruction: str, set_by_user_id: int) -> bool:
975
+ """تنظیم system instruction برای گروه"""
976
+ chat_id_str = str(chat_id)
977
+ DATA['system_instructions']['groups'][chat_id_str] = {
978
+ 'instruction': instruction,
979
+ 'set_by': set_by_user_id,
980
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
981
+ 'enabled': True
982
+ }
983
+ save_data()
984
+ return True
985
+
986
+ def set_user_system_instruction(user_id: int, instruction: str, set_by_user_id: int) -> bool:
987
+ """تنظیم system instruction برای کاربر"""
988
+ user_id_str = str(user_id)
989
+ DATA['system_instructions']['users'][user_id_str] = {
990
+ 'instruction': instruction,
991
+ 'set_by': set_by_user_id,
992
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
993
+ 'enabled': True
994
+ }
995
+ save_data()
996
+ return True
997
+
998
+ def remove_group_system_instruction(chat_id: int) -> bool:
999
+ """حذف system instruction گروه"""
1000
+ chat_id_str = str(chat_id)
1001
+ if chat_id_str in DATA['system_instructions']['groups']:
1002
+ del DATA['system_instructions']['groups'][chat_id_str]
1003
+ save_data()
1004
+ return True
1005
+ return False
1006
+
1007
+ def remove_user_system_instruction(user_id: int) -> bool:
1008
+ """حذف system instruction کاربر"""
1009
+ user_id_str = str(user_id)
1010
+ if user_id_str in DATA['system_instructions']['users']:
1011
+ del DATA['system_instructions']['users'][user_id_str]
1012
+ save_data()
1013
+ return True
1014
+ return False
1015
+
1016
+ def toggle_group_system_instruction(chat_id: int, enabled: bool) -> bool:
1017
+ """فعال/غیرفعال کردن system instruction گروه"""
1018
+ chat_id_str = str(chat_id)
1019
+ if chat_id_str in DATA['system_instructions']['groups']:
1020
+ DATA['system_instructions']['groups'][chat_id_str]['enabled'] = enabled
1021
+ save_data()
1022
+ return True
1023
+ return False
1024
+
1025
+ def toggle_user_system_instruction(user_id: int, enabled: bool) -> bool:
1026
+ """فعال/غیرفعال کردن system instruction کاربر"""
1027
+ user_id_str = str(user_id)
1028
+ if user_id_str in DATA['system_instructions']['users']:
1029
+ DATA['system_instructions']['users'][user_id_str]['enabled'] = enabled
1030
+ save_data()
1031
+ return True
1032
+ return False
1033
+
1034
+ def get_system_instruction_info(user_id: int = None, chat_id: int = None) -> dict:
1035
+ """دریافت اطلاعات system instruction"""
1036
+ user_id_str = str(user_id) if user_id else None
1037
+ chat_id_str = str(chat_id) if chat_id else None
1038
+
1039
+ result = {
1040
+ 'has_instruction': False,
1041
+ 'type': 'global',
1042
+ 'instruction': DATA['system_instructions'].get('global', ''),
1043
+ 'details': None
1044
+ }
1045
+
1046
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
1047
+ user_data = DATA['system_instructions']['users'][user_id_str]
1048
+ result.update({
1049
+ 'has_instruction': True,
1050
+ 'type': 'user',
1051
+ 'instruction': user_data.get('instruction', ''),
1052
+ 'details': user_data
1053
+ })
1054
+ elif chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
1055
+ group_data = DATA['system_instructions']['groups'][chat_id_str]
1056
+ result.update({
1057
+ 'has_instruction': True,
1058
+ 'type': 'group',
1059
+ 'instruction': group_data.get('instruction', ''),
1060
+ 'details': group_data
1061
+ })
1062
+
1063
+ return result
1064
+
1065
+ # بارگذاری اولیه داده‌ها
1066
+ load_data()
1067
+ logger.info(f"Data loaded. Context mode: {get_context_mode()}, Hybrid mode: {DATA['hybrid_settings']['mode']}")
BOT/render-main/FIXES/fix_data.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fix_data.py
2
+ import json
3
+ import os
4
+
5
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
6
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
7
+
8
+ def fix_data_file():
9
+ """رفع مشکلات فایل داده‌های موجود"""
10
+ if not os.path.exists(DATA_FILE):
11
+ print(f"فایل داده در {DATA_FILE} یافت نشد.")
12
+ return
13
+
14
+ try:
15
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
16
+ data = json.load(f)
17
+
18
+ # رفع مشکل banned_users
19
+ if 'banned_users' in data and isinstance(data['banned_users'], list):
20
+ data['banned_users'] = list(set(data['banned_users'])) # حذف duplicates
21
+
22
+ # رفع مشکل groups و members
23
+ if 'groups' in data:
24
+ for group_id, group_info in data['groups'].items():
25
+ # رفع مشکل members
26
+ if 'members' in group_info:
27
+ if isinstance(group_info['members'], list):
28
+ # تبدیل list به set و سپس دوباره به list (حذف duplicates)
29
+ members_set = set(group_info['members'])
30
+ group_info['members'] = list(members_set)
31
+ elif isinstance(group_info['members'], set):
32
+ # اگر set است، به list تبدیل کن
33
+ group_info['members'] = list(group_info['members'])
34
+ else:
35
+ # اگر نه list است نه set، آن را list خالی کن
36
+ group_info['members'] = []
37
+
38
+ # اطمینان از وجود کلیدهای ضروری
39
+ if 'context' not in group_info:
40
+ group_info['context'] = []
41
+ if 'title' not in group_info:
42
+ group_info['title'] = 'Unknown Group'
43
+ if 'type' not in group_info:
44
+ group_info['type'] = 'group'
45
+
46
+ # رفع مشکل users
47
+ if 'users' in data:
48
+ for user_id, user_info in data['users'].items():
49
+ if 'context' not in user_info:
50
+ user_info['context'] = []
51
+
52
+ # ذخیره فایل اصلاح شده
53
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
54
+ json.dump(data, f, indent=4, ensure_ascii=False)
55
+
56
+ print(f"فایل داده در {DATA_FILE} با موفقیت اصلاح شد.")
57
+
58
+ # نمایش آمار
59
+ print("\n📊 آمار فایل اصلاح شده:")
60
+ print(f"تعداد کاربران: {len(data.get('users', {}))}")
61
+ print(f"تعداد گروه‌ها: {len(data.get('groups', {}))}")
62
+ print(f"کاربران مسدود شده: {len(data.get('banned_users', []))}")
63
+
64
+ # بررسی groups
65
+ groups_with_member_issues = 0
66
+ for group_id, group_info in data.get('groups', {}).items():
67
+ if 'members' in group_info and not isinstance(group_info['members'], list):
68
+ groups_with_member_issues += 1
69
+
70
+ if groups_with_member_issues > 0:
71
+ print(f"⚠️ {groups_with_member_issues} گروه دارای مشکل در members هستند.")
72
+ else:
73
+ print("✅ همه groups به درستی اصلاح شدند.")
74
+
75
+ except Exception as e:
76
+ print(f"خطا در اصلاح فایل داده: {e}")
77
+
78
+ if __name__ == "__main__":
79
+ fix_data_file()
BOT/render-main/FIXES/keep_alive.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import threading
3
+ import time
4
+
5
+ def ping_service():
6
+ """ارسال درخواست پینگ به سرویس برای نگه داشتن آن فعال."""
7
+ url = "https://render2-bot.onrender.com"
8
+ while True:
9
+ try:
10
+ requests.get(url)
11
+ print(f"Pinged {url} to keep service alive")
12
+ except Exception as e:
13
+ print(f"Error pinging service: {e}")
14
+
15
+ # هر 14 دقیقه یک بار پینگ بزن (زیر 15 دقیقه برای جلوگیری از خاموشی)
16
+ time.sleep(1 * 60)
17
+
18
+ # شروع ترد پینگ در پس‌زمینه
19
+ def start_keep_alive():
20
+ """شروع سرویس نگه داشتن ربات فعال."""
21
+ thread = threading.Thread(target=ping_service)
22
+ thread.daemon = True
23
+ thread.start()
BOT/render-main/FIXES/main.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import asyncio
4
+ import httpx
5
+ import time
6
+ from telegram import Update
7
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
8
+ from openai import AsyncOpenAI
9
+ from keep_alive import start_keep_alive
10
+ from datetime import datetime
11
+ from flask import Flask, jsonify
12
+
13
+ import threading
14
+
15
+ flask_app = Flask(__name__)
16
+
17
+ @flask_app.route('/')
18
+ def home():
19
+ return jsonify({"status": "ok", "service": "telegram-bot"})
20
+
21
+ @flask_app.route('/health')
22
+ def health_check():
23
+ return jsonify({
24
+ "status": "healthy",
25
+ "timestamp": datetime.now().isoformat(),
26
+ "service": "telegram-bot"
27
+ })
28
+
29
+ @flask_app.route('/webhook', methods=['POST'])
30
+ def webhook_receiver():
31
+ """این endpoint توسط Telegram استفاده می‌شود"""
32
+ # Telegram webhook handler
33
+ pass
34
+
35
+ def run_flask():
36
+ """اجرای Flask در یک thread جداگانه"""
37
+ port = int(os.environ.get("FLASK_PORT", 5000))
38
+ flask_app.run(host='0.0.0.0', port=port)
39
+
40
+ # وارد کردن مدیر داده‌ها و پنل ادمین
41
+ import data_manager
42
+ import admin_panel
43
+ import system_instruction_handlers
44
+
45
+ # بارگذاری داده‌ها در ابتدا
46
+ data_manager.load_data()
47
+
48
+ # شروع سرویس نگه داشتن ربات فعال
49
+ start_keep_alive()
50
+
51
+ # --- بهبود لاگینگ ---
52
+ logging.basicConfig(
53
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
54
+ level=logging.INFO,
55
+ filename=data_manager.LOG_FILE,
56
+ filemode='a'
57
+ )
58
+ logger = logging.getLogger(__name__)
59
+
60
+ try:
61
+ with open(data_manager.LOG_FILE, 'a') as f:
62
+ f.write("")
63
+ except Exception as e:
64
+ print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
65
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
66
+
67
+ # --- ایجاد یک کلاینت HTTP بهینه‌سازی‌شده ---
68
+ http_client = httpx.AsyncClient(
69
+ http2=True,
70
+ limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
71
+ timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
72
+ )
73
+
74
+ # کلاینت OpenAI (HuggingFace)
75
+ client = AsyncOpenAI(
76
+ base_url="https://router.huggingface.co/v1",
77
+ api_key=os.environ["HF_TOKEN"],
78
+ http_client=http_client
79
+ )
80
+
81
+ # --- دیکشنری برای مدیریت وظایف پس‌زمینه هر کاربر ---
82
+ user_tasks = {} # برای چت خصوصی: {user_id: task}
83
+ user_group_tasks = {} # برای گروه: {(chat_id, user_id): task}
84
+
85
+ # --- توابع کمکی برای مدیریت ریپلای ---
86
+ def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple:
87
+ """استخراج اطلاعات از ریپلای"""
88
+ message = update.message
89
+
90
+ # اگر ریپلای وجود نداشت
91
+ if not message or not message.reply_to_message:
92
+ return None, None, None, None
93
+
94
+ replied_message = message.reply_to_message
95
+
96
+ # اطلاعات پیام ریپلای شده
97
+ replied_user_id = replied_message.from_user.id if replied_message.from_user else None
98
+ replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown"
99
+
100
+ # استخراج متن پیام ریپلای شده
101
+ replied_text = ""
102
+ if replied_message.text:
103
+ replied_text = replied_message.text
104
+ elif replied_message.caption:
105
+ replied_text = replied_message.caption
106
+
107
+ # بررسی اینکه آیا ریپلای به ربات است
108
+ is_reply_to_bot = False
109
+ if replied_message.from_user:
110
+ if replied_message.from_user.is_bot:
111
+ is_reply_to_bot = True
112
+ elif context.bot and context.bot.username and replied_message.text:
113
+ if f"@{context.bot.username}" in replied_message.text:
114
+ is_reply_to_bot = True
115
+
116
+ return replied_user_id, replied_user_name, replied_text, is_reply_to_bot
117
+
118
+ def format_reply_message(user_message: str, replied_user_name: str, replied_text: str,
119
+ is_reply_to_bot: bool = False, current_user_name: str = None) -> str:
120
+ """فرمت‌دهی پیام با در نظر گرفتن ریپلای"""
121
+ if not replied_text:
122
+ return user_message
123
+
124
+ # محدود کردن طول متن ریپلای شده
125
+ if len(replied_text) > 100:
126
+ replied_preview = replied_text[:97] + "..."
127
+ else:
128
+ replied_preview = replied_text
129
+
130
+ # حذف منشن ربات از متن ریپلای شده اگر وجود دارد
131
+ replied_preview = replied_preview.replace("@", "(at)")
132
+
133
+ if is_reply_to_bot:
134
+ if current_user_name:
135
+ return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}"
136
+ else:
137
+ return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}"
138
+ else:
139
+ if current_user_name:
140
+ return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
141
+ else:
142
+ return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
143
+
144
+ def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot):
145
+ """ایجاد دیکشنری اطلاعات ریپلای"""
146
+ if not replied_text:
147
+ return None
148
+
149
+ return {
150
+ 'replied_user_id': replied_user_id,
151
+ 'replied_user_name': replied_user_name,
152
+ 'replied_text': replied_text[:1500],
153
+ 'is_reply_to_bot': is_reply_to_bot,
154
+ 'timestamp': time.time()
155
+ }
156
+
157
+ # --- توابع کمکی برای مدیریت وظایف ---
158
+ def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int):
159
+ if task_id in task_dict and task_dict[task_id] == task:
160
+ del task_dict[task_id]
161
+ logger.info(f"Cleaned up finished task for ID {task_id}.")
162
+ try:
163
+ exception = task.exception()
164
+ if exception:
165
+ logger.error(f"Background task for ID {task_id} failed: {exception}")
166
+ except asyncio.CancelledError:
167
+ logger.info(f"Task for ID {task_id} was cancelled.")
168
+ except asyncio.InvalidStateError:
169
+ pass
170
+
171
+ def _cleanup_user_group_task(task: asyncio.Task, chat_id: int, user_id: int):
172
+ """پاک‌سازی وظایف کاربران در گروه"""
173
+ task_key = (chat_id, user_id)
174
+ if task_key in user_group_tasks and user_group_tasks[task_key] == task:
175
+ del user_group_tasks[task_key]
176
+ logger.info(f"Cleaned up finished task for group {chat_id}, user {user_id}.")
177
+ try:
178
+ exception = task.exception()
179
+ if exception:
180
+ logger.error(f"Background task for group {chat_id}, user {user_id} failed: {exception}")
181
+ except asyncio.CancelledError:
182
+ logger.info(f"Task for group {chat_id}, user {user_id} was cancelled.")
183
+ except asyncio.InvalidStateError:
184
+ pass
185
+
186
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE,
187
+ custom_message: str = None, reply_info: dict = None):
188
+ """پردازش درخواست کاربر در چت خصوصی"""
189
+ chat_id = update.effective_chat.id
190
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
191
+ user_id = update.effective_user.id
192
+
193
+ if not user_message:
194
+ logger.warning(f"No message content for user {user_id}")
195
+ return
196
+
197
+ if reply_info is None:
198
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
199
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
200
+
201
+ if reply_info and reply_info.get('replied_text'):
202
+ formatted_message = format_reply_message(
203
+ user_message,
204
+ reply_info.get('replied_user_name', 'Unknown'),
205
+ reply_info.get('replied_text'),
206
+ reply_info.get('is_reply_to_bot', False)
207
+ )
208
+ else:
209
+ formatted_message = user_message
210
+
211
+ start_time = time.time()
212
+
213
+ try:
214
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
215
+
216
+ user_context = data_manager.get_context_for_api(user_id)
217
+
218
+ data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
219
+
220
+ system_instruction = data_manager.get_system_instruction(user_id=user_id)
221
+
222
+ messages = []
223
+
224
+ if system_instruction:
225
+ messages.append({"role": "system", "content": system_instruction})
226
+
227
+ messages.extend(user_context.copy())
228
+ messages.append({"role": "user", "content": formatted_message})
229
+
230
+ logger.info(f"User {user_id} sending {len(messages)} messages to AI")
231
+ if reply_info and reply_info.get('replied_text'):
232
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
233
+
234
+ response = await client.chat.completions.create(
235
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
236
+ messages=messages,
237
+ temperature=0.7,
238
+ top_p=0.95,
239
+ stream=False,
240
+ )
241
+
242
+ end_time = time.time()
243
+ response_time = end_time - start_time
244
+ data_manager.update_response_stats(response_time)
245
+
246
+ ai_response = response.choices[0].message.content
247
+
248
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
249
+
250
+ await update.message.reply_text(ai_response)
251
+ data_manager.update_user_stats(user_id, update.effective_user)
252
+
253
+ except httpx.TimeoutException:
254
+ logger.warning(f"Request timed out for user {user_id}.")
255
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره ��لاش کنید.")
256
+ except Exception as e:
257
+ logger.error(f"Error while processing message for user {user_id}: {e}")
258
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
259
+
260
+ async def _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE,
261
+ custom_message: str = None, reply_info: dict = None):
262
+ """پردازش درخواست در گروه با حالت Hybrid پیشرفته"""
263
+ chat_id = update.effective_chat.id
264
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
265
+ user_id = update.effective_user.id
266
+ user_name = update.effective_user.first_name
267
+
268
+ if not user_message:
269
+ logger.warning(f"No message content for group {chat_id}, user {user_id}")
270
+ return
271
+
272
+ if reply_info is None:
273
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
274
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
275
+
276
+ if reply_info and reply_info.get('replied_text'):
277
+ formatted_message = format_reply_message(
278
+ user_message,
279
+ reply_info.get('replied_user_name', 'Unknown'),
280
+ reply_info.get('replied_text'),
281
+ reply_info.get('is_reply_to_bot', False),
282
+ user_name
283
+ )
284
+ else:
285
+ formatted_message = user_message
286
+
287
+ start_time = time.time()
288
+
289
+ try:
290
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
291
+
292
+ context_mode = data_manager.get_context_mode()
293
+ hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
294
+
295
+ if context_mode == 'hybrid' and hybrid_mode == 'advanced':
296
+ # حالت Hybrid پیشرفته
297
+ messages = data_manager.get_advanced_hybrid_context_for_api(user_id, chat_id)
298
+
299
+ data_manager.add_to_hybrid_context_advanced(
300
+ user_id, chat_id, "user", formatted_message, user_name, reply_info
301
+ )
302
+
303
+ messages.append({
304
+ "role": "user",
305
+ "content": f"{user_name}: {formatted_message}"
306
+ })
307
+
308
+ logger.info(f"Group {chat_id} - Advanced Hybrid mode active for user {user_id}")
309
+
310
+ elif context_mode == 'hybrid':
311
+ # حالت Hybrid ساده
312
+ messages = data_manager.get_context_for_api(user_id)
313
+ group_context = data_manager.get_context_for_api_group(chat_id)
314
+
315
+ data_manager.add_to_hybrid_context_advanced(
316
+ user_id, chat_id, "user", formatted_message, user_name, reply_info
317
+ )
318
+
319
+ messages.extend(group_context[-10:]) # اضافه کردن 10 پیام آخر گروه
320
+ messages.append({
321
+ "role": "user",
322
+ "content": f"{user_name}: {formatted_message}"
323
+ })
324
+
325
+ elif context_mode == 'group_shared':
326
+ messages = data_manager.get_context_for_api_group(chat_id)
327
+ data_manager.add_to_group_context_with_reply(
328
+ chat_id, "user", formatted_message, user_name, reply_info, user_id
329
+ )
330
+
331
+ messages.append({
332
+ "role": "user",
333
+ "content": f"{user_name}: {formatted_message}"
334
+ })
335
+
336
+ else: # separate
337
+ messages = data_manager.get_context_for_api(user_id)
338
+ data_manager.add_to_user_context_with_reply(
339
+ user_id, "user", formatted_message, reply_info
340
+ )
341
+
342
+ messages.append({"role": "user", "content": formatted_message})
343
+
344
+ system_instruction = data_manager.get_system_instruction(user_id=user_id, chat_id=chat_id)
345
+
346
+ if system_instruction:
347
+ messages.insert(0, {"role": "system", "content": system_instruction})
348
+
349
+ logger.info(f"Group {chat_id} - User {user_id} ({context_mode} mode) sending {len(messages)} messages to AI")
350
+
351
+ if reply_info and reply_info.get('replied_text'):
352
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
353
+
354
+ response = await client.chat.completions.create(
355
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
356
+ messages=messages,
357
+ temperature=0.7,
358
+ top_p=0.95,
359
+ stream=False,
360
+ )
361
+
362
+ end_time = time.time()
363
+ response_time = end_time - start_time
364
+ data_manager.update_response_stats(response_time)
365
+
366
+ ai_response = response.choices[0].message.content
367
+
368
+ if context_mode == 'hybrid':
369
+ data_manager.add_to_hybrid_context_advanced(
370
+ user_id, chat_id, "assistant", ai_response, None, None
371
+ )
372
+ elif context_mode == 'group_shared':
373
+ data_manager.add_to_group_context(chat_id, "assistant", ai_response)
374
+ else:
375
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
376
+
377
+ data_manager.update_group_stats(chat_id, update.effective_chat, user_id)
378
+
379
+ await update.message.reply_text(
380
+ ai_response,
381
+ reply_to_message_id=update.message.message_id
382
+ )
383
+
384
+ except httpx.TimeoutException:
385
+ logger.warning(f"Request timed out for group {chat_id}, user {user_id}.")
386
+ await update.message.reply_text(
387
+ "⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.",
388
+ reply_to_message_id=update.message.message_id
389
+ )
390
+ except Exception as e:
391
+ logger.error(f"Error while processing message for group {chat_id}, user {user_id}: {e}")
392
+ await update.message.reply_text(
393
+ "❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
394
+ reply_to_message_id=update.message.message_id
395
+ )
396
+
397
+ # --- هندلرهای اصلی ربات ---
398
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
399
+ user = update.effective_user
400
+ user_id = user.id
401
+ chat = update.effective_chat
402
+
403
+ if chat.type in ['group', 'supergroup']:
404
+ data_manager.update_group_stats(chat.id, chat, user_id)
405
+
406
+ welcome_msg = data_manager.DATA.get('group_welcome_message',
407
+ "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیام‌ها ریپلای کنید")
408
+
409
+ context_mode = data_manager.get_context_mode()
410
+ hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
411
+
412
+ mode_info = ""
413
+ if context_mode == 'hybrid':
414
+ mode_info = f"\n\n🎯 **حالت فعلی:** Hybrid ({hybrid_mode})\n"
415
+ if hybrid_mode == 'advanced':
416
+ mode_info += "• سیستم Hybrid پیشرفته فعال است\n"
417
+ mode_info += "• ربات هر کاربر را جداگانه می‌شناسد\n"
418
+ mode_info += "• تاریخچه شخصی + گروهی + آگاهی از دیگر کاربران\n"
419
+ else:
420
+ mode_info += "• سیستم Hybrid ساده فعال است\n"
421
+ mode_info += "• تاریخچه شخصی + گروهی\n"
422
+ elif context_mode == 'group_shared':
423
+ mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده می‌شود. همه کاربران تاریخچه مکالمه یکسانی دارند."
424
+ else:
425
+ mode_info = "\n\n📝 **نکته:** در این گروه هر کاربر تاریخچه مکالمه جداگانه خود را دارد."
426
+
427
+ system_info = data_manager.get_system_instruction_info(chat_id=chat.id)
428
+ if system_info['type'] == 'group' and system_info['has_instruction']:
429
+ instruction_preview = system_info['instruction'][:100] + "..." if len(system_info['instruction']) > 100 else system_info['instruction']
430
+ mode_info += f"\n\n⚙️ **سیستم‌اینستراکشن گروه:**\n{instruction_preview}"
431
+
432
+ await update.message.reply_html(
433
+ welcome_msg + mode_info,
434
+ disable_web_page_preview=True
435
+ )
436
+ else:
437
+ data_manager.update_user_stats(user_id, user)
438
+
439
+ welcome_msg = data_manager.DATA.get('welcome_message',
440
+ "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\n\n💡 **نکته:** می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.")
441
+
442
+ await update.message.reply_html(
443
+ welcome_msg.format(user_mention=user.mention_html()),
444
+ disable_web_page_preview=True
445
+ )
446
+
447
+ async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
448
+ """پاک کردن تاریخچه چت"""
449
+ user_id = update.effective_user.id
450
+ chat = update.effective_chat
451
+
452
+ if chat.type in ['group', 'supergroup']:
453
+ data_manager.clear_group_context(chat.id)
454
+
455
+ context_mode = data_manager.get_context_mode()
456
+ if context_mode == 'group_shared':
457
+ await update.message.reply_text(
458
+ "🧹 تاریخچه مکالمه گروه پاک شد.\n"
459
+ "از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد."
460
+ )
461
+ elif context_mode == 'hybrid':
462
+ await update.message.reply_text(
463
+ "🧹 تاریخچه مکالمه گروه پاک شد.\n"
464
+ "تاریخچه شخصی شما همچنان حفظ شده است.\n"
465
+ "از این لحظه مکالمه جدیدی در گروه شروع خواهد شد."
466
+ )
467
+ else:
468
+ await update.message.reply_text(
469
+ "🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n"
470
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
471
+ )
472
+ else:
473
+ data_manager.clear_user_context(user_id)
474
+
475
+ await update.message.reply_text(
476
+ "🧹 تاریخچه مکالمه شما پاک شد.\n"
477
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
478
+ )
479
+
480
+ async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
481
+ """نمایش اطلاعات context"""
482
+ user_id = update.effective_user.id
483
+ chat = update.effective_chat
484
+
485
+ if chat.type in ['group', 'supergroup']:
486
+ context_mode = data_manager.get_context_mode()
487
+
488
+ if context_mode == 'hybrid':
489
+ hybrid_summary = data_manager.get_hybrid_context_summary(user_id, chat.id)
490
+ await update.message.reply_text(
491
+ f"📊 **اطلاعات تاریخچه مکالمه (حالت Hybrid پیشرفته):**\n\n"
492
+ f"{hybrid_summary}\n\n"
493
+ f"🎯 **ویژگی‌های این حالت:**\n"
494
+ f"✅ تاریخچه شخصی شما حفظ می‌شود (تا 16384 توکن)\n"
495
+ f"✅ تاریخچه گروه کامل ذخیره می‌شود (تا 32768 توکن)\n"
496
+ f"✅ اطلاعات دیگر کاربران فعال در نظر گرفته می‌شود\n"
497
+ f"✅ ربات می‌داند که چند کاربر در حال گفتگو هستند\n"
498
+ f"✅ پاسخ‌ها دقیق و مرتبط با هر کاربر خواهند بود\n\n"
499
+ f"برای پاک کردن تاریخچه شخصی از /clear استفاده کنید.\n"
500
+ f"برای پاک کردن تاریخچه گروه، ادمین از /clear_group_context استفاده کند."
501
+ )
502
+ elif context_mode == 'group_shared':
503
+ context_summary = data_manager.get_group_context_summary(chat.id)
504
+ await update.message.reply_text(
505
+ f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n"
506
+ f"{context_summary}\n\n"
507
+ f"**حالت:** مشترک بین همه اعضای گروه\n"
508
+ f"**سقف توکن:** 32768 توکن\n"
509
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
510
+ )
511
+ else:
512
+ context_summary = data_manager.get_context_summary(user_id)
513
+ await update.message.reply_text(
514
+ f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n"
515
+ f"{context_summary}\n\n"
516
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
517
+ )
518
+ else:
519
+ context_summary = data_manager.get_context_summary(user_id)
520
+ await update.message.reply_text(
521
+ f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
522
+ f"{context_summary}\n\n"
523
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
524
+ )
525
+
526
+ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
527
+ """نمایش دستورات کمک"""
528
+ user_id = update.effective_user.id
529
+ chat = update.effective_chat
530
+
531
+ admin_ids = admin_panel.get_admin_ids()
532
+ is_admin_bot = user_id in admin_ids
533
+ is_admin_group = system_instruction_handlers.is_group_admin(update) if chat.type in ['group', 'supergroup'] else False
534
+
535
+ context_mode = data_manager.get_context_mode()
536
+ hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
537
+
538
+ if chat.type in ['group', 'supergroup']:
539
+ help_text = (
540
+ f"🤖 **دستورات ربات در گروه:**\n\n"
541
+ f"🟢 `/start` - شروع کار با ربات در گروه\n"
542
+ f"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
543
+ f"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
544
+ f"🟢 `/help` - نمایش این پیام راهنما\n\n"
545
+ f"📝 **نکته:** ربات به سه صورت کار می‌کند:\n"
546
+ f"1. پاسخ به پیام‌های مستقیم\n"
547
+ f"2. پاسخ وقتی منشن می‌شوید\n"
548
+ f"3. پاسخ به ریپلای‌ها (روی پیام‌های من یا دیگران)\n\n"
549
+ f"**حالت فعلی:** {context_mode}"
550
+ )
551
+
552
+ if context_mode == 'hybrid':
553
+ help_text += f" ({hybrid_mode})\n"
554
+ if hybrid_mode == 'advanced':
555
+ help_text += (
556
+ "• **Hybrid پیشرفته**: هر کاربر تاریخچه شخصی + گروهی + آگاهی از دیگران\n"
557
+ "• ربات شما را جداگانه می‌شناسد و پاسخ‌های شخصی‌سازی شده می‌دهد\n"
558
+ )
559
+ else:
560
+ help_text += (
561
+ "• **Hybrid ساده**: تاریخچه شخصی + گروهی\n"
562
+ "• پاسخ‌ها بر اساس ترکیب تاریخچه شما و گروه\n"
563
+ )
564
+ elif context_mode == 'group_shared':
565
+ help_text += "\n• **مشترک گروهی**: همه کاربران تاریخچه مشترک دارند\n"
566
+ else:
567
+ help_text += "\n• **جداگانه**: هر کاربر تاریخچه جداگانه خود را دارد\n"
568
+
569
+ help_text += "\n💡 **مزایای حالت Hybrid پیشرفته:**\n"
570
+ help_text += "✅ ربات تاریخچه شخصی شما را به خاطر می‌سپارد\n"
571
+ help_text += "✅ ربات از مکالمات گروه نیز آگاه است\n"
572
+ help_text += "✅ آگاهی از کاربران دیگر فعال در گروه\n"
573
+ help_text += "✅ پاسخ‌های دقیق‌تر و شخصی‌سازی شده\n"
574
+ help_text += "✅ برای بحث‌های گروهی پیچیده ایده‌آل است"
575
+
576
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
577
+
578
+ if is_admin_bot or is_admin_group:
579
+ help_text += (
580
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
581
+ "• `/system clear` - حذف system instruction این گروه\n"
582
+ "• `/system_status` - نمایش وضعیت فعلی\n"
583
+ "• `/system_help` - نمایش راهنما\n\n"
584
+ )
585
+
586
+ if is_admin_bot:
587
+ help_text += "🎯 **دسترسی ادمین ربات:**\n"
588
+ help_text += "- می‌توانید Global System Instruction را مدیریت کنید\n"
589
+ help_text += "- برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n"
590
+ help_text += "- می‌توانید حالت context را با `/set_context_mode` تغییر دهید\n"
591
+ help_text += "- می‌توانید حالت Hybrid را با `/set_hybrid_mode` تنظیم کنید\n"
592
+ else:
593
+ help_text += "🎯 **دسترسی ادمین گروه:**\n"
594
+ help_text += "- فقط می‌توانید system instruction همین گروه را مدیریت کنید\n"
595
+ else:
596
+ help_text += (
597
+ "این دستورات فقط برای ادمین‌های گروه در دسترس است.\n"
598
+ "برای تنظیم شخصیت ربات در این گروه، با ادمین‌های گروه تماس بگیرید."
599
+ )
600
+
601
+ else:
602
+ help_text = (
603
+ "🤖 **دستورات ربات:**\n\n"
604
+ "🟢 `/start` - شروع کار با ربات\n"
605
+ "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
606
+ "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
607
+ "🟢 `/help` - نمایش این پیام راهنما\n\n"
608
+ "📝 **نکته:** ربات تاریخچه مکالمه شما را تا 16384 توکن ذخیره می‌کند. "
609
+ "می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n"
610
+ "برای شروع مکالمه جدید از دستور /clear استفاده کنید."
611
+ )
612
+
613
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
614
+
615
+ if is_admin_bot:
616
+ help_text += (
617
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
618
+ "• `/system_help` - نمایش راهنما\n\n"
619
+ "🎯 **دسترسی ادمین ربات:**\n"
620
+ "- می‌توانید Global System Instruction را مدیریت کنید\n"
621
+ "- از پنل ادمین برای تنظیمات پیشرفته استفاده کنید"
622
+ )
623
+ else:
624
+ help_text += "این دستورات فقط برای ادمین‌های ربات در دسترس است."
625
+
626
+ await update.message.reply_text(help_text, parse_mode='Markdown')
627
+
628
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
629
+ """هندلر اصلی برای پیام‌ها"""
630
+ if not update.message:
631
+ return
632
+
633
+ user_id = update.effective_user.id
634
+ chat = update.effective_chat
635
+
636
+ if data_manager.is_user_banned(user_id):
637
+ logger.info(f"Banned user {user_id} tried to send a message.")
638
+ return
639
+
640
+ admin_ids = admin_panel.get_admin_ids()
641
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
642
+ await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
643
+ return
644
+
645
+ message_text = update.message.text or update.message.caption or ""
646
+ if not message_text:
647
+ return
648
+
649
+ if data_manager.contains_blocked_words(message_text):
650
+ logger.info(f"User {user_id} sent a message with a blocked word.")
651
+ return
652
+
653
+ if chat.type in ['group', 'supergroup']:
654
+ task_key = (chat.id, user_id)
655
+
656
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
657
+ user_group_tasks[task_key].cancel()
658
+ logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")
659
+
660
+ task = asyncio.create_task(_process_group_request(update, context))
661
+ user_group_tasks[task_key] = task
662
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
663
+ else:
664
+ if user_id in user_tasks and not user_tasks[user_id].done():
665
+ user_tasks[user_id].cancel()
666
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
667
+
668
+ task = asyncio.create_task(_process_user_request(update, context))
669
+ user_tasks[user_id] = task
670
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
671
+
672
+ async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
673
+ """هندلر برای زمانی که ربات در گروه منشن می‌شود"""
674
+ if not update.message:
675
+ return
676
+
677
+ if update.effective_chat.type in ['group', 'supergroup']:
678
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
679
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
680
+
681
+ message_text = update.message.text or ""
682
+ bot_username = context.bot.username
683
+
684
+ if bot_username and f"@{bot_username}" in message_text:
685
+ message_text = message_text.replace(f"@{bot_username}", "").strip()
686
+
687
+ if message_text:
688
+ user_name = update.effective_user.first_name
689
+
690
+ if reply_info and reply_info.get('replied_text'):
691
+ formatted_message = format_reply_message(
692
+ message_text,
693
+ reply_info.get('replied_user_name', 'Unknown'),
694
+ reply_info.get('replied_text'),
695
+ reply_info.get('is_reply_to_bot', False),
696
+ user_name
697
+ )
698
+ else:
699
+ formatted_message = message_text
700
+
701
+ task_key = (update.effective_chat.id, update.effective_user.id)
702
+
703
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
704
+ user_group_tasks[task_key].cancel()
705
+ logger.info(f"Cancelled previous task for group {update.effective_chat.id}, user {update.effective_user.id} to start a new one.")
706
+
707
+ task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info))
708
+ user_group_tasks[task_key] = task
709
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, update.effective_chat.id, update.effective_user.id))
710
+ else:
711
+ await update.message.reply_text("بله؟ چگونه می‌توانم کمک کنم؟")
712
+
713
+ async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
714
+ """هندلر مخصوص ریپلای‌ها"""
715
+ if not update.message:
716
+ return
717
+
718
+ message_text = update.message.text or update.message.caption or ""
719
+ if not message_text:
720
+ return
721
+
722
+ user_id = update.effective_user.id
723
+ chat = update.effective_chat
724
+
725
+ if data_manager.is_user_banned(user_id):
726
+ return
727
+
728
+ admin_ids = admin_panel.get_admin_ids()
729
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
730
+ return
731
+
732
+ if data_manager.contains_blocked_words(message_text):
733
+ return
734
+
735
+ if chat.type in ['group', 'supergroup']:
736
+ task_key = (chat.id, user_id)
737
+
738
+ if task_key in user_group_tasks and not user_group_tasks[task_key].done():
739
+ user_group_tasks[task_key].cancel()
740
+ logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")
741
+
742
+ task = asyncio.create_task(_process_group_request(update, context))
743
+ user_group_tasks[task_key] = task
744
+ task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
745
+ else:
746
+ if user_id in user_tasks and not user_tasks[user_id].done():
747
+ user_tasks[user_id].cancel()
748
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
749
+
750
+ task = asyncio.create_task(_process_user_request(update, context))
751
+ user_tasks[user_id] = task
752
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
753
+
754
+ def main() -> None:
755
+
756
+ flask_thread = threading.Thread(target=run_flask, daemon=True)
757
+ flask_thread.start()
758
+ logger.info(f"Flask server started on port {os.environ.get('FLASK_PORT', 5000)}")
759
+
760
+ token = os.environ.get("BOT_TOKEN")
761
+ if not token:
762
+ logger.error("BOT_TOKEN not set in environment variables!")
763
+ return
764
+
765
+ application = (
766
+ Application.builder()
767
+ .token(token)
768
+ .concurrent_updates(True)
769
+ .build()
770
+ )
771
+
772
+ # هندلرهای کاربران
773
+ application.add_handler(CommandHandler("start", start))
774
+ application.add_handler(CommandHandler("clear", clear_chat))
775
+ application.add_handler(CommandHandler("context", context_info))
776
+ application.add_handler(CommandHandler("help", help_command))
777
+
778
+ # هندلر برای ریپلای‌ها
779
+ application.add_handler(MessageHandler(
780
+ filters.TEXT & filters.REPLY,
781
+ reply_handler
782
+ ))
783
+
784
+ # هندلر برای منشن در گروه
785
+ application.add_handler(MessageHandler(
786
+ filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS,
787
+ mention_handler
788
+ ))
789
+
790
+ # هندلر برای پیام‌های متنی معمولی
791
+ application.add_handler(MessageHandler(
792
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY,
793
+ handle_message
794
+ ))
795
+
796
+ # هندلر برای پیام‌های متنی در گروه
797
+ application.add_handler(MessageHandler(
798
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS &
799
+ ~filters.Entity("mention") & ~filters.REPLY,
800
+ handle_message
801
+ ))
802
+
803
+ # راه‌اندازی و ثبت هندلرهای پنل ادمین
804
+ admin_panel.setup_admin_handlers(application)
805
+
806
+ # راه‌اندازی هندلرهای system instruction
807
+ system_instruction_handlers.setup_system_instruction_handlers(application)
808
+
809
+ # تنظیم هندلر خطا
810
+ async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
811
+ logger.error(f"Exception while handling an update: {context.error}")
812
+ try:
813
+ if update and update.message:
814
+ await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.")
815
+ except:
816
+ pass
817
+
818
+ application.add_error_handler(error_handler)
819
+
820
+ # --- بخش حیاتی: راه‌اندازی وب‌سرویس ---
821
+ port = int(os.environ.get("PORT", 8443))
822
+ webhook_url = os.environ.get("RENDER_EXTERNAL_URL")
823
+
824
+ logger.info(f"Starting bot with port={port}, webhook_url={webhook_url}")
825
+
826
+ if webhook_url:
827
+ # استفاده از webhook در Render
828
+ webhook_url = webhook_url.rstrip('/') + "/webhook"
829
+ logger.info(f"Using webhook: {webhook_url}")
830
+
831
+ # شروع وب‌سرویس با webhook
832
+ application.run_webhook(
833
+ listen="0.0.0.0",
834
+ port=port,
835
+ url_path="webhook",
836
+ webhook_url=webhook_url,
837
+ secret_token=os.environ.get("WEBHOOK_SECRET", None)
838
+ )
839
+ else:
840
+ # استفاده از polling (برای توسعه محلی)
841
+ logger.info("Using polling mode (local development)")
842
+ application.run_polling()
843
+
844
+ if __name__ == "__main__":
845
+ main()
BOT/render-main/FIXES/render.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ - type: web
3
+ name: telegram-ai-bot
4
+ env: python
5
+ buildCommand: pip install -r requirements.txt
6
+ startCommand: python main.py
7
+ plan: free # می‌توانید از پلن رایگان استفاده کنید
8
+ envVars:
9
+ - key: BOT_TOKEN
10
+ sync: false # مقدار این متغیر را باید در داشبورد Render وارد کنید
11
+ - key: HF_TOKEN
12
+ sync: false # مقدار این متغیر را نیز در داشبورد Render وارد کنید
BOT/render-main/FIXES/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-telegram-bot[job-queue]
2
+ python-telegram-bot[webhooks]
3
+ openai
4
+ requests
5
+ huggingface_hub
6
+ aiohttp
7
+ httpx[http2]
8
+ matplotlib
9
+ pandas
10
+ psutil
11
+ tiktoken
BOT/render-main/FIXES/restart.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # restart.py
2
+ import os
3
+ import sys
4
+ import subprocess
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def restart_bot():
10
+ """ریستارت کردن ربات"""
11
+ logger.info("Restarting bot...")
12
+ python = sys.executable
13
+ os.execl(python, python, *sys.argv)
BOT/render-main/FIXES/smart_context.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import asyncio
7
+ import hashlib
8
+ import numpy as np
9
+ from datetime import datetime, timedelta
10
+ from typing import List, Dict, Any, Optional, Tuple, Set
11
+ from collections import defaultdict, deque
12
+ import pickle
13
+ from dataclasses import dataclass, field
14
+ from enum import Enum
15
+ import re
16
+ import heapq
17
+
18
+ # برای embeddings (در صورت نبود کتابخانه، از روش جایگزین استفاده می‌شود)
19
+ try:
20
+ from sentence_transformers import SentenceTransformer
21
+ HAS_SBERT = True
22
+ except ImportError:
23
+ HAS_SBERT = False
24
+ from sklearn.feature_extraction.text import TfidfVectorizer
25
+ import warnings
26
+ warnings.filterwarnings("ignore")
27
+
28
+ # وارد کردن مدیر داده‌ها
29
+ import data_manager
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # ==================== ENUMS و DataClasses ====================
34
+
35
+ class MemoryPriority(Enum):
36
+ """اولویت حافظه"""
37
+ LOW = 1
38
+ MEDIUM = 2
39
+ HIGH = 3
40
+ CRITICAL = 4
41
+
42
+ class MessageType(Enum):
43
+ """نوع پیام"""
44
+ FACT = "fact"
45
+ PREFERENCE = "preference"
46
+ EMOTION = "emotion"
47
+ QUESTION = "question"
48
+ ANSWER = "answer"
49
+ DECISION = "decision"
50
+ ACTION = "action"
51
+ CHITCHAT = "chitchat"
52
+
53
+ class EmotionType(Enum):
54
+ """نوع احساس"""
55
+ POSITIVE = "positive"
56
+ NEUTRAL = "neutral"
57
+ NEGATIVE = "negative"
58
+ EXCITED = "excited"
59
+ ANGRY = "angry"
60
+ CONFUSED = "confused"
61
+
62
+ @dataclass
63
+ class MessageNode:
64
+ """گره پیام در گراف حافظه"""
65
+ id: str
66
+ content: str
67
+ role: str
68
+ timestamp: datetime
69
+ message_type: MessageType
70
+ importance_score: float = 0.5
71
+ emotion_score: Dict[EmotionType, float] = field(default_factory=dict)
72
+ tokens: int = 0
73
+ embeddings: Optional[np.ndarray] = None
74
+ metadata: Dict[str, Any] = field(default_factory=dict)
75
+
76
+ def __hash__(self):
77
+ return hash(self.id)
78
+
79
+ def __eq__(self, other):
80
+ return self.id == other.id
81
+
82
+ @dataclass
83
+ class MemoryConnection:
84
+ """اتصال بین پیام‌ها در گراف حافظه"""
85
+ source_id: str
86
+ target_id: str
87
+ connection_type: str # 'semantic', 'temporal', 'causal', 'contextual'
88
+ strength: float = 1.0
89
+ metadata: Dict[str, Any] = field(default_factory=dict)
90
+
91
+ @dataclass
92
+ class UserProfile:
93
+ """پروفایل کاربر"""
94
+ user_id: int
95
+ personality_traits: Dict[str, float] = field(default_factory=dict)
96
+ interests: Set[str] = field(default_factory=set)
97
+ preferences: Dict[str, Any] = field(default_factory=dict)
98
+ conversation_style: str = "balanced"
99
+ knowledge_level: Dict[str, float] = field(default_factory=dict)
100
+ emotional_patterns: Dict[str, List[float]] = field(default_factory=dict)
101
+ learning_style: Optional[str] = None
102
+
103
+ def update_from_message(self, message: str, analysis: Dict[str, Any]):
104
+ """به‌روزرسانی پروفایل بر اساس پیام جدید"""
105
+ if 'personality_clues' in analysis:
106
+ for trait, score in analysis['personality_clues'].items():
107
+ current = self.personality_traits.get(trait, 0.5)
108
+ self.personality_traits[trait] = 0.7 * current + 0.3 * score
109
+
110
+ if 'interests' in analysis:
111
+ self.interests.update(analysis['interests'])
112
+
113
+ if 'preferences' in analysis:
114
+ self.preferences.update(analysis['preferences'])
115
+
116
+ # ==================== کلاس Embedding Manager ====================
117
+
118
+ class EmbeddingManager:
119
+ """مدیریت embeddings برای جستجوی معنایی"""
120
+
121
+ def __init__(self, model_name: str = None):
122
+ self.model = None
123
+ self.vectorizer = None
124
+ self.use_sbert = HAS_SBERT
125
+
126
+ if self.use_sbert:
127
+ try:
128
+ self.model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
129
+ logger.info("Loaded multilingual sentence transformer")
130
+ except Exception as e:
131
+ logger.warning(f"Failed to load sentence transformer: {e}")
132
+ self.use_sbert = False
133
+
134
+ if not self.use_sbert:
135
+ try:
136
+ from sklearn.feature_extraction.text import TfidfVectorizer
137
+ self.vectorizer = TfidfVectorizer(max_features=1000)
138
+ logger.info("Using TF-IDF for embeddings")
139
+ except ImportError:
140
+ logger.warning("scikit-learn not available, using simple word vectors")
141
+ self.vectorizer = None
142
+
143
+ def get_embedding(self, text: str) -> np.ndarray:
144
+ """دریافت embedding برای متن"""
145
+ if self.use_sbert and self.model:
146
+ return self.model.encode([text])[0]
147
+ elif self.vectorizer:
148
+ # برای TF-IDF نیاز به fit داریم، فقط بردار ساده برمی‌گردانیم
149
+ words = text.lower().split()
150
+ unique_words = list(set(words))
151
+ embedding = np.zeros(100)
152
+ for i, word in enumerate(unique_words[:100]):
153
+ embedding[i] = hash(word) % 100 / 100.0
154
+ return embedding
155
+ else:
156
+ # روش ساده‌تر
157
+ text_lower = text.lower()
158
+ embedding = np.zeros(50)
159
+ # وزن بر اساس طول و محتوا
160
+ embedding[0] = len(text) / 1000.0
161
+ embedding[1] = text.count('؟') / 5.0
162
+ embedding[2] = text.count('!') / 5.0
163
+ # ویژگی‌های ساده
164
+ embedding[3] = 1.0 if 'چه' in text_lower else 0.0
165
+ embedding[4] = 1.0 if 'چرا' in text_lower else 0.0
166
+ embedding[5] = 1.0 if 'چگونه' in text_lower else 0.0
167
+ return embedding
168
+
169
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
170
+ """محاسبه cosine similarity"""
171
+ norm1 = np.linalg.norm(vec1)
172
+ norm2 = np.linalg.norm(vec2)
173
+ if norm1 == 0 or norm2 == 0:
174
+ return 0.0
175
+ return np.dot(vec1, vec2) / (norm1 * norm2)
176
+
177
+ # ==================== کلاس Memory Graph ====================
178
+
179
+ class MemoryGraph:
180
+ """گراف حافظه برای ذخیره و بازیابی ارتباطات"""
181
+
182
+ def __init__(self):
183
+ self.nodes: Dict[str, MessageNode] = {}
184
+ self.connections: List[MemoryConnection] = []
185
+ self.adjacency: Dict[str, List[MemoryConnection]] = defaultdict(list)
186
+ self.topic_clusters: Dict[str, Set[str]] = defaultdict(set)
187
+ self.time_index: List[Tuple[datetime, str]] = []
188
+
189
+ def add_node(self, node: MessageNode):
190
+ """افزودن گره جدید"""
191
+ self.nodes[node.id] = node
192
+ self.time_index.append((node.timestamp, node.id))
193
+ self.time_index.sort(key=lambda x: x[0])
194
+
195
+ def add_connection(self, connection: MemoryConnection):
196
+ """افزودن اتصال جدید"""
197
+ self.connections.append(connection)
198
+ self.adjacency[connection.source_id].append(connection)
199
+
200
+ def find_similar_nodes(self, query_embedding: np.ndarray,
201
+ threshold: float = 0.7,
202
+ max_results: int = 5) -> List[Tuple[str, float]]:
203
+ """یافتن گره‌های مشابه"""
204
+ similarities = []
205
+ for node_id, node in self.nodes.items():
206
+ if node.embeddings is not None:
207
+ similarity = self._cosine_similarity(query_embedding, node.embeddings)
208
+ if similarity > threshold:
209
+ similarities.append((node_id, similarity))
210
+
211
+ similarities.sort(key=lambda x: x[1], reverse=True)
212
+ return similarities[:max_results]
213
+
214
+ def get_temporal_neighbors(self, node_id: str,
215
+ time_window: timedelta = timedelta(hours=24)) -> List[str]:
216
+ """یافتن همسایه‌های زمانی"""
217
+ if node_id not in self.nodes:
218
+ return []
219
+
220
+ node_time = self.nodes[node_id].timestamp
221
+ neighbors = []
222
+
223
+ for timestamp, nid in self.time_index:
224
+ if nid != node_id and abs(timestamp - node_time) <= time_window:
225
+ neighbors.append(nid)
226
+
227
+ return neighbors
228
+
229
+ def get_semantic_cluster(self, node_id: str, min_similarity: float = 0.6) -> Set[str]:
230
+ """دریافت خوشه معنایی یک گره"""
231
+ cluster = {node_id}
232
+
233
+ if node_id not in self.nodes or self.nodes[node_id].embeddings is None:
234
+ return cluster
235
+
236
+ query_embedding = self.nodes[node_id].embeddings
237
+
238
+ for other_id, other_node in self.nodes.items():
239
+ if other_id != node_id and other_node.embeddings is not None:
240
+ similarity = self._cosine_similarity(query_embedding, other_node.embeddings)
241
+ if similarity > min_similarity:
242
+ cluster.add(other_id)
243
+
244
+ return cluster
245
+
246
+ def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
247
+ """محاسبه cosine similarity"""
248
+ norm1 = np.linalg.norm(vec1)
249
+ norm2 = np.linalg.norm(vec2)
250
+ if norm1 == 0 or norm2 == 0:
251
+ return 0.0
252
+ return np.dot(vec1, vec2) / (norm1 * norm2)
253
+
254
+ # ==================== کلاس Context Analyzer ====================
255
+
256
+ class ContextAnalyzer:
257
+ """آنالیزور هوشمند context"""
258
+
259
+ def __init__(self):
260
+ self.keyword_patterns = {
261
+ 'name': [r'نام\s+من\s+(.*?)(?:است|می‌باشد)', r'اسم\s+من\s+(.*?)'],
262
+ 'age': [r'سن\s+من\s+(\d+)', r'(\d+)\s+سالمه'],
263
+ 'location': [r'اهل\s+(.*?)\s+هستم', r'د��\s+(.*?)\s+زندگی می‌کنم'],
264
+ 'preference': [r'دوست\s+دارم\s+(.*?)', r'علاقه\s+دارم\s+(.*?)', r'ترجیح\s+می‌دهم\s+(.*?)'],
265
+ 'dislike': [r'دوست\s+ندارم\s+(.*?)', r'مخالف\s+(.*?)\s+هستم'],
266
+ 'goal': [r'می‌خواهم\s+(.*?)', r'هدف\s+من\s+(.*?)\s+است'],
267
+ 'question': [r'(چرا|چگونه|چه|کجا|کی|آیا)\s+.*?\?'],
268
+ 'decision': [r'تصمیم\s+گرفتم\s+(.*?)', r'قصد\s+دارم\s+(.*?)'],
269
+ 'emotion': [r'احساس\s+(.*?)\s+دارم', r'(خوشحالم|ناراحتم|عصبانی‌ام|خستهام)']
270
+ }
271
+
272
+ self.emotion_keywords = {
273
+ EmotionType.POSITIVE: ['خوب', 'عالی', 'خوشحال', 'عالی', 'ممنون', 'مرسی', 'دوست دارم', 'عالیه'],
274
+ EmotionType.NEGATIVE: ['بد', 'بدی', 'ناراحت', 'غمگین', 'عصبانی', 'مشکل', 'خطا', 'اشتباه'],
275
+ EmotionType.EXCITED: ['هیجان‌زده', 'هیجان', 'جالب', 'شگفت‌انگیز', 'عالی', 'وای'],
276
+ EmotionType.ANGRY: ['عصبانی', 'خشمگین', 'ناراحت', 'اعصاب', 'دیوانه'],
277
+ EmotionType.CONFUSED: ['سردرگم', 'گیج', 'نمی‌فهمم', 'مشکل دارم', 'کمک']
278
+ }
279
+
280
+ def analyze_message(self, text: str, role: str) -> Dict[str, Any]:
281
+ """آنالیز پیام و استخراج اطلاعات"""
282
+ analysis = {
283
+ 'type': self._detect_message_type(text, role),
284
+ 'entities': self._extract_entities(text),
285
+ 'keywords': self._extract_keywords(text),
286
+ 'emotion': self._analyze_emotion(text),
287
+ 'importance': self._calculate_importance(text, role),
288
+ 'topics': self._extract_topics(text),
289
+ 'intent': self._detect_intent(text),
290
+ 'complexity': self._calculate_complexity(text),
291
+ 'has_personal_info': False,
292
+ 'personal_info': {}
293
+ }
294
+
295
+ # استخراج اطلاعات شخصی
296
+ personal_info = self._extract_personal_info(text)
297
+ if personal_info:
298
+ analysis['has_personal_info'] = True
299
+ analysis['personal_info'] = personal_info
300
+
301
+ # استخراج ترجیحات
302
+ preferences = self._extract_preferences(text)
303
+ if preferences:
304
+ analysis['preferences'] = preferences
305
+
306
+ return analysis
307
+
308
+ def _detect_message_type(self, text: str, role: str) -> MessageType:
309
+ """تشخیص نوع پیام"""
310
+ text_lower = text.lower()
311
+
312
+ if role == 'user':
313
+ if any(q in text_lower for q in ['؟', '?', 'چرا', 'چگونه', 'چه', 'کجا']):
314
+ return MessageType.QUESTION
315
+ elif any(e in text_lower for e in ['احساس', 'حالم', 'خوشحالم', 'ناراحتم']):
316
+ return MessageType.EMOTION
317
+ elif any(d in text_lower for d in ['تصمیم', 'قصد', 'می‌خواهم']):
318
+ return MessageType.DECISION
319
+ elif any(p in text_lower for p in ['دوست دارم', 'علاقه', 'ترجیح']):
320
+ return MessageType.PREFERENCE
321
+ else:
322
+ return MessageType.FACT
323
+ else:
324
+ if '؟' in text_lower:
325
+ return MessageType.QUESTION
326
+ elif any(a in text_lower for a in ['پاسخ', 'جواب', 'راه حل']):
327
+ return MessageType.ANSWER
328
+ else:
329
+ return MessageType.FACT
330
+
331
+ def _extract_entities(self, text: str) -> List[str]:
332
+ """استخراج موجودیت‌ها"""
333
+ entities = []
334
+ # الگوهای ساده برای اسامی
335
+ name_patterns = [
336
+ r'نام\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
337
+ r'اسم\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
338
+ ]
339
+
340
+ for pattern in name_patterns:
341
+ matches = re.findall(pattern, text)
342
+ entities.extend(matches)
343
+
344
+ return entities
345
+
346
+ def _extract_keywords(self, text: str) -> List[str]:
347
+ """استخراج کلمات کلیدی"""
348
+ # حذف کلمات توقف فارسی
349
+ stopwords = {'و', 'در', 'با', 'به', 'از', 'که', 'این', 'آن', 'را', 'برای', 'اما', 'یا'}
350
+ words = re.findall(r'\b[\wآ-ی]+\b', text.lower())
351
+ keywords = [w for w in words if w not in stopwords and len(w) > 2]
352
+
353
+ return list(set(keywords))[:10]
354
+
355
+ def _analyze_emotion(self, text: str) -> Dict[EmotionType, float]:
356
+ """تحلیل احساسات متن"""
357
+ emotion_scores = {e: 0.0 for e in EmotionType}
358
+ text_lower = text.lower()
359
+
360
+ for emotion_type, keywords in self.emotion_keywords.items():
361
+ score = 0.0
362
+ for keyword in keywords:
363
+ if keyword in text_lower:
364
+ score += 1.0
365
+ emotion_scores[emotion_type] = min(score / 3.0, 1.0)
366
+
367
+ # تشخیص احساس کلی
368
+ if sum(emotion_scores.values()) == 0:
369
+ emotion_scores[EmotionType.NEUTRAL] = 1.0
370
+
371
+ return emotion_scores
372
+
373
+ def _calculate_importance(self, text: str, role: str) -> float:
374
+ """محاسبه اهمیت پیام"""
375
+ score = 0.0
376
+
377
+ # امتیاز بر اساس نقش
378
+ if role == 'user':
379
+ score += 0.3
380
+
381
+ # امتیاز بر اساس طول
382
+ length = len(text)
383
+ if length > 200:
384
+ score += 0.3
385
+ elif length > 100:
386
+ score += 0.2
387
+ elif length > 50:
388
+ score += 0.1
389
+
390
+ # امتیاز بر اساس سوال بودن
391
+ if '؟' in text or '?' in text:
392
+ score += 0.2
393
+
394
+ # امتیاز بر اساس کلمات کلیدی مهم
395
+ important_words = ['مهم', 'لطفا', 'فوری', 'ضروری', 'لازم', 'حتما']
396
+ for word in important_words:
397
+ if word in text.lower():
398
+ score += 0.2
399
+ break
400
+
401
+ # امتیاز بر اساس اطلاعات شخصی
402
+ if any(pattern in text for pattern in ['نام من', 'سن من', 'اهل']):
403
+ score += 0.3
404
+
405
+ return min(score, 1.0)
406
+
407
+ def _extract_topics(self, text: str) -> List[str]:
408
+ """استخراج موضوعات"""
409
+ topics = []
410
+
411
+ # دسته‌بندی موضوعات بر اساس کلمات کلیدی
412
+ topic_categories = {
413
+ 'ورزش': ['فوتبال', 'ورزش', 'تمرین', 'مسابقه', 'تیم'],
414
+ 'تکنولوژی': ['کامپیوتر', 'برنامه', 'کد', 'پایتون', 'هوش مصنوعی'],
415
+ 'هنر': ['فیلم', 'موسیقی', 'نقاشی', 'کتاب', 'خواننده'],
416
+ 'علم': ['تحقیق', 'دانش', 'کشف', 'آزمایش', 'نظریه'],
417
+ 'غذا': ['غذا', 'رستوران', 'پخت', 'خوراک', 'ناهار'],
418
+ 'سفر': ['سفر', 'مسافرت', 'کشور', 'شهر', 'هتل'],
419
+ 'سلامتی': ['سلامت', 'بیماری', 'درمان', 'دکتر', 'بیمارستان'],
420
+ 'کاری': ['کار', 'شغل', 'شرکت', 'مصاحبه', 'پروژه'],
421
+ 'تحصیل': ['درس', 'دانشگاه', 'مدرسه', 'آموزش', 'یادگیری'],
422
+ }
423
+
424
+ text_lower = text.lower()
425
+ for topic, keywords in topic_categories.items():
426
+ if any(keyword in text_lower for keyword in keywords):
427
+ topics.append(topic)
428
+
429
+ return topics[:3]
430
+
431
+ def _detect_intent(self, text: str) -> str:
432
+ """تشخیص قصد کاربر"""
433
+ text_lower = text.lower()
434
+
435
+ if any(q in text_lower for q in ['چطور', 'چگونه', 'راهنمایی']):
436
+ return 'guidance'
437
+ elif any(q in text_lower for q in ['چه', 'اطلاعات', 'معرفی']):
438
+ return 'information'
439
+ elif any(q in text_lower for q in ['چرا', 'دلیل', 'علت']):
440
+ return 'explanation'
441
+ elif any(q in text_lower for q in ['کمک', 'راه حل', 'مشکل']):
442
+ return 'help'
443
+ elif any(q in text_lower for q in ['توصیه', 'پیشنهاد', 'نظر']):
444
+ return 'advice'
445
+ elif any(q in text_lower for q in ['بحث', 'بحث کنیم', 'نظرت']):
446
+ return 'discussion'
447
+ else:
448
+ return 'general'
449
+
450
+ def _calculate_complexity(self, text: str) -> float:
451
+ """محاسبه پیچیدگی متن"""
452
+ # میانگین طول کلمات
453
+ words = text.split()
454
+ if not words:
455
+ return 0.0
456
+
457
+ avg_word_length = sum(len(w) for w in words) / len(words)
458
+
459
+ # تعداد جملات
460
+ sentences = re.split(r'[.!?]', text)
461
+ num_sentences = max(len(sentences), 1)
462
+
463
+ # نسبت کلمات منحصر به فرد
464
+ unique_words = len(set(words))
465
+ diversity = unique_words / len(words) if words else 0
466
+
467
+ complexity = (avg_word_length / 10.0 + diversity + min(len(words) / 50.0, 1.0)) / 3.0
468
+
469
+ return min(complexity, 1.0)
470
+
471
+ def _extract_personal_info(self, text: str) -> Dict[str, Any]:
472
+ """استخراج اطلاعات شخصی"""
473
+ info = {}
474
+
475
+ for info_type, patterns in self.keyword_patterns.items():
476
+ for pattern in patterns:
477
+ matches = re.findall(pattern, text)
478
+ if matches:
479
+ info[info_type] = matches[0]
480
+ break
481
+
482
+ return info
483
+
484
+ def _extract_preferences(self, text: str) -> Dict[str, Any]:
485
+ """استخراج ترجیحات"""
486
+ preferences = {}
487
+ text_lower = text.lower()
488
+
489
+ # ترجیحات ساده
490
+ if 'دوست دارم' in text_lower:
491
+ parts = text_lower.split('دوست دارم')
492
+ if len(parts) > 1:
493
+ preference = parts[1].split('.')[0].strip()
494
+ if preference:
495
+ preferences['likes'] = preferences.get('likes', []) + [preference]
496
+
497
+ if 'دوست ندارم' in text_lower:
498
+ parts = text_lower.split('دوست ندارم')
499
+ if len(parts) > 1:
500
+ preference = parts[1].split('.')[0].strip()
501
+ if preference:
502
+ preferences['dislikes'] = preferences.get('dislikes', []) + [preference]
503
+
504
+ return preferences
505
+
506
+ # ==================== کلاس Intelligent Context Manager ====================
507
+
508
+ class IntelligentContextManager:
509
+ """مدیر هوشمند context"""
510
+
511
+ def __init__(self, user_id: int):
512
+ self.user_id = user_id
513
+ self.embedding_manager = EmbeddingManager()
514
+ self.analyzer = ContextAnalyzer()
515
+ self.memory_graph = MemoryGraph()
516
+ self.user_profile = UserProfile(user_id=user_id)
517
+
518
+ # لایه‌های حافظه
519
+ self.memory_layers = {
520
+ 'ephemeral': deque(maxlen=20), # حافظه زودگذر (چند دقیقه)
521
+ 'working': deque(maxlen=50), # حافظه فعال (مکالمه جاری)
522
+ 'recent': deque(maxlen=100), # حافظه اخیر (چند روز)
523
+ 'long_term': [], # حافظه بلندمدت (اهمیت بالا)
524
+ 'core': [] # حافظه هسته (اطلاعات حیاتی)
525
+ }
526
+
527
+ # تنظیمات
528
+ self.max_working_tokens = 512
529
+ self.max_context_tokens = 2048
530
+ self.min_importance_threshold = 0.3
531
+ self.semantic_similarity_threshold = 0.7
532
+
533
+ # آمار
534
+ self.stats = {
535
+ 'total_messages': 0,
536
+ 'compressed_messages': 0,
537
+ 'retrieved_memories': 0,
538
+ 'profile_updates': 0,
539
+ 'average_importance': 0.0
540
+ }
541
+
542
+ # بارگذاری داده‌های ذخیره شده
543
+ self._load_saved_data()
544
+
545
+ def _load_saved_data(self):
546
+ """بارگذاری داده‌های ذخیره شده"""
547
+ try:
548
+ # بارگذاری از data_manager
549
+ user_data = data_manager.DATA['users'].get(str(self.user_id), {})
550
+
551
+ if 'smart_context' in user_data:
552
+ saved_data = user_data['smart_context']
553
+
554
+ # بارگذاری پروفایل کاربر
555
+ if 'profile' in saved_data:
556
+ self.user_profile = UserProfile(**saved_data['profile'])
557
+
558
+ # بارگذاری آمار
559
+ if 'stats' in saved_data:
560
+ self.stats.update(saved_data['stats'])
561
+
562
+ logger.info(f"Loaded smart context for user {self.user_id}")
563
+ except Exception as e:
564
+ logger.error(f"Error loading saved context data: {e}")
565
+
566
+ def _save_data(self):
567
+ """ذخیره داده‌ها"""
568
+ try:
569
+ user_id_str = str(self.user_id)
570
+ if user_id_str not in data_manager.DATA['users']:
571
+ data_manager.DATA['users'][user_id_str] = {}
572
+
573
+ # ذخیره داده‌های هوشمند
574
+ data_manager.DATA['users'][user_id_str]['smart_context'] = {
575
+ 'profile': {
576
+ 'user_id': self.user_profile.user_id,
577
+ 'personality_traits': dict(self.user_profile.personality_traits),
578
+ 'interests': list(self.user_profile.interests),
579
+ 'preferences': dict(self.user_profile.preferences),
580
+ 'conversation_style': self.user_profile.conversation_style,
581
+ 'knowledge_level': dict(self.user_profile.knowledge_level),
582
+ 'emotional_patterns': dict(self.user_profile.emotional_patterns),
583
+ 'learning_style': self.user_profile.learning_style
584
+ },
585
+ 'stats': self.stats,
586
+ 'last_updated': datetime.now().isoformat()
587
+ }
588
+
589
+ data_manager.save_data()
590
+ except Exception as e:
591
+ logger.error(f"Error saving smart context data: {e}")
592
+
593
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
594
+ """پرداش کامل یک پیام جدید"""
595
+ start_time = datetime.now()
596
+
597
+ # 1. تحلیل پیام
598
+ analysis = self.analyzer.analyze_message(content, role)
599
+
600
+ # 2. ایجاد گره حافظه
601
+ message_id = self._generate_message_id(content)
602
+
603
+ # ایجاد embedding به صورت غیرهمزمان
604
+ embedding_task = asyncio.create_task(
605
+ self._get_embedding_async(content)
606
+ )
607
+
608
+ node = MessageNode(
609
+ id=message_id,
610
+ content=content,
611
+ role=role,
612
+ timestamp=datetime.now(),
613
+ message_type=analysis['type'],
614
+ importance_score=analysis['importance'],
615
+ emotion_score=analysis['emotion'],
616
+ tokens=data_manager.count_tokens(content),
617
+ embeddings=None, # موقتاً None
618
+ metadata={
619
+ 'analysis': analysis,
620
+ 'topics': analysis['topics'],
621
+ 'intent': analysis['intent'],
622
+ 'complexity': analysis['complexity']
623
+ }
624
+ )
625
+
626
+ # دریافت embedding (اگر موجود باشد)
627
+ try:
628
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
629
+ except asyncio.TimeoutError:
630
+ logger.warning(f"Embedding generation timeout for message {message_id}")
631
+ node.embeddings = self.embedding_manager.get_embedding(content)
632
+
633
+ # 3. افزودن به حافظه و گراف
634
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
635
+ await asyncio.to_thread(self.memory_graph.add_node, node)
636
+
637
+ # 4. ایجاد ارتباطات
638
+ await asyncio.to_thread(self._create_memory_connections, node)
639
+
640
+ # 5. به‌روزرسانی پروفایل کاربر
641
+ if role == 'user':
642
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
643
+
644
+ # 6. بهینه‌سازی حافظه
645
+ await asyncio.to_thread(self._optimize_memory)
646
+
647
+ # 7. به‌روزرسانی آمار
648
+ self.stats['total_messages'] += 1
649
+ self.stats['average_importance'] = (
650
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
651
+ analysis['importance']
652
+ ) / self.stats['total_messages']
653
+
654
+ # 8. ذخیره داده‌ها
655
+ await asyncio.to_thread(self._save_data)
656
+
657
+ processing_time = (datetime.now() - start_time).total_seconds()
658
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
659
+
660
+ return {
661
+ 'node_id': message_id,
662
+ 'analysis': analysis,
663
+ 'processing_time': processing_time
664
+ }
665
+
666
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
667
+ """دریافت embedding به صورت async"""
668
+ loop = asyncio.get_event_loop()
669
+ return await loop.run_in_executor(
670
+ None,
671
+ self.embedding_manager.get_embedding,
672
+ text
673
+ )
674
+
675
+ def _generate_message_id(self, content: str) -> str:
676
+ """تولید شناسه منحصر به فرد برای پیام"""
677
+ timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
678
+ content_hash = hashlib.md5(content.encode()).hexdigest()[:8]
679
+ return f"{self.user_id}_{timestamp}_{content_hash}"
680
+
681
+ def _add_to_memory_layers(self, node: MessageNode, analysis: Dict[str, Any]):
682
+ """افزودن پیام به لایه‌های حافظه مناسب"""
683
+
684
+ # همیشه به حافظه زودگذر و فعال اضافه می‌شود
685
+ self.memory_layers['ephemeral'].append(node)
686
+ self.memory_layers['working'].append(node)
687
+
688
+ # بررسی برای حافظه اخیر
689
+ if analysis['importance'] > 0.2:
690
+ self.memory_layers['recent'].append(node)
691
+
692
+ # بررسی برای حافظه بلندمدت
693
+ if analysis['importance'] > self.min_importance_threshold:
694
+ self.memory_layers['long_term'].append(node)
695
+
696
+ # بررسی برای حافظه هسته (اطلاعات حیاتی)
697
+ if analysis.get('has_personal_info', False) or analysis['importance'] > 0.8:
698
+ core_entry = {
699
+ 'node': node,
700
+ 'info': analysis.get('personal_info', {}),
701
+ 'timestamp': datetime.now()
702
+ }
703
+ self.memory_layers['core'].append(core_entry)
704
+
705
+ def _create_memory_connections(self, node: MessageNode):
706
+ """ایجاد ارتباطات حافظه برای گره جدید"""
707
+
708
+ # اگر گره‌های قبلی وجود دارند، ارتباط ایجاد کن
709
+ if len(self.memory_graph.nodes) > 1:
710
+ # ارتباط زمانی با آخرین گره
711
+ last_nodes = list(self.memory_graph.nodes.values())[-5:]
712
+ for last_node in last_nodes:
713
+ if last_node.id != node.id:
714
+ temporal_conn = MemoryConnection(
715
+ source_id=last_node.id,
716
+ target_id=node.id,
717
+ connection_type='temporal',
718
+ strength=0.8
719
+ )
720
+ self.memory_graph.add_connection(temporal_conn)
721
+
722
+ # ارتباط معنایی با گره‌های مشابه
723
+ if node.embeddings is not None:
724
+ similar_nodes = self.memory_graph.find_similar_nodes(
725
+ node.embeddings,
726
+ threshold=self.semantic_similarity_threshold
727
+ )
728
+
729
+ for similar_id, similarity in similar_nodes:
730
+ semantic_conn = MemoryConnection(
731
+ source_id=node.id,
732
+ target_id=similar_id,
733
+ connection_type='semantic',
734
+ strength=similarity
735
+ )
736
+ self.memory_graph.add_connection(semantic_conn)
737
+
738
+ def _update_user_profile(self, content: str, analysis: Dict[str, Any]):
739
+ """به‌روزرسانی پروفایل کاربر"""
740
+
741
+ # به‌روزرسانی علاقه‌مندی‌ها
742
+ if 'topics' in analysis:
743
+ for topic in analysis['topics']:
744
+ self.user_profile.interests.add(topic)
745
+
746
+ # به‌روزرسانی ترجیحات
747
+ if 'preferences' in analysis:
748
+ self.user_profile.preferences.update(analysis['preferences'])
749
+
750
+ # تشخیص سبک مکالمه
751
+ complexity = analysis.get('complexity', 0.5)
752
+ if complexity > 0.7:
753
+ self.user_profile.conversation_style = "detailed"
754
+ elif complexity < 0.3:
755
+ self.user_profile.conversation_style = "concise"
756
+
757
+ # به‌روزرسانی الگوهای احساسی
758
+ emotion = analysis.get('emotion', {})
759
+ for emotion_type, score in emotion.items():
760
+ if score > 0.3:
761
+ emotion_name = emotion_type.value if hasattr(emotion_type, 'value') else str(emotion_type)
762
+ if emotion_name not in self.user_profile.emotional_patterns:
763
+ self.user_profile.emotional_patterns[emotion_name] = []
764
+ self.user_profile.emotional_patterns[emotion_name].append(score)
765
+
766
+ self.stats['profile_updates'] += 1
767
+
768
+ def _optimize_memory(self):
769
+ """بهینه‌سازی و فشرده‌سازی حافظه"""
770
+
771
+ # فشرده‌سازی حافظه فعال اگر توکن‌ها زیاد شد
772
+ working_tokens = sum(node.tokens for node in self.memory_layers['working'])
773
+ if working_tokens > self.max_working_tokens:
774
+ self._compress_working_memory()
775
+ self.stats['compressed_messages'] += 1
776
+
777
+ # پاکسازی حافظه زودگذر قدیمی
778
+ if len(self.memory_layers['ephemeral']) > 50:
779
+ self.memory_layers['ephemeral'].clear()
780
+
781
+ # مرتب‌سازی حافظه بلندمدت بر اساس اهمیت
782
+ self.memory_layers['long_term'].sort(key=lambda x: x.importance_score, reverse=True)
783
+ if len(self.memory_layers['long_term']) > 100:
784
+ self.memory_layers['long_term'] = self.memory_layers['long_term'][:100]
785
+
786
+ def _compress_working_memory(self):
787
+ """فشرده‌سازی هوشمند حافظه فعال"""
788
+ if len(self.memory_layers['working']) <= 10:
789
+ return
790
+
791
+ working_memory = list(self.memory_layers['working'])
792
+
793
+ # 1. محاسبه امتیاز برای هر پیام
794
+ scored_messages = []
795
+ for i, node in enumerate(working_memory):
796
+ score = self._calculate_compression_score(node, i, len(working_memory))
797
+ scored_messages.append((score, node))
798
+
799
+ # 2. مرتب‌سازی بر اساس امتیاز
800
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
801
+
802
+ # 3. انتخاب پیام‌های برتر تا سقف توکن
803
+ compressed = []
804
+ total_tokens = 0
805
+
806
+ for score, node in scored_messages:
807
+ if total_tokens + node.tokens <= self.max_working_tokens:
808
+ compressed.append(node)
809
+ total_tokens += node.tokens
810
+ else:
811
+ break
812
+
813
+ # 4. مرتب‌سازی دوباره بر اساس زمان
814
+ compressed.sort(key=lambda x: x.timestamp)
815
+
816
+ # 5. جایگزینی حافظه فعال
817
+ self.memory_layers['working'] = deque(compressed, maxlen=50)
818
+
819
+ logger.info(f"Compressed working memory: {len(working_memory)} -> {len(compressed)} messages")
820
+
821
+ def _calculate_compression_score(self, node: MessageNode, index: int, total: int) -> float:
822
+ """محاسبه امتیاز فشرده‌سازی برای یک پیام"""
823
+ score = 0.0
824
+
825
+ # 1. اهمیت پیام
826
+ score += node.importance_score * 0.4
827
+
828
+ # 2. تازگی (پیام‌های جدیدتر مهم‌تر)
829
+ recency = (index / total) * 0.3
830
+ score += recency
831
+
832
+ # 3. تنوع اطلاعات (بر اساس topics)
833
+ topics = node.metadata.get('topics', [])
834
+ topic_diversity = min(len(topics) / 3.0, 0.2)
835
+ score += topic_diversity
836
+
837
+ # 4. نوع پیام
838
+ type_weights = {
839
+ MessageType.QUESTION: 0.2,
840
+ MessageType.PREFERENCE: 0.2,
841
+ MessageType.DECISION: 0.2,
842
+ MessageType.EMOTION: 0.1,
843
+ MessageType.FACT: 0.1,
844
+ MessageType.ANSWER: 0.1,
845
+ MessageType.ACTION: 0.2,
846
+ MessageType.CHITCHAT: 0.05
847
+ }
848
+ score += type_weights.get(node.message_type, 0.1)
849
+
850
+ # 5. اطلاعات شخصی
851
+ if 'has_personal_info' in node.metadata.get('analysis', {}):
852
+ if node.metadata['analysis']['has_personal_info']:
853
+ score += 0.2
854
+
855
+ return score
856
+
857
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
858
+ """بازیابی هوشمند context مرتبط با query"""
859
+ try:
860
+ if max_tokens is None:
861
+ max_tokens = self.max_context_tokens
862
+
863
+ start_time = datetime.now()
864
+
865
+ # دریافت embedding با timeout
866
+ try:
867
+ embedding_task = asyncio.create_task(
868
+ self._get_embedding_async(query)
869
+ )
870
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
871
+ except asyncio.TimeoutError:
872
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
873
+ query_embedding = self.embedding_manager.get_embedding(query)
874
+
875
+ # بازیابی از حافظه‌های مختلف به صورت موازی
876
+ tasks = []
877
+
878
+ # حافظه فعال
879
+ tasks.append(asyncio.create_task(
880
+ asyncio.to_thread(self._retrieve_from_working_memory)
881
+ ))
882
+
883
+ # حافظه معنایی
884
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
885
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
886
+
887
+ # حافظه هسته
888
+ tasks.append(asyncio.create_task(
889
+ asyncio.to_thread(self._retrieve_core_memories, query)
890
+ ))
891
+
892
+ # اجرای موازی همه tasks
893
+ results = await asyncio.gather(*tasks, return_exceptions=True)
894
+
895
+ # جمع‌آوری نتایج
896
+ retrieved_memories = []
897
+ for result in results:
898
+ if isinstance(result, Exception):
899
+ logger.error(f"Error retrieving memory: {result}")
900
+ continue
901
+ retrieved_memories.extend(result)
902
+
903
+ except Exception as e:
904
+ logger.error(f"Error in retrieve_context: {e}")
905
+ # Fallback: برگرداندن حافظه فعال
906
+ return self._retrieve_from_working_memory()
907
+
908
+ # 1. دریافت embedding برای query
909
+ query_embedding = self.embedding_manager.get_embedding(query)
910
+
911
+ # 2. بازیابی از لایه‌های مختلف حافظه
912
+ retrieved_memories = []
913
+
914
+ # از حافظه فعال (همیشه)
915
+ retrieved_memories.extend(self._retrieve_from_working_memory())
916
+
917
+ # از حافظه اخیر (بر اساس شباهت)
918
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
919
+ retrieved_memories.extend(recent_memories)
920
+
921
+ # از حافظه بلندمدت (اطلاعات مهم)
922
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
923
+ retrieved_memories.extend(long_term_memories)
924
+
925
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
926
+ core_memories = self._retrieve_core_memories(query)
927
+ retrieved_memories.extend(core_memories)
928
+
929
+ # 3. حذف تکراری‌ها و مرتب‌سازی
930
+ unique_memories = self._deduplicate_memories(retrieved_memories)
931
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
932
+
933
+ # 4. انتخاب تا سقف توکن
934
+ final_context = []
935
+ total_tokens = 0
936
+
937
+ for memory in prioritized_memories:
938
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
939
+
940
+ if total_tokens + memory_tokens <= max_tokens:
941
+ final_context.append(memory)
942
+ total_tokens += memory_tokens
943
+ else:
944
+ break
945
+
946
+ # 5. به‌روزرسانی آمار
947
+ self.stats['retrieved_memories'] += len(final_context)
948
+
949
+ retrieval_time = (datetime.now() - start_time).total_seconds()
950
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
951
+
952
+ return final_context
953
+
954
+
955
+ def _retrieve_from_working_memory(self) -> List[Dict[str, Any]]:
956
+ """بازیابی از حافظه فعال"""
957
+ memories = []
958
+
959
+ for node in list(self.memory_layers['working'])[-10:]: # 10 پیام آخر
960
+ memories.append({
961
+ 'node': node,
962
+ 'source': 'working',
963
+ 'relevance': 1.0,
964
+ 'recency': 1.0
965
+ })
966
+
967
+ return memories
968
+
969
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
970
+ layer: str) -> List[Dict[str, Any]]:
971
+ """بازیابی حافظه‌های معنایی"""
972
+ memories = []
973
+
974
+ if layer not in self.memory_layers:
975
+ return memories
976
+
977
+ layer_memories = self.memory_layers[layer]
978
+
979
+ for item in layer_memories:
980
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
981
+
982
+ if node and node.embeddings is not None:
983
+ similarity = self.embedding_manager.cosine_similarity(
984
+ query_embedding, node.embeddings
985
+ )
986
+
987
+ if similarity > self.semantic_similarity_threshold:
988
+ recency_weight = 1.0 if layer == 'working' else 0.7
989
+
990
+ memories.append({
991
+ 'node': node,
992
+ 'source': layer,
993
+ 'relevance': similarity,
994
+ 'recency': recency_weight,
995
+ 'importance': node.importance_score
996
+ })
997
+
998
+ return memories
999
+
1000
+ def _retrieve_core_memories(self, query: str) -> List[Dict[str, Any]]:
1001
+ """بازیابی حافظه‌های هسته"""
1002
+ memories = []
1003
+ query_lower = query.lower()
1004
+
1005
+ for core_entry in self.memory_layers['core']:
1006
+ node = core_entry['node']
1007
+ info = core_entry.get('info', {})
1008
+
1009
+ # بررسی تطابق با query
1010
+ relevance = 0.0
1011
+
1012
+ # تطابق با اطلاعات شخصی
1013
+ for key, value in info.items():
1014
+ if isinstance(value, str) and value.lower() in query_lower:
1015
+ relevance = 0.9
1016
+ break
1017
+
1018
+ # تطابق با محتوای پیام
1019
+ if relevance == 0.0 and node.content.lower() in query_lower:
1020
+ relevance = 0.7
1021
+
1022
+ if relevance > 0.5:
1023
+ memories.append({
1024
+ 'node': node,
1025
+ 'source': 'core',
1026
+ 'relevance': relevance,
1027
+ 'recency': 0.8,
1028
+ 'importance': 1.0,
1029
+ 'personal_info': info
1030
+ })
1031
+
1032
+ return memories
1033
+
1034
+ def _deduplicate_memories(self, memories: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1035
+ """حذف حافظه‌های تکراری"""
1036
+ seen_ids = set()
1037
+ unique_memories = []
1038
+
1039
+ for memory in memories:
1040
+ node = memory.get('node')
1041
+ if node and node.id not in seen_ids:
1042
+ seen_ids.add(node.id)
1043
+ unique_memories.append(memory)
1044
+
1045
+ return unique_memories
1046
+
1047
+ def _prioritize_memories(self, memories: List[Dict[str, Any]],
1048
+ query_embedding: np.ndarray) -> List[Dict[str, Any]]:
1049
+ """اولویت‌بندی حافظه‌های بازیابی شده"""
1050
+
1051
+ def calculate_priority(memory: Dict[str, Any]) -> float:
1052
+ """محاسبه اولویت برای یک حافظه"""
1053
+ priority = 0.0
1054
+
1055
+ # 1. ارتباط معنایی
1056
+ priority += memory.get('relevance', 0.0) * 0.4
1057
+
1058
+ # 2. تازگی
1059
+ priority += memory.get('recency', 0.0) * 0.3
1060
+
1061
+ # 3. اهمیت
1062
+ priority += memory.get('importance', 0.5) * 0.2
1063
+
1064
+ # 4. منبع (حافظه هسته اولویت بالاتری دارد)
1065
+ source = memory.get('source', '')
1066
+ if source == 'core':
1067
+ priority += 0.2
1068
+ elif source == 'long_term':
1069
+ priority += 0.1
1070
+
1071
+ return priority
1072
+
1073
+ # محاسبه اولویت و مرتب‌سازی
1074
+ prioritized = []
1075
+ for memory in memories:
1076
+ priority = calculate_priority(memory)
1077
+ prioritized.append((priority, memory))
1078
+
1079
+ prioritized.sort(key=lambda x: x[0], reverse=True)
1080
+
1081
+ return [memory for _, memory in prioritized]
1082
+
1083
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
1084
+ """تهیه context برای ارسال به API"""
1085
+
1086
+ # اگر query داریم، context هوشمند بازیابی کن
1087
+ if query:
1088
+ retrieved = await self.retrieve_context(query)
1089
+
1090
+ # تبدیل به فرمت API
1091
+ api_messages = []
1092
+
1093
+ # ابتدا اطلاعات پروفایل کاربر
1094
+ api_messages.append({
1095
+ 'role': 'system',
1096
+ 'content': f"User profile: {self._format_user_profile()}"
1097
+ })
1098
+
1099
+ # سپس حافظه‌های بازیابی شده
1100
+ for memory in retrieved:
1101
+ node = memory['node']
1102
+ api_messages.append({
1103
+ 'role': node.role,
1104
+ 'content': node.content
1105
+ })
1106
+
1107
+ return api_messages
1108
+
1109
+ else:
1110
+ # حالت ساده: فقط حافظه فعال
1111
+ api_messages = []
1112
+
1113
+ for node in list(self.memory_layers['working'])[-6:]:
1114
+ api_messages.append({
1115
+ 'role': node.role,
1116
+ 'content': node.content
1117
+ })
1118
+
1119
+ return api_messages
1120
+
1121
+ def _format_user_profile(self) -> str:
1122
+ """قالب‌بندی پروفایل کاربر برای سیستم"""
1123
+ profile_parts = []
1124
+
1125
+ if self.user_profile.interests:
1126
+ interests_str = ', '.join(list(self.user_profile.interests)[:5])
1127
+ profile_parts.append(f"Interests: {interests_str}")
1128
+
1129
+ if self.user_profile.preferences:
1130
+ prefs = list(self.user_profile.preferences.items())[:3]
1131
+ prefs_str = ', '.join(f"{k}: {v}" for k, v in prefs)
1132
+ profile_parts.append(f"Preferences: {prefs_str}")
1133
+
1134
+ if self.user_profile.conversation_style:
1135
+ profile_parts.append(f"Conversation style: {self.user_profile.conversation_style}")
1136
+
1137
+ if self.user_profile.learning_style:
1138
+ profile_parts.append(f"Learning style: {self.user_profile.learning_style}")
1139
+
1140
+ if profile_parts:
1141
+ return ' | '.join(profile_parts)
1142
+ else:
1143
+ return "New user, minimal profile information available."
1144
+
1145
+ def get_summary(self) -> Dict[str, Any]:
1146
+ """دریافت خلاصه وضعیت"""
1147
+ return {
1148
+ 'user_id': self.user_id,
1149
+ 'total_messages': self.stats['total_messages'],
1150
+ 'working_memory': len(self.memory_layers['working']),
1151
+ 'recent_memory': len(self.memory_layers['recent']),
1152
+ 'long_term_memory': len(self.memory_layers['long_term']),
1153
+ 'core_memory': len(self.memory_layers['core']),
1154
+ 'profile_interests': list(self.user_profile.interests)[:10],
1155
+ 'average_importance': self.stats['average_importance'],
1156
+ 'compression_ratio': self.stats.get('compressed_messages', 0) / max(self.stats['total_messages'], 1),
1157
+ 'retrieval_efficiency': self.stats.get('retrieved_memories', 0) / max(self.stats['total_messages'], 1)
1158
+ }
1159
+
1160
+ def clear_context(self):
1161
+ """پاک کردن context کاربر"""
1162
+ self.memory_layers['working'].clear()
1163
+ self.memory_layers['ephemeral'].clear()
1164
+
1165
+ # حافظه هسته و بلندمدت پاک نمی‌شوند
1166
+ logger.info(f"Cleared context for user {self.user_id}")
1167
+
1168
+ def export_debug_info(self) -> Dict[str, Any]:
1169
+ """دریافت اطلاعات دیباگ"""
1170
+ return {
1171
+ 'memory_graph_size': len(self.memory_graph.nodes),
1172
+ 'memory_graph_connections': len(self.memory_graph.connections),
1173
+ 'user_profile': {
1174
+ 'interests_count': len(self.user_profile.interests),
1175
+ 'preferences_count': len(self.user_profile.preferences),
1176
+ 'personality_traits': dict(self.user_profile.personality_traits)
1177
+ },
1178
+ 'layer_sizes': {k: len(v) for k, v in self.memory_layers.items()},
1179
+ 'stats': dict(self.stats)
1180
+ }
BOT/render-main/FIXES/system_instruction_handlers.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # system_instruction_handlers.py
2
+
3
+ import logging
4
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
5
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
6
+ from datetime import datetime
7
+ import data_manager
8
+ # از admin_panel وارد کردن توابع بررسی ادمین
9
+ from admin_panel import is_admin, is_super_admin, get_admin_ids
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def is_group_admin(update: Update) -> bool:
14
+ """بررسی اینکه آیا کاربر ادمین گروه است یا خیر"""
15
+ if not update.effective_chat.type in ['group', 'supergroup']:
16
+ return False
17
+
18
+ try:
19
+ chat_id = update.effective_chat.id
20
+ user_id = update.effective_user.id
21
+
22
+ # دریافت لیست ادمین‌های گروه
23
+ chat_admins = update.effective_chat.get_administrators()
24
+
25
+ # بررسی اینکه کاربر در لیست ادمین‌ها باشد
26
+ for admin in chat_admins:
27
+ if admin.user.id == user_id:
28
+ return True
29
+
30
+ # بررسی اینکه آیا کاربر ادمین ربات است
31
+ if is_admin(user_id):
32
+ return True
33
+
34
+ return False
35
+
36
+ except Exception as e:
37
+ logger.error(f"Error checking group admin status: {e}")
38
+ return False
39
+
40
+ def check_admin_permission(update: Update) -> tuple:
41
+ """
42
+ بررسی مجوز کاربر برای دسترسی به system instruction
43
+ بازگشت: (is_allowed, is_admin_bot, is_admin_group, message)
44
+ """
45
+ user_id = update.effective_user.id
46
+ chat = update.effective_chat
47
+
48
+ is_admin_bot = is_admin(user_id)
49
+ is_admin_group = is_group_admin(update)
50
+
51
+ if chat.type in ['group', 'supergroup']:
52
+ # در گروه: باید ادمین گروه یا ادمین ربات باشد
53
+ if not (is_admin_bot or is_admin_group):
54
+ return False, False, False, "⛔️ فقط ادمین‌های گروه یا ربات می‌توانند از دستورات System Instruction استفاده کنند."
55
+ else:
56
+ # در چت خصوصی: فقط ادمین ربات مجاز است
57
+ if not is_admin_bot:
58
+ return False, False, False, "⛔️ فقط ادمین‌های ربات می‌توانند از دستورات System Instruction استفاده کنند."
59
+
60
+ return True, is_admin_bot, is_admin_group, ""
61
+
62
+ def check_global_permission(update: Update) -> tuple:
63
+ """
64
+ بررسی مجوز برای دسترسی به global instruction
65
+ فقط ادمین ربات مجاز است
66
+ """
67
+ user_id = update.effective_user.id
68
+
69
+ if not is_admin(user_id):
70
+ return False, False, "⛔️ فقط ادمین‌های ربات می‌توانند به Global System Instruction دسترسی داشته باشند."
71
+
72
+ return True, True, ""
73
+
74
+ async def set_system_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
75
+ """تنظیم system instruction - فقط برای ادمین‌ها"""
76
+ # بررسی مجوز
77
+ allowed, is_admin_bot, is_admin_group, message = check_admin_permission(update)
78
+ if not allowed:
79
+ await update.message.reply_text(message)
80
+ return
81
+
82
+ user_id = update.effective_user.id
83
+ chat = update.effective_chat
84
+
85
+ if not context.args:
86
+ await update.message.reply_text(
87
+ "⚠️ لطفاً دستور system instruction را وارد کنید.\n\n"
88
+ "مثال:\n"
89
+ "/system تو یک دستیار فارسی هستی. همیشه با ادب و مفید پاسخ بده.\n\n"
90
+ "برای حذف:\n"
91
+ "/system clear\n\n"
92
+ "برای مشاهده وضعیت فعلی:\n"
93
+ "/system_status"
94
+ )
95
+ return
96
+
97
+ instruction_text = " ".join(context.args)
98
+
99
+ if instruction_text.lower() == 'clear':
100
+ # حذف system instruction
101
+ if chat.type in ['group', 'supergroup']:
102
+ # حذف برای گروه
103
+ if is_admin_bot or is_admin_group:
104
+ if data_manager.remove_group_system_instruction(chat.id):
105
+ await update.message.reply_text("✅ system instruction گروه حذف شد.")
106
+ else:
107
+ await update.message.reply_text("⚠️ system instruction گروه وجود نداشت.")
108
+ else:
109
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
110
+ else:
111
+ # حذف برای کاربر (فقط ادمین ربات)
112
+ if is_admin_bot:
113
+ if data_manager.remove_user_system_instruction(user_id):
114
+ await update.message.reply_text("✅ system instruction شخصی شما حذف شد.")
115
+ else:
116
+ await update.message.reply_text("⚠️ system instruction شخصی وجود نداشت.")
117
+ else:
118
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی را حذف کنند.")
119
+ return
120
+
121
+ # تنظیم system instruction جدید
122
+ if chat.type in ['group', 'supergroup']:
123
+ # تنظیم برای گروه
124
+ if is_admin_bot or is_admin_group:
125
+ if data_manager.set_group_system_instruction(chat.id, instruction_text, user_id):
126
+ instruction_preview = instruction_text[:500] + "..." if len(instruction_text) > 100 else instruction_text
127
+ await update.message.reply_text(
128
+ f"✅ system instruction گروه تنظیم شد:\n\n"
129
+ f"{instruction_preview}\n\n"
130
+ f"از این پس تمام پاسخ‌های ربات در این گروه با این دستور تنظیم خواهد شد."
131
+ )
132
+ else:
133
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
134
+ else:
135
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
136
+ else:
137
+ # تنظیم برای کاربر (فقط ادمین ربات)
138
+ if is_admin_bot:
139
+ if data_manager.set_user_system_instruction(user_id, instruction_text, user_id):
140
+ instruction_preview = instruction_text[:500] + "..." if len(instruction_text) > 100 else instruction_text
141
+ await update.message.reply_text(
142
+ f"✅ system instruction شخصی تنظیم شد:\n\n"
143
+ f"{instruction_preview}\n\n"
144
+ f"از این پس تمام پاسخ‌های ربات به شما با این دستور تنظیم خواهد شد."
145
+ )
146
+ else:
147
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
148
+ else:
149
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی تنظیم کنند.")
150
+
151
+ async def system_instruction_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
152
+ """نمایش وضعیت system instruction فعلی - با محدودیت دسترسی"""
153
+ user_id = update.effective_user.id
154
+ chat = update.effective_chat
155
+
156
+ is_admin_bot = is_admin(user_id)
157
+ is_admin_group = is_group_admin(update)
158
+
159
+ if chat.type in ['group', 'supergroup']:
160
+ # در گروه
161
+ if not (is_admin_bot or is_admin_group):
162
+ await update.message.reply_text(
163
+ "⚙️ **System Instruction گروه:**\n\n"
164
+ "تنظیمات System Instruction فقط برای ادمین‌های گروه قابل مشاهده است.\n"
165
+ "برای مشاهده وضعیت فعلی، با ادمین‌های گروه تماس بگیرید."
166
+ )
167
+ return
168
+
169
+ # کاربر مجاز است (ادمین ربات یا ادمین گروه)
170
+ if is_admin_bot:
171
+ # ادمین ربات: می‌تواند global و group instruction را ببیند
172
+ await show_admin_bot_status(update, context, chat.id, user_id, in_group=True)
173
+ else:
174
+ # ادمین گروه (نه ادمین ربات): فقط group instruction گروه خودش را می‌بیند
175
+ await show_group_admin_status(update, context, chat.id)
176
+ else:
177
+ # در چت خصوصی
178
+ if not is_admin_bot:
179
+ await update.message.reply_text(
180
+ "⚙️ **System Instruction:**\n\n"
181
+ "تنظیمات System Instruction فقط برای ادمین‌های ربات قابل مشاهده است."
182
+ )
183
+ return
184
+
185
+ # ادمین ربات در چت خصوصی
186
+ await show_admin_bot_status(update, context, None, user_id, in_group=False)
187
+
188
+ async def show_group_admin_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int):
189
+ """نمایش وضعیت برای ادمین گروه (نه ادمین ربات)"""
190
+ # فقط system instruction گروه را نشان بده
191
+ info = data_manager.get_system_instruction_info(chat_id=chat_id)
192
+
193
+ if info['type'] == 'group' and info['has_instruction']:
194
+ # نمایش اطلاعات group instruction
195
+ details = info['details']
196
+ instruction_preview = info['instruction'][:500] + "..." if len(info['instruction']) > 200 else info['instruction']
197
+ set_at = details.get('set_at', 'نامشخص')
198
+ set_by = details.get('set_by', 'نامشخص')
199
+ enabled = details.get('enabled', True)
200
+
201
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
202
+
203
+ status_text = (
204
+ f"👥 **System Instruction گروه شما:**\n\n"
205
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
206
+ f"📅 **زمان تنظیم:** {set_at}\n"
207
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
208
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
209
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
210
+ )
211
+
212
+ # دکمه‌های مدیریت فقط برای group instruction
213
+ keyboard = [
214
+ [
215
+ InlineKeyboardButton("✏️ ویرایش", callback_data=f"system_edit:group:{chat_id}"),
216
+ InlineKeyboardButton("🗑️ حذف", callback_data=f"system_delete:group:{chat_id}")
217
+ ]
218
+ ]
219
+
220
+ if enabled:
221
+ keyboard.append([
222
+ InlineKeyboardButton("🚫 غیرفعال", callback_data=f"system_toggle:group:{chat_id}")
223
+ ])
224
+ else:
225
+ keyboard.append([
226
+ InlineKeyboardButton("✅ فعال", callback_data=f"system_toggle:group:{chat_id}")
227
+ ])
228
+
229
+ reply_markup = InlineKeyboardMarkup(keyboard)
230
+ else:
231
+ # هیچ system instruction برای گروه تنظیم نشده
232
+ status_text = (
233
+ f"👥 **System Instruction گروه شما:**\n\n"
234
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
235
+ f"برای تنظیم از دستور زیر استفاده کنید:\n"
236
+ f"`/system [متن دستور]`\n\n"
237
+ f"در حال حاضر از تنظیمات global ربات استفاده می‌شود."
238
+ )
239
+
240
+ # فقط دکمه تنظیم
241
+ keyboard = [
242
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")]
243
+ ]
244
+ reply_markup = InlineKeyboardMarkup(keyboard)
245
+
246
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
247
+
248
+ async def show_admin_bot_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int = None, user_id: int = None, in_group: bool = False):
249
+ """نمایش وضعیت برای ادمین ربات"""
250
+ if in_group and chat_id:
251
+ # ادمین ربات در گروه
252
+ group_info = data_manager.get_system_instruction_info(chat_id=chat_id)
253
+ global_info = data_manager.get_system_instruction_info()
254
+
255
+ if group_info['type'] == 'group' and group_info['has_instruction']:
256
+ # گروه system instruction دارد
257
+ details = group_info['details']
258
+ instruction_preview = group_info['instruction'][:500] + "..." if len(group_info['instruction']) > 200 else group_info['instruction']
259
+ set_at = details.get('set_at', 'نامشخص')
260
+ set_by = details.get('set_by', 'نامشخص')
261
+ enabled = details.get('enabled', True)
262
+
263
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
264
+
265
+ status_text = (
266
+ f"👥 **System Instruction گروه:**\n\n"
267
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
268
+ f"📅 **زمان تنظیم:** {set_at}\n"
269
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
270
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
271
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
272
+ )
273
+
274
+ # دکمه‌های مدیریت برای group instruction
275
+ keyboard = [
276
+ [
277
+ InlineKeyboardButton("✏️ ویرایش گروه", callback_data=f"system_edit:group:{chat_id}"),
278
+ InlineKeyboardButton("🗑️ حذف گروه", callback_data=f"system_delete:group:{chat_id}")
279
+ ]
280
+ ]
281
+
282
+ if enabled:
283
+ keyboard.append([
284
+ InlineKeyboardButton("🚫 غیرفعال گروه", callback_data=f"system_toggle:group:{chat_id}")
285
+ ])
286
+ else:
287
+ keyboard.append([
288
+ InlineKeyboardButton("✅ فعال گروه", callback_data=f"system_toggle:group:{chat_id}")
289
+ ])
290
+
291
+ # دکمه برای مشاهده global instruction
292
+ keyboard.append([
293
+ InlineKeyboardButton("🌐 مشاهده Global", callback_data="system_show_global")
294
+ ])
295
+
296
+ reply_markup = InlineKeyboardMarkup(keyboard)
297
+ else:
298
+ # گروه system instruction ندارد
299
+ global_preview = global_info['instruction'][:500] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
300
+
301
+ status_text = (
302
+ f"👥 **System Instruction گروه:**\n\n"
303
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
304
+ f"🌐 **در حال استفاده از Global:**\n"
305
+ f"{global_preview}\n\n"
306
+ f"برای تنظیم system instruction مخصوص این گروه از دستور `/system [متن]` استفاده کنید."
307
+ )
308
+
309
+ keyboard = [
310
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")],
311
+ [InlineKeyboardButton("🌐 مشاهده کامل Global", callback_data="system_show_global")]
312
+ ]
313
+ reply_markup = InlineKeyboardMarkup(keyboard)
314
+ else:
315
+ # ادمین ربات در چت خصوصی
316
+ global_info = data_manager.get_system_instruction_info()
317
+ global_preview = global_info['instruction'][:500] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
318
+
319
+ status_text = (
320
+ f"🌐 **Global System Instruction:**\n\n"
321
+ f"📝 **محتوا:**\n{global_preview}\n\n"
322
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
323
+ )
324
+
325
+ keyboard = [
326
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
327
+ ]
328
+ reply_markup = InlineKeyboardMarkup(keyboard)
329
+
330
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
331
+
332
+ async def show_global_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
333
+ """نمایش کامل global instruction - فقط برای ادمین ربات"""
334
+ query = update.callback_query
335
+ if query:
336
+ await query.answer()
337
+ user_id = query.from_user.id
338
+ else:
339
+ user_id = update.effective_user.id
340
+
341
+ # بررسی مجوز
342
+ if not is_admin(user_id):
343
+ if query:
344
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
345
+ else:
346
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
347
+ return
348
+
349
+ global_info = data_manager.get_system_instruction_info()
350
+ global_preview = global_info['instruction']
351
+
352
+ if len(global_preview) > 1000:
353
+ global_preview = global_preview[:1000] + "...\n\n(متن کامل به دلیل طولانی بودن نمایش داده نشد)"
354
+
355
+ status_text = (
356
+ f"🌐 **Global System Instruction (کامل):**\n\n"
357
+ f"📝 **محتوا:**\n{global_preview}\n\n"
358
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
359
+ )
360
+
361
+ keyboard = [
362
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
363
+ ]
364
+ reply_markup = InlineKeyboardMarkup(keyboard)
365
+
366
+ if query:
367
+ await query.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
368
+ else:
369
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
370
+
371
+ async def system_instruction_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
372
+ """نمایش راهنمای system instruction - با محدودیت دسترسی"""
373
+ user_id = update.effective_user.id
374
+ chat = update.effective_chat
375
+
376
+ is_admin_bot = is_admin(user_id)
377
+ is_admin_group = is_group_admin(update)
378
+
379
+ if chat.type in ['group', 'supergroup']:
380
+ # در گروه
381
+ if not (is_admin_bot or is_admin_group):
382
+ await update.message.reply_text(
383
+ "🤖 **راهنمای System Instruction**\n\n"
384
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
385
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های گروه یا ربات در دسترس است.\n\n"
386
+ "برای تنظیم System Instruction در این گروه، با ادمین‌های گروه تماس بگیرید."
387
+ )
388
+ return
389
+
390
+ # کاربر مجاز است
391
+ help_text = (
392
+ "🤖 **راهنمای System Instruction**\n\n"
393
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
394
+ "📋 **دستورات:**\n"
395
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
396
+ "• `/system clear` - حذف system instruction این گروه\n"
397
+ "• `/system_status` - نمایش وضعیت فعلی\n"
398
+ "• `/system_help` - نمایش این راهنما\n\n"
399
+ )
400
+
401
+ if is_admin_bot:
402
+ help_text += (
403
+ "🎯 **دسترسی ادمین ربات:**\n"
404
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
405
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
406
+ "• برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n\n"
407
+ )
408
+ else:
409
+ help_text += (
410
+ "🎯 **دسترسی ادمین گروه:**\n"
411
+ "• فقط می‌توانید system instruction همین گروه را مشاهده و تنظیم کنید\n"
412
+ "• نمی‌توانید Global System Instruction را مشاهده کنید\n\n"
413
+ )
414
+
415
+ help_text += (
416
+ "💡 **مثال‌ها:**\n"
417
+ "• `/system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n"
418
+ "• `/system تو یک ربات جوک‌گو هستی. به هر سوالی با یک جوک پاسخ بده.`\n\n"
419
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
420
+ )
421
+ else:
422
+ # در چت خصوصی
423
+ if not is_admin_bot:
424
+ await update.message.reply_text(
425
+ "🤖 **راهنمای System Instruction**\n\n"
426
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
427
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های ربات در دسترس است."
428
+ )
429
+ return
430
+
431
+ # ادمین ربات
432
+ help_text = (
433
+ "🤖 **راهنمای System Instruction**\n\n"
434
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
435
+ "📋 **دستورات:**\n"
436
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
437
+ "• `/system_help` - نمایش این راهنما\n\n"
438
+ "🎯 **دسترسی ادمین ربات:**\n"
439
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
440
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
441
+ "• می‌توانید برای هر کاربر system instruction تنظیم کنید\n\n"
442
+ "🔧 **دستورات ادمین پنل برای System Instruction:**\n"
443
+ "• `/set_global_system [متن]` - تنظیم Global System Instruction\n"
444
+ "• `/set_group_system [آیدی گروه] [متن]` - تنظیم برای گروه\n"
445
+ "• `/set_user_system [آیدی کاربر] [متن]` - تنظیم برای کاربر\n"
446
+ "• `/list_system_instructions` - نمایش لیست تمام system instruction‌ها\n\n"
447
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
448
+ )
449
+
450
+ await update.message.reply_text(help_text, parse_mode='Markdown')
451
+
452
+ async def system_callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
453
+ """پردازش کلیک‌های دکمه‌های system instruction"""
454
+ query = update.callback_query
455
+ await query.answer()
456
+
457
+ data_parts = query.data.split(":")
458
+ action = data_parts[0]
459
+ user_id = query.from_user.id
460
+
461
+ if action == 'system_show_global':
462
+ # نمایش global instruction
463
+ await show_global_instruction(update, context)
464
+ return
465
+
466
+ if len(data_parts) < 3:
467
+ await query.message.reply_text("❌ خطا در پردازش درخواست.")
468
+ return
469
+
470
+ entity_type = data_parts[1]
471
+ entity_id = data_parts[2]
472
+
473
+ # بررسی مجوزها
474
+ if entity_type == 'global':
475
+ # فقط ادمین ربات می‌تواند global را مدیریت کند
476
+ if not is_admin(user_id):
477
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مدیریت کنند.")
478
+ return
479
+
480
+ entity_id_int = 0 # global entity
481
+ elif entity_type == 'group':
482
+ # بررسی اینکه آیا کاربر ادمین گروه یا ادمین ربات است
483
+ chat = query.message.chat
484
+ is_admin_bot = is_admin(user_id)
485
+ is_admin_group = is_group_admin(update)
486
+
487
+ if not (is_admin_bot or is_admin_group):
488
+ await query.message.reply_text("⛔️ شما مجوز لازم برای این کار را ندارید.")
489
+ return
490
+
491
+ try:
492
+ entity_id_int = int(entity_id)
493
+ except ValueError:
494
+ await query.message.reply_text("❌ شناسه گروه نامعتبر است.")
495
+ return
496
+ else: # user
497
+ # فقط ادمین ربات می‌تواند system instruction کاربران را تغییر دهد
498
+ if not is_admin(user_id):
499
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را تغییر دهند.")
500
+ return
501
+
502
+ try:
503
+ entity_id_int = int(entity_id)
504
+ except ValueError:
505
+ await query.message.reply_text("❌ شناسه کاربر نامعتبر است.")
506
+ return
507
+
508
+ if action == 'system_delete':
509
+ # حذف system instruction
510
+ if entity_type == 'global':
511
+ # حذف global (در واقع تنظیم مجدد به پیش‌فرض)
512
+ default_instruction = "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد."
513
+ if data_manager.set_global_system_instruction(default_instruction):
514
+ await query.message.reply_text("✅ Global System Instruction به حالت پیش‌فرض بازگردانده شد.")
515
+ else:
516
+ await query.message.reply_text("❌ خطا در بازگرداندن Global System Instruction.")
517
+ elif entity_type == 'group':
518
+ success = data_manager.remove_group_system_instruction(entity_id_int)
519
+ message = "✅ system instruction گروه حذف شد." if success else "⚠️ system instruction گروه وجود نداشت."
520
+ else:
521
+ success = data_manager.remove_user_system_instruction(entity_id_int)
522
+ message = "✅ system instruction کاربر حذف شد." if success else "⚠️ system instruction کاربر وجود نداشت."
523
+
524
+ if entity_type != 'global':
525
+ await query.message.reply_text(message)
526
+
527
+ await query.message.delete()
528
+
529
+ elif action == 'system_toggle':
530
+ # فعال/غیرفعال کردن system instruction
531
+ if entity_type == 'global':
532
+ await query.message.reply_text("⚠️ Global System Instruction را نمی‌توان غیرفعال کرد.")
533
+ return
534
+
535
+ info = data_manager.get_system_instruction_info(
536
+ user_id=entity_id_int if entity_type == 'user' else None,
537
+ chat_id=entity_id_int if entity_type == 'group' else None
538
+ )
539
+
540
+ if info['type'] == entity_type and info['details']:
541
+ current_enabled = info['details'].get('enabled', True)
542
+ new_enabled = not current_enabled
543
+
544
+ if entity_type == 'group':
545
+ success = data_manager.toggle_group_system_instruction(entity_id_int, new_enabled)
546
+ else:
547
+ success = data_manager.toggle_user_system_instruction(entity_id_int, new_enabled)
548
+
549
+ if success:
550
+ status = "✅ فعال شد" if new_enabled else "🚫 غیرفعال شد"
551
+ await query.message.reply_text(f"system instruction {status}.")
552
+
553
+ # به‌روزرسانی پیام اصلی
554
+ if entity_type == 'group':
555
+ await show_group_admin_status(update, context, entity_id_int)
556
+ else:
557
+ await system_instruction_status(update, context)
558
+ else:
559
+ await query.message.reply_text("❌ خطا در تغییر وضعیت system instruction.")
560
+
561
+ elif action == 'system_edit':
562
+ # ویرایش system instruction
563
+ if entity_type == 'global':
564
+ instruction_type = "Global"
565
+ elif entity_type == 'group':
566
+ instruction_type = "گروه"
567
+ else:
568
+ instruction_type = "کاربر"
569
+
570
+ await query.message.reply_text(
571
+ f"لطفاً system instruction جدید برای {instruction_type} را وارد کنید:\n\n"
572
+ "برای لغو: /cancel"
573
+ )
574
+
575
+ # ذخیره اطلاعات برای مرحله بعد
576
+ context.user_data['system_edit'] = {
577
+ 'entity_type': entity_type,
578
+ 'entity_id': entity_id_int,
579
+ 'message_id': query.message.message_id
580
+ }
581
+
582
+ async def handle_system_edit(update: Update, context: ContextTypes.DEFAULT_TYPE):
583
+ """پردازش ویرایش system instruction"""
584
+ # بررسی مجوز اولیه
585
+ user_id = update.effective_user.id
586
+ chat = update.effective_chat
587
+
588
+ if 'system_edit' not in context.user_data:
589
+ return
590
+
591
+ if update.message.text.lower() == '/cancel':
592
+ del context.user_data['system_edit']
593
+ await update.message.reply_text("ویرایش system instruction لغو شد.")
594
+ return
595
+
596
+ edit_data = context.user_data['system_edit']
597
+ entity_type = edit_data['entity_type']
598
+ entity_id = edit_data['entity_id']
599
+
600
+ # بررسی مجوزهای خاص
601
+ if entity_type == 'global':
602
+ if not is_admin(user_id):
603
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را ویرایش کنند.")
604
+ del context.user_data['system_edit']
605
+ return
606
+ elif entity_type == 'group':
607
+ is_admin_bot = is_admin(user_id)
608
+ is_admin_group = is_group_admin(update)
609
+
610
+ if not (is_admin_bot or is_admin_group):
611
+ await update.message.reply_text("⛔️ شما مجوز لازم برای ویرایش system instruction این گروه را ندارید.")
612
+ del context.user_data['system_edit']
613
+ return
614
+ else: # user
615
+ if not is_admin(user_id):
616
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را ویرایش کنند.")
617
+ del context.user_data['system_edit']
618
+ return
619
+
620
+ instruction_text = update.message.text
621
+
622
+ if entity_type == 'global':
623
+ success = data_manager.set_global_system_instruction(instruction_text)
624
+ message = "✅ Global System Instruction به‌روزرسانی شد."
625
+ elif entity_type == 'group':
626
+ success = data_manager.set_group_system_instruction(entity_id, instruction_text, user_id)
627
+ message = "✅ system instruction گروه به‌روزرسانی شد."
628
+ else:
629
+ success = data_manager.set_user_system_instruction(entity_id, instruction_text, user_id)
630
+ message = "✅ system instruction کاربر به‌روزرسانی شد."
631
+
632
+ if success:
633
+ await update.message.reply_text(message)
634
+ del context.user_data['system_edit']
635
+
636
+ # نمایش وضعیت جدید
637
+ await system_instruction_status(update, context)
638
+ else:
639
+ await update.message.reply_text("❌ خطا در به‌روزرسانی system instruction.")
640
+
641
+ def setup_system_instruction_handlers(application):
642
+ """تنظیم هندلرهای system instruction"""
643
+ application.add_handler(CommandHandler("system", set_system_instruction))
644
+ application.add_handler(CommandHandler("system_status", system_instruction_status))
645
+ application.add_handler(CommandHandler("system_help", system_instruction_help))
646
+
647
+ # هندلر برای نمایش global instruction
648
+ application.add_handler(CommandHandler("show_global", show_global_instruction))
649
+
650
+ application.add_handler(CallbackQueryHandler(system_callback_handler, pattern="^system_"))
651
+
652
+ # هندلر برای ویرایش system instruction
653
+ application.add_handler(MessageHandler(
654
+ filters.TEXT & ~filters.COMMAND,
655
+ handle_system_edit
656
+ ))
657
+
658
+ logger.info("System instruction handlers have been set up.")
BOT/render-main/STORED.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py - اصلاح تابع retrieve_context
2
+
3
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
4
+ """بازیابی هوشمند context مرتبط با query"""
5
+
6
+ if max_tokens is None:
7
+ max_tokens = self.max_context_tokens
8
+
9
+ start_time = datetime.now()
10
+
11
+ # 1. دریافت embedding برای query
12
+ query_embedding = self.embedding_manager.get_embedding(query)
13
+
14
+ # 2. بازیابی از لایه‌های مختلف حافظه
15
+ retrieved_memories = []
16
+
17
+ # از حافظه فعال (همیشه)
18
+ retrieved_memories.extend(self._retrieve_from_working_memory())
19
+
20
+ # از حافظه اخیر (بر اساس شباهت)
21
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
22
+ retrieved_memories.extend(recent_memories)
23
+
24
+ # از حافظه بلندمدت (اطلاعات مهم)
25
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
26
+ retrieved_memories.extend(long_term_memories)
27
+
28
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
29
+ core_memories = self._retrieve_core_memories(query)
30
+ retrieved_memories.extend(core_memories)
31
+
32
+ # 3. حذف تکراری‌ها و مرتب‌سازی
33
+ unique_memories = self._deduplicate_memories(retrieved_memories)
34
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
35
+
36
+ # 4. انتخاب تا سقف توکن
37
+ final_context = []
38
+ total_tokens = 0
39
+
40
+ for memory in prioritized_memories:
41
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
42
+
43
+ if total_tokens + memory_tokens <= max_tokens:
44
+ final_context.append(memory)
45
+ total_tokens += memory_tokens
46
+ else:
47
+ break
48
+
49
+ # 5. به‌روزرسانی آمار
50
+ self.stats['retrieved_memories'] += len(final_context)
51
+
52
+ retrieval_time = (datetime.now() - start_time).total_seconds()
53
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
54
+
55
+ return final_context
56
+
57
+ # اصلاح تابع get_context_for_api
58
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
59
+ """تهیه context برای ارسال به API"""
60
+
61
+ # اگر query داریم، context هوشمند بازیابی کن
62
+ if query:
63
+ retrieved = await self.retrieve_context(query)
64
+
65
+ # تبدیل به فرمت API
66
+ api_messages = []
67
+
68
+ # ابتدا اطلاعات پروفایل کاربر
69
+ api_messages.append({
70
+ 'role': 'system',
71
+ 'content': f"User profile: {self._format_user_profile()}"
72
+ })
73
+
74
+ # سپس حافظه‌های بازیابی شده
75
+ for memory in retrieved:
76
+ node = memory['node']
77
+ api_messages.append({
78
+ 'role': node.role,
79
+ 'content': node.content
80
+ })
81
+
82
+ return api_messages
83
+
84
+ else:
85
+ # حالت ساده: فقط حافظه فعال
86
+ api_messages = []
87
+
88
+ for node in list(self.memory_layers['working'])[-6:]:
89
+ api_messages.append({
90
+ 'role': node.role,
91
+ 'content': node.content
92
+ })
93
+
94
+ return api_messages
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ # main.py - اصلاح تابع _process_user_request
114
+
115
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
116
+ chat_id = update.effective_chat.id
117
+ user_message = update.message.text
118
+ user_id = update.effective_user.id
119
+
120
+ start_time = time.time()
121
+
122
+ try:
123
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
124
+
125
+ # استفاده از Context هوشمند اگر فعال باشد
126
+ if HAS_SMART_CONTEXT:
127
+ smart_context = _get_or_create_smart_context(user_id)
128
+
129
+ # پردازش پیام کاربر با سیستم هوشمند
130
+ await smart_context.process_message("user", user_message)
131
+
132
+ # بازیابی context مرتبط
133
+ retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)
134
+
135
+ # آماده‌سازی پیام‌ها برای API
136
+ messages = await smart_context.get_context_for_api(user_message)
137
+
138
+ logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")
139
+ else:
140
+ # استفاده از سیستم قدیمی
141
+ user_context = data_manager.get_context_for_api(user_id)
142
+ data_manager.add_to_user_context(user_id, "user", user_message)
143
+ messages = user_context.copy()
144
+ messages.append({"role": "user", "content": user_message})
145
+
146
+ # ارسال به API
147
+ response = await client.chat.completions.create(
148
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
149
+ messages=messages,
150
+ temperature=1.0,
151
+ top_p=0.95,
152
+ stream=False,
153
+ )
154
+
155
+ end_time = time.time()
156
+ response_time = end_time - start_time
157
+ data_manager.update_response_stats(response_time)
158
+
159
+ ai_response = response.choices[0].message.content
160
+
161
+ # ذخیره پاسخ در سیستم مناسب
162
+ if HAS_SMART_CONTEXT:
163
+ await smart_context.process_message("assistant", ai_response)
164
+ else:
165
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
166
+
167
+ await update.message.reply_text(ai_response)
168
+ data_manager.update_user_stats(user_id, update.effective_user)
169
+
170
+ except httpx.TimeoutException:
171
+ logger.warning(f"Request timed out for user {user_id}.")
172
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
173
+ except Exception as e:
174
+ logger.error(f"Error while processing message for user {user_id}: {e}")
175
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+ # smart_context.py - اصلاح توابع async
194
+
195
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
196
+ layer: str) -> List[Dict[str, Any]]:
197
+ """بازیابی حافظه‌های معنایی"""
198
+ memories = []
199
+
200
+ if layer not in self.memory_layers:
201
+ return memories
202
+
203
+ layer_memories = self.memory_layers[layer]
204
+
205
+ for item in layer_memories:
206
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
207
+
208
+ if node and node.embeddings is not None:
209
+ similarity = self.embedding_manager.cosine_similarity(
210
+ query_embedding, node.embeddings
211
+ )
212
+
213
+ if similarity > self.semantic_similarity_threshold:
214
+ recency_weight = 1.0 if layer == 'working' else 0.7
215
+
216
+ memories.append({
217
+ 'node': node,
218
+ 'source': layer,
219
+ 'relevance': similarity,
220
+ 'recency': recency_weight,
221
+ 'importance': node.importance_score
222
+ })
223
+
224
+ return memories
225
+
226
+ # اصلاح تابع process_message برای جلوگیری از block کردن
227
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
228
+ """پرداش کامل یک پیام جدید"""
229
+ start_time = datetime.now()
230
+
231
+ # 1. تحلیل پیام
232
+ analysis = self.analyzer.analyze_message(content, role)
233
+
234
+ # 2. ایجاد گره حافظه
235
+ message_id = self._generate_message_id(content)
236
+
237
+ # ایجاد embedding به صورت غیرهمزمان
238
+ embedding_task = asyncio.create_task(
239
+ self._get_embedding_async(content)
240
+ )
241
+
242
+ node = MessageNode(
243
+ id=message_id,
244
+ content=content,
245
+ role=role,
246
+ timestamp=datetime.now(),
247
+ message_type=analysis['type'],
248
+ importance_score=analysis['importance'],
249
+ emotion_score=analysis['emotion'],
250
+ tokens=data_manager.count_tokens(content),
251
+ embeddings=None, # موقتاً None
252
+ metadata={
253
+ 'analysis': analysis,
254
+ 'topics': analysis['topics'],
255
+ 'intent': analysis['intent'],
256
+ 'complexity': analysis['complexity']
257
+ }
258
+ )
259
+
260
+ # دریافت embedding (اگر موجود باشد)
261
+ try:
262
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
263
+ except asyncio.TimeoutError:
264
+ logger.warning(f"Embedding generation timeout for message {message_id}")
265
+ node.embeddings = self.embedding_manager.get_embedding(content)
266
+
267
+ # 3. افزودن به حافظه و گراف
268
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
269
+ await asyncio.to_thread(self.memory_graph.add_node, node)
270
+
271
+ # 4. ایجاد ارتباطات
272
+ await asyncio.to_thread(self._create_memory_connections, node)
273
+
274
+ # 5. به‌روزرسانی پروفایل کاربر
275
+ if role == 'user':
276
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
277
+
278
+ # 6. بهینه‌سازی حافظه
279
+ await asyncio.to_thread(self._optimize_memory)
280
+
281
+ # 7. به‌روزرسانی آمار
282
+ self.stats['total_messages'] += 1
283
+ self.stats['average_importance'] = (
284
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
285
+ analysis['importance']
286
+ ) / self.stats['total_messages']
287
+
288
+ # 8. ذخیره داده‌ها
289
+ await asyncio.to_thread(self._save_data)
290
+
291
+ processing_time = (datetime.now() - start_time).total_seconds()
292
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
293
+
294
+ return {
295
+ 'node_id': message_id,
296
+ 'analysis': analysis,
297
+ 'processing_time': processing_time
298
+ }
299
+
300
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
301
+ """دریافت embedding به صورت async"""
302
+ loop = asyncio.get_event_loop()
303
+ return await loop.run_in_executor(
304
+ None,
305
+ self.embedding_manager.get_embedding,
306
+ text
307
+ )
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+ # admin_panel.py - اصلاح توابع async در smart_context
338
+
339
+ @admin_only
340
+ async def admin_smart_context_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
341
+ """نمایش آمار context هوشمند برای کاربران"""
342
+ if not HAS_SMART_CONTEXT:
343
+ await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
344
+ return
345
+
346
+ if not context.args:
347
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/smart_stats 123456789`")
348
+ return
349
+
350
+ user_id = int(context.args[0])
351
+
352
+ # بررسی وجود مدیر context
353
+ if user_id not in smart_context_managers:
354
+ smart_context_managers[user_id] = IntelligentContextManager(user_id)
355
+
356
+ smart_context = smart_context_managers[user_id]
357
+ summary = await asyncio.to_thread(smart_context.get_summary)
358
+
359
+ # ... بقیه کد بدون تغییر
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+ # smart_context.py - اضافه کردن خطاگیری بهتر
388
+
389
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
390
+ """بازیابی هوشمند context مرتبط با query"""
391
+ try:
392
+ if max_tokens is None:
393
+ max_tokens = self.max_context_tokens
394
+
395
+ start_time = datetime.now()
396
+
397
+ # دریافت embedding با timeout
398
+ try:
399
+ embedding_task = asyncio.create_task(
400
+ self._get_embedding_async(query)
401
+ )
402
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
403
+ except asyncio.TimeoutError:
404
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
405
+ query_embedding = self.embedding_manager.get_embedding(query)
406
+
407
+ # بازیابی از حافظه‌های مختلف به صورت موازی
408
+ tasks = []
409
+
410
+ # حافظه فعال
411
+ tasks.append(asyncio.create_task(
412
+ asyncio.to_thread(self._retrieve_from_working_memory)
413
+ ))
414
+
415
+ # حافظه معنایی
416
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
417
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
418
+
419
+ # حافظه هسته
420
+ tasks.append(asyncio.create_task(
421
+ asyncio.to_thread(self._retrieve_core_memories, query)
422
+ ))
423
+
424
+ # اجرای موازی همه tasks
425
+ results = await asyncio.gather(*tasks, return_exceptions=True)
426
+
427
+ # جمع‌آوری نتایج
428
+ retrieved_memories = []
429
+ for result in results:
430
+ if isinstance(result, Exception):
431
+ logger.error(f"Error retrieving memory: {result}")
432
+ continue
433
+ retrieved_memories.extend(result)
434
+
435
+ # ادامه پردازش...
436
+ # ... بقیه کد بدون تغییر
437
+
438
+ except Exception as e:
439
+ logger.error(f"Error in retrieve_context: {e}")
440
+ # Fallback: برگرداندن حافظه فعال
441
+ return self._retrieve_from_working_memory()
BOT/render-main/admin_panel.py ADDED
@@ -0,0 +1,1426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin_panel.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import csv
7
+ import io
8
+ import asyncio
9
+ from datetime import datetime, timedelta
10
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
11
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler
12
+ from telegram.error import TelegramError
13
+
14
+ import matplotlib
15
+ matplotlib.use('Agg')
16
+ import matplotlib.pyplot as plt
17
+ import pandas as pd
18
+ import tempfile
19
+ import psutil
20
+ import platform
21
+ import time
22
+
23
+ # --- تنظیمات ---
24
+ ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
25
+
26
+ import data_manager
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ # --- دکوراتور برای دسترسی ادمین ---
31
+ def admin_only(func):
32
+ async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
33
+ if update.effective_user.id not in ADMIN_IDS:
34
+ await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
35
+ return
36
+ return await func(update, context, *args, **kwargs)
37
+ return wrapped
38
+
39
+ # --- هندلرهای دستورات ادمین ---
40
+ @admin_only
41
+ async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
42
+ """نمایش تمام دستورات موجود ادمین."""
43
+ commands_text = (
44
+ "📋 **دستورات ادمین ربات:**\n\n"
45
+ "📊 `/stats` - نمایش آمار ربات\n"
46
+ "📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
47
+ "🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
48
+ "📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامه‌ریزی شده\n"
49
+ "📋 `/list_scheduled` - نمایش لیست ارسال‌های برنامه‌ریزی شده\n"
50
+ "🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامه‌ریزی شده\n"
51
+ "🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
52
+ "✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
53
+ "💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
54
+ "ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
55
+ "📝 `/logs` - نمایش آخرین لاگ‌ها\n"
56
+ "📂 `/logs_file` - دانلود فایل کامل لاگ‌ها\n"
57
+ "👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
58
+ "🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
59
+ "💾 `/backup` - ایجاد نسخه پشتیبان از داده‌ها\n"
60
+ "📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
61
+ "🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
62
+ "👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
63
+ "👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
64
+ "📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
65
+ "⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
66
+ "🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
67
+ "✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
68
+ "📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
69
+ "💻 `/system_info` - نمایش اطلاعات سیستم\n"
70
+ "🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
71
+ "🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
72
+ "📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
73
+ "📋 `/view_replies [user|group] [آیدی]` - مشاهده ریپلای‌ها\n"
74
+ "🔄 `/set_context_mode [separate|group_shared|hybrid]` - تغییر حالت context\n"
75
+ "📊 `/group_info [آیدی]` - نمایش اطلاعات گروه\n"
76
+ "🗑️ `/clear_group_context [آیدی]` - پاک کردن context گروه\n"
77
+ "💾 `/memory_status` - نمایش وضعیت حافظه\n"
78
+ "⚙️ `/set_global_system [متن]` - تنظیم system instruction سراسری\n"
79
+ "👥 `/set_group_system [آیدی گروه] [متن]` - تنظیم system instruction برای گروه\n"
80
+ "👤 `/set_user_system [آیدی کاربر] [متن]` - تنظیم system instruction برای کاربر\n"
81
+ "📋 `/list_system_instructions` - نمایش لیست system instruction‌ها\n"
82
+ "📋 `/commands` - نمایش این لیست دستورات"
83
+ )
84
+ await update.message.reply_text(commands_text, parse_mode='Markdown')
85
+
86
+ @admin_only
87
+ async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
88
+ """آمار ربات را نمایش می‌دهد."""
89
+ total_users = len(data_manager.DATA['users'])
90
+ total_groups = len(data_manager.DATA['groups'])
91
+ total_messages = data_manager.DATA['stats']['total_messages']
92
+ banned_count = len(data_manager.DATA['banned_users'])
93
+
94
+ now = datetime.now()
95
+ active_24h = sum(1 for user in data_manager.DATA['users'].values()
96
+ if 'last_seen' in user and
97
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
98
+
99
+ active_7d = sum(1 for user in data_manager.DATA['users'].values()
100
+ if 'last_seen' in user and
101
+ datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
102
+
103
+ active_users = sorted(
104
+ data_manager.DATA['users'].items(),
105
+ key=lambda item: item[1].get('last_seen', ''),
106
+ reverse=True
107
+ )[:5]
108
+
109
+ active_users_text = "\n".join(
110
+ [f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
111
+ for user_id, info in active_users]
112
+ )
113
+
114
+ # آمار context
115
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values()
116
+ if user.get('context') and len(user['context']) > 0)
117
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
118
+
119
+ # آمار ریپلای‌ها
120
+ total_replies = 0
121
+ for user in data_manager.DATA['users'].values():
122
+ if 'context' in user:
123
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
124
+
125
+ # آمار گروه‌ها
126
+ groups_with_context = sum(1 for group in data_manager.DATA['groups'].values()
127
+ if group.get('context') and len(group['context']) > 0)
128
+
129
+ # آمار system instructions
130
+ system_stats = data_manager.DATA['system_instructions']
131
+ group_system_count = len(system_stats.get('groups', {}))
132
+ user_system_count = len(system_stats.get('users', {}))
133
+
134
+ text = (
135
+ f"📊 **آمار ربات**\n\n"
136
+ f"👥 **تعداد کل کاربران:** `{total_users}`\n"
137
+ f"👥 **تعداد کل گروه‌ها:** `{total_groups}`\n"
138
+ f"📝 **تعداد کل پیام‌ها:** `{total_messages}`\n"
139
+ f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
140
+ f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
141
+ f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
142
+ f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
143
+ f"💬 **گروه‌های با context فعال:** `{groups_with_context}`\n"
144
+ f"📝 **کل پیام‌های context:** `{total_context_messages}`\n"
145
+ f"📎 **کل ریپلای‌های ثبت شده:** `{total_replies}`\n"
146
+ f"🔄 **حالت context فعلی:** `{data_manager.get_context_mode()}`\n"
147
+ f"⚙️ **System Instructions گروه‌ها:** `{group_system_count}`\n"
148
+ f"⚙️ **System Instructions کاربران:** `{user_system_count}`\n\n"
149
+ f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
150
+ )
151
+ await update.message.reply_text(text, parse_mode='Markdown')
152
+
153
+ @admin_only
154
+ async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
155
+ """یک پیام را به تمام کاربران ارسال می‌کند."""
156
+ if not context.args:
157
+ await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
158
+ return
159
+
160
+ message_text = " ".join(context.args)
161
+ user_ids = list(data_manager.DATA['users'].keys())
162
+ total_sent = 0
163
+ total_failed = 0
164
+
165
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
166
+
167
+ for user_id_str in user_ids:
168
+ try:
169
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
170
+ total_sent += 1
171
+ await asyncio.sleep(0.05)
172
+ except TelegramError as e:
173
+ logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
174
+ total_failed += 1
175
+
176
+ result_text = (
177
+ f"✅ **ارسال همگانی تمام شد**\n\n"
178
+ f"✅ موفق: `{total_sent}`\n"
179
+ f"❌ ناموفق: `{total_failed}`"
180
+ )
181
+ await update.message.reply_text(result_text, parse_mode='Markdown')
182
+
183
+ @admin_only
184
+ async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
185
+ """ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
186
+ if len(context.args) < 3:
187
+ await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
188
+ "معیارهای موجود: `active_days`, `message_count`, `banned`")
189
+ return
190
+
191
+ criteria = context.args[0].lower()
192
+ value = context.args[1]
193
+ message_text = " ".join(context.args[2:])
194
+
195
+ target_users = []
196
+
197
+ if criteria == "active_days":
198
+ try:
199
+ days = int(value)
200
+ target_users = data_manager.get_active_users(days)
201
+ except ValueError:
202
+ await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
203
+ return
204
+
205
+ elif criteria == "message_count":
206
+ try:
207
+ min_count = int(value)
208
+ target_users = data_manager.get_users_by_message_count(min_count)
209
+ except ValueError:
210
+ await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
211
+ return
212
+
213
+ elif criteria == "banned":
214
+ if value.lower() == "true":
215
+ target_users = list(data_manager.DATA['banned_users'])
216
+ elif value.lower() == "false":
217
+ for user_id in data_manager.DATA['users']:
218
+ if int(user_id) not in data_manager.DATA['banned_users']:
219
+ target_users.append(int(user_id))
220
+ else:
221
+ await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
222
+ return
223
+
224
+ else:
225
+ await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
226
+ return
227
+
228
+ if not target_users:
229
+ await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
230
+ return
231
+
232
+ await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
233
+
234
+ total_sent, total_failed = 0, 0
235
+ for user_id in target_users:
236
+ try:
237
+ await context.bot.send_message(chat_id=user_id, text=message_text)
238
+ total_sent += 1
239
+ await asyncio.sleep(0.05)
240
+ except TelegramError as e:
241
+ logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
242
+ total_failed += 1
243
+
244
+ result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
245
+ await update.message.reply_text(result_text, parse_mode='Markdown')
246
+
247
+ @admin_only
248
+ async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
249
+ """تنظیم ارسال برنامه‌ریزی شده پیام به همه کاربران."""
250
+ if len(context.args) < 3:
251
+ await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
252
+ return
253
+
254
+ try:
255
+ date_str, time_str = context.args[0], context.args[1]
256
+ message_text = " ".join(context.args[2:])
257
+
258
+ scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
259
+
260
+ if scheduled_time <= datetime.now():
261
+ await update.message.reply_text("⚠️ زمان برنامه‌ریزی شده باید در آینده باشد.")
262
+ return
263
+
264
+ data_manager.DATA['scheduled_broadcasts'].append({
265
+ 'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
266
+ 'message': message_text,
267
+ 'status': 'pending'
268
+ })
269
+ data_manager.save_data()
270
+
271
+ await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامه‌ریزی شد.")
272
+
273
+ except ValueError:
274
+ await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
275
+
276
+ @admin_only
277
+ async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
278
+ """نمایش لیست ارسال‌های برنامه‌ریزی شده."""
279
+ if not data_manager.DATA['scheduled_broadcasts']:
280
+ await update.message.reply_text("هیچ ارسال برنامه‌ریزی شده‌ای وجود ندارد.")
281
+ return
282
+
283
+ broadcasts_text = "📅 **لیست ارسال‌های برنامه‌ریزی شده:**\n\n"
284
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
285
+ status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
286
+ broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
287
+
288
+ await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
289
+
290
+ @admin_only
291
+ async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
292
+ """حذف یک ارسال برنامه‌ریزی شده."""
293
+ if not context.args or not context.args[0].isdigit():
294
+ await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامه‌ریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
295
+ return
296
+
297
+ index = int(context.args[0]) - 1
298
+
299
+ if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
300
+ await update.message.reply_text("⚠️ شماره ارسال برنامه‌ریزی شده نامعتبر است.")
301
+ return
302
+
303
+ removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
304
+ data_manager.save_data()
305
+
306
+ await update.message.reply_text(f"✅ ارسال برنامه‌ریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
307
+
308
+ @admin_only
309
+ async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
310
+ """یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع می‌دهد."""
311
+ if not context.args or not context.args[0].isdigit():
312
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
313
+ return
314
+
315
+ user_id_to_ban = int(context.args[0])
316
+
317
+ if user_id_to_ban in ADMIN_IDS:
318
+ await update.message.reply_text("🛡️ شما نمی‌توانید یک ادمین را مسدود کنید!")
319
+ return
320
+
321
+ if data_manager.is_user_banned(user_id_to_ban):
322
+ await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
323
+ return
324
+
325
+ data_manager.ban_user(user_id_to_ban)
326
+
327
+ # ارسال پیام به کاربر مسدود شده
328
+ try:
329
+ await context.bot.send_message(
330
+ chat_id=user_id_to_ban,
331
+ text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمی‌توانید از خدمات ربات استفاده کنید."
332
+ )
333
+ except TelegramError as e:
334
+ logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
335
+
336
+ await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
337
+
338
+ @admin_only
339
+ async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
340
+ """مسدودیت یک کاربر را برمی‌دارد و به او اطلاع می‌دهد."""
341
+ if not context.args or not context.args[0].isdigit():
342
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
343
+ return
344
+
345
+ user_id_to_unban = int(context.args[0])
346
+
347
+ if not data_manager.is_user_banned(user_id_to_unban):
348
+ await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شده‌ها وجود ندارد.")
349
+ return
350
+
351
+ data_manager.unban_user(user_id_to_unban)
352
+
353
+ # ارسال پیام به کاربر برای رفع مسدودیت
354
+ try:
355
+ await context.bot.send_message(
356
+ chat_id=user_id_to_unban,
357
+ text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. می‌توانید دوباره از ربات استفاده کنید."
358
+ )
359
+ except TelegramError as e:
360
+ logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
361
+
362
+ await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
363
+
364
+ @admin_only
365
+ async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
366
+ """ارسال پیام مستقیم به یک کاربر خاص."""
367
+ if len(context.args) < 2:
368
+ await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
369
+ return
370
+
371
+ user_id_str = context.args[0]
372
+ if not user_id_str.isdigit():
373
+ await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
374
+ return
375
+
376
+ message_text = " ".join(context.args[1:])
377
+ user_id = int(user_id_str)
378
+
379
+ try:
380
+ await context.bot.send_message(chat_id=user_id, text=message_text)
381
+ await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
382
+ except TelegramError as e:
383
+ await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
384
+
385
+ @admin_only
386
+ async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
387
+ """اطلاعات یک کاربر خاص را نمایش می‌دهد."""
388
+ if not context.args or not context.args[0].isdigit():
389
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
390
+ return
391
+
392
+ user_id = int(context.args[0])
393
+ user_info = data_manager.DATA['users'].get(str(user_id))
394
+
395
+ if not user_info:
396
+ await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
397
+ return
398
+
399
+ is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
400
+
401
+ if 'first_seen' in user_info and 'last_seen' in user_info:
402
+ try:
403
+ first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
404
+ last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
405
+ days_active = max(1, (last_date - first_date).days)
406
+ avg_messages = user_info.get('message_count', 0) / days_active
407
+ except:
408
+ avg_messages = user_info.get('message_count', 0)
409
+ else:
410
+ avg_messages = user_info.get('message_count', 0)
411
+
412
+ # اطلاعات context
413
+ context_messages = len(user_info.get('context', []))
414
+ context_tokens = data_manager.get_context_token_count(user_id)
415
+
416
+ # اطلاعات ریپلای‌ها
417
+ reply_count = 0
418
+ if 'context' in user_info:
419
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
420
+
421
+ # اطلاعات system instruction
422
+ system_info = data_manager.get_system_instruction_info(user_id=user_id)
423
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'user' else "❌"
424
+ system_type = system_info['type']
425
+
426
+ text = (
427
+ f"ℹ️ **اطلاعات کاربر**\n\n"
428
+ f"🆔 **آیدی:** `{user_id}`\n"
429
+ f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
430
+ f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
431
+ f"📊 **تعداد پیام‌ها:** `{user_info.get('message_count', 0)}`\n"
432
+ f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
433
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
434
+ f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
435
+ f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
436
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
437
+ f"🔢 **توکن‌های context:** `{context_tokens}`\n"
438
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
439
+ f"🚫 **وضعیت مسدودیت:** {is_banned}"
440
+ )
441
+ await update.message.reply_text(text, parse_mode='Markdown')
442
+
443
+ @admin_only
444
+ async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
445
+ """آخرین خطوط لاگ ربات را ارسال می‌کند."""
446
+ try:
447
+ with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
448
+ lines = f.readlines()
449
+ last_lines = lines[-30:]
450
+ log_text = "".join(last_lines)
451
+ if not log_text:
452
+ await update.message.reply_text("فایل لاگ خالی است.")
453
+ return
454
+
455
+ if len(log_text) > 4096:
456
+ for i in range(0, len(log_text), 4096):
457
+ await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
458
+ else:
459
+ await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
460
+
461
+ except FileNotFoundError:
462
+ await update.message.reply_text("فایل لاگ یافت نشد.")
463
+ except Exception as e:
464
+ await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
465
+
466
+ @admin_only
467
+ async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
468
+ """فایل کامل لاگ ربات را ارسال می‌کند."""
469
+ try:
470
+ await update.message.reply_document(
471
+ document=open(data_manager.LOG_FILE, 'rb'),
472
+ caption="📂 فایل کامل لاگ‌های ربات"
473
+ )
474
+ except FileNotFoundError:
475
+ await update.message.reply_text("فایل لاگ یافت نشد.")
476
+ except Exception as e:
477
+ await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
478
+
479
+ @admin_only
480
+ async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
481
+ """نمایش لیست کامل کاربران با صفحه‌بندی."""
482
+ users = data_manager.DATA['users']
483
+
484
+ page = 1
485
+ if context.args and context.args[0].isdigit():
486
+ page = int(context.args[0])
487
+ if page < 1: page = 1
488
+
489
+ users_per_page = 20
490
+ total_users = len(users)
491
+ total_pages = (total_users + users_per_page - 1) // users_per_page
492
+
493
+ if page > total_pages: page = total_pages
494
+
495
+ start_idx = (page - 1) * users_per_page
496
+ end_idx = min(start_idx + users_per_page, total_users)
497
+
498
+ sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
499
+
500
+ users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
501
+
502
+ for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
503
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
504
+ username = user_info.get('username', 'N/A')
505
+ first_name = user_info.get('first_name', 'N/A')
506
+ last_seen = user_info.get('last_seen', 'N/A')
507
+ message_count = user_info.get('message_count', 0)
508
+ context_count = len(user_info.get('context', []))
509
+
510
+ # تعداد ریپلای‌ها
511
+ reply_count = 0
512
+ if 'context' in user_info:
513
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
514
+
515
+ # system instruction
516
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
517
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
518
+
519
+ users_text += f"{i}. {is_banned} {has_system} `{user_id}` - {first_name} (@{username})\n"
520
+ users_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
521
+ users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
522
+
523
+ keyboard = []
524
+ if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
525
+ if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
526
+
527
+ reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
528
+ await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
529
+
530
+ @admin_only
531
+ async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
532
+ """جستجوی کاربر بر اساس نام یا نام کاربری."""
533
+ if not context.args:
534
+ await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
535
+ return
536
+
537
+ search_term = " ".join(context.args).lower()
538
+ users = data_manager.DATA['users']
539
+
540
+ matching_users = []
541
+ for user_id, user_info in users.items():
542
+ first_name = (user_info.get('first_name') or '').lower()
543
+ username = (user_info.get('username') or '').lower()
544
+
545
+ if search_term in first_name or search_term in username:
546
+ is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
547
+ matching_users.append((user_id, user_info, is_banned))
548
+
549
+ if not matching_users:
550
+ await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
551
+ return
552
+
553
+ results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
554
+
555
+ for user_id, user_info, is_banned in matching_users:
556
+ username_display = user_info.get('username', 'N/A')
557
+ first_name_display = user_info.get('first_name', 'N/A')
558
+ last_seen = user_info.get('last_seen', 'N/A')
559
+ message_count = user_info.get('message_count', 0)
560
+ context_count = len(user_info.get('context', []))
561
+
562
+ # تعداد ریپلای‌ها
563
+ reply_count = 0
564
+ if 'context' in user_info:
565
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
566
+
567
+ # system instruction
568
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
569
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'user' else ""
570
+
571
+ results_text += f"{is_banned} {has_system} `{user_id}` - {first_name_display} (@{username_display})\n"
572
+ results_text += f" 📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
573
+ results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
574
+
575
+ await update.message.reply_text(results_text, parse_mode='Markdown')
576
+
577
+ @admin_only
578
+ async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
579
+ """ایجاد نسخه پشتیبان از داده‌های ربات."""
580
+ try:
581
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
582
+ backup_file = f"bot_backup_{timestamp}.json"
583
+
584
+ data_to_backup = data_manager.DATA.copy()
585
+ data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
586
+
587
+ with open(backup_file, 'w', encoding='utf-8') as f:
588
+ json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
589
+
590
+ await update.message.reply_document(
591
+ document=open(backup_file, 'rb'),
592
+ caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
593
+ )
594
+
595
+ logger.info(f"Backup created: {backup_file}")
596
+ os.remove(backup_file)
597
+ except Exception as e:
598
+ await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
599
+ logger.error(f"Error creating backup: {e}")
600
+
601
+ @admin_only
602
+ async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
603
+ """ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
604
+ users = data_manager.DATA['users']
605
+
606
+ df_data = []
607
+ for user_id, user_info in users.items():
608
+ is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
609
+ context_count = len(user_info.get('context', []))
610
+ context_tokens = data_manager.get_context_token_count(int(user_id))
611
+
612
+ # تعداد ریپلای‌ها
613
+ reply_count = 0
614
+ if 'context' in user_info:
615
+ reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
616
+
617
+ # system instruction
618
+ system_info = data_manager.get_system_instruction_info(user_id=int(user_id))
619
+ has_system = "بله" if system_info['has_instruction'] and system_info['type'] == 'user' else "خیر"
620
+ system_type = system_info['type']
621
+
622
+ df_data.append({
623
+ 'User ID': user_id,
624
+ 'First Name': user_info.get('first_name', 'N/A'),
625
+ 'Username': user_info.get('username', 'N/A'),
626
+ 'Message Count': user_info.get('message_count', 0),
627
+ 'Context Messages': context_count,
628
+ 'Context Tokens': context_tokens,
629
+ 'Reply Count': reply_count,
630
+ 'Has System Instruction': has_system,
631
+ 'System Type': system_type,
632
+ 'First Seen': user_info.get('first_seen', 'N/A'),
633
+ 'Last Seen': user_info.get('last_seen', 'N/A'),
634
+ 'Banned': is_banned
635
+ })
636
+
637
+ df = pd.DataFrame(df_data)
638
+
639
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
640
+ df.to_csv(f.name, index=False)
641
+ temp_file_path = f.name
642
+
643
+ await update.message.reply_document(
644
+ document=open(temp_file_path, 'rb'),
645
+ caption="📊 فایل CSV اطلاعات کاربران"
646
+ )
647
+
648
+ os.unlink(temp_file_path)
649
+
650
+ @admin_only
651
+ async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
652
+ """حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع می‌دهد."""
653
+ if not context.args or context.args[0].lower() not in ['on', 'off']:
654
+ await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
655
+ return
656
+
657
+ status = context.args[0].lower()
658
+
659
+ if status == 'on':
660
+ if data_manager.DATA.get('maintenance_mode', False):
661
+ await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
662
+ return
663
+
664
+ data_manager.DATA['maintenance_mode'] = True
665
+ data_manager.save_data()
666
+
667
+ await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاع‌رسانی به کاربران...")
668
+
669
+ user_ids = list(data_manager.DATA['users'].keys())
670
+ for user_id_str in user_ids:
671
+ try:
672
+ if int(user_id_str) not in ADMIN_IDS:
673
+ await context.bot.send_message(
674
+ chat_id=int(user_id_str),
675
+ text="🔧 ربات در حال حاضر در حالت به‌روزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
676
+ )
677
+ await asyncio.sleep(0.05)
678
+ except TelegramError:
679
+ continue
680
+
681
+ elif status == 'off':
682
+ if not data_manager.DATA.get('maintenance_mode', False):
683
+ await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
684
+ return
685
+
686
+ data_manager.DATA['maintenance_mode'] = False
687
+ data_manager.save_data()
688
+
689
+ await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاع‌رسانی به کاربران...")
690
+
691
+ user_ids = list(data_manager.DATA['users'].keys())
692
+ for user_id_str in user_ids:
693
+ try:
694
+ if int(user_id_str) not in ADMIN_IDS:
695
+ await context.bot.send_message(
696
+ chat_id=int(user_id_str),
697
+ text="✅ به‌روزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! می‌توانید دوباره از ربات استفاده کنید."
698
+ )
699
+ await asyncio.sleep(0.05)
700
+ except TelegramError:
701
+ continue
702
+
703
+ @admin_only
704
+ async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
705
+ """تنظیم پیام خوشامدگویی جدید."""
706
+ if not context.args:
707
+ await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
708
+ "مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
709
+ return
710
+
711
+ new_message = " ".join(context.args)
712
+ data_manager.DATA['welcome_message'] = new_message
713
+ data_manager.save_data()
714
+
715
+ await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت به‌روز��سانی شد.")
716
+
717
+ @admin_only
718
+ async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
719
+ """تنظیم پیام خداحافظی جدید."""
720
+ if not context.args:
721
+ await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
722
+ "مثال: `/set_goodbye {user_mention}، خداحافظ!`")
723
+ return
724
+
725
+ new_message = " ".join(context.args)
726
+ data_manager.DATA['goodbye_message'] = new_message
727
+ data_manager.save_data()
728
+
729
+ await update.message.reply_text("✅ پیام خداحافظی با موفقیت به‌روزرسانی شد.")
730
+
731
+ @admin_only
732
+ async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
733
+ """ایجاد و ارسال نمودار فعالیت کاربران."""
734
+ users = data_manager.DATA['users']
735
+ activity_hours = [0] * 24
736
+
737
+ for user_info in users.values():
738
+ if 'last_seen' in user_info:
739
+ try:
740
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
741
+ activity_hours[last_seen.hour] += 1
742
+ except ValueError:
743
+ continue
744
+
745
+ plt.figure(figsize=(12, 6))
746
+ plt.bar(range(24), activity_hours, color='skyblue')
747
+ plt.title('نمودار فعالیت کاربران بر اساس ساعت')
748
+ plt.xlabel('ساعت')
749
+ plt.ylabel('تعداد کاربران فعال')
750
+ plt.xticks(range(24))
751
+ plt.grid(axis='y', alpha=0.3)
752
+
753
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
754
+ plt.savefig(f.name, bbox_inches='tight')
755
+ temp_file_path = f.name
756
+
757
+ plt.close()
758
+
759
+ await update.message.reply_photo(
760
+ photo=open(temp_file_path, 'rb'),
761
+ caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
762
+ )
763
+
764
+ os.unlink(temp_file_path)
765
+
766
+ @admin_only
767
+ async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
768
+ """نمایش آمار زمان پاسخگویی ربات."""
769
+ stats = data_manager.DATA['stats']
770
+ await update.message.reply_text(
771
+ "📈 **آمار زمان پاسخگویی ربات**\n\n"
772
+ f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
773
+ f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
774
+ f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
775
+ f"📊 کل پاسخ‌های ثبت شده: `{stats.get('total_responses', 0)}`"
776
+ )
777
+
778
+ @admin_only
779
+ async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
780
+ """افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
781
+ if not context.args:
782
+ await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
783
+ "مثال: `/add_blocked_word کلمه_نامناسب`")
784
+ return
785
+
786
+ word = " ".join(context.args).lower()
787
+
788
+ if word in data_manager.DATA['blocked_words']:
789
+ await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
790
+ return
791
+
792
+ data_manager.DATA['blocked_words'].append(word)
793
+ data_manager.save_data()
794
+
795
+ await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
796
+
797
+ @admin_only
798
+ async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
799
+ """حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
800
+ if not context.args:
801
+ await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
802
+ "مثال: `/remove_blocked_word کلمه_نامناسب`")
803
+ return
804
+
805
+ word = " ".join(context.args).lower()
806
+
807
+ if word not in data_manager.DATA['blocked_words']:
808
+ await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
809
+ return
810
+
811
+ data_manager.DATA['blocked_words'].remove(word)
812
+ data_manager.save_data()
813
+
814
+ await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
815
+
816
+ @admin_only
817
+ async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
818
+ """نمایش لیست کلمات مسدود شده."""
819
+ if not data_manager.DATA['blocked_words']:
820
+ await update.message.reply_text("هیچ کلمه مسدود شده‌ای در لیست وجود ندارد.")
821
+ return
822
+
823
+ words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
824
+ await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
825
+
826
+ @admin_only
827
+ async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
828
+ """نمایش اطلاعات سیستم و منابع."""
829
+ bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
830
+ try:
831
+ bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
832
+ uptime = datetime.now() - bot_start_time
833
+ except:
834
+ uptime = "نامشخص"
835
+
836
+ total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
837
+ users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
838
+
839
+ # تعداد کل ریپلای‌ها
840
+ total_replies = 0
841
+ for user in data_manager.DATA['users'].values():
842
+ if 'context' in user:
843
+ total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
844
+
845
+ # آمار system instructions
846
+ system_stats = data_manager.DATA['system_instructions']
847
+ group_system_count = len(system_stats.get('groups', {}))
848
+ user_system_count = len(system_stats.get('users', {}))
849
+
850
+ system_info = (
851
+ f"💻 **اطلاعات سیستم:**\n\n"
852
+ f"🖥️ سیستم‌عامل: {platform.system()} {platform.release()}\n"
853
+ f"🐍 نسخه پایتون: {platform.python_version()}\n"
854
+ f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
855
+ f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
856
+ f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
857
+ f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
858
+ f"⏱️ زمان اجرای ربات: {uptime}\n"
859
+ f"💭 کاربران با context: {users_with_context}\n"
860
+ f"💬 کل پیام‌های context: {total_context_messages}\n"
861
+ f"📎 کل ریپلای‌های ثبت شده: {total_replies}\n"
862
+ f"⚙️ System Instructions گروه‌ها: {group_system_count}\n"
863
+ f"⚙️ System Instructions کاربران: {user_system_count}"
864
+ )
865
+
866
+ await update.message.reply_text(system_info, parse_mode='Markdown')
867
+
868
+ @admin_only
869
+ async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
870
+ """ریست کردن آمار ربات."""
871
+ if not context.args:
872
+ await update.message.reply_text("⚠️ لطفاً نوع آماری که می‌خواهید ریست کنید را مشخص کنید.\n"
873
+ "مثال: `/reset_stats messages` یا `/reset_stats all`")
874
+ return
875
+
876
+ stat_type = context.args[0].lower()
877
+
878
+ if stat_type == "messages":
879
+ data_manager.DATA['stats']['total_messages'] = 0
880
+ for user_id in data_manager.DATA['users']:
881
+ data_manager.DATA['users'][user_id]['message_count'] = 0
882
+ await update.message.reply_text("✅ آمار پیام‌ها با موفقیت ریست شد.")
883
+
884
+ elif stat_type == "all":
885
+ data_manager.DATA['stats'] = {
886
+ 'total_messages': 0,
887
+ 'total_users': len(data_manager.DATA['users']),
888
+ 'total_groups': len(data_manager.DATA['groups']),
889
+ 'avg_response_time': 0,
890
+ 'max_response_time': 0,
891
+ 'min_response_time': 0,
892
+ 'total_responses': 0
893
+ }
894
+ for user_id in data_manager.DATA['users']:
895
+ data_manager.DATA['users'][user_id]['message_count'] = 0
896
+ await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
897
+
898
+ else:
899
+ await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینه‌های موجود: messages, all")
900
+ return
901
+
902
+ data_manager.save_data()
903
+
904
+ # --- دستورات مدیریت context ---
905
+ @admin_only
906
+ async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
907
+ """پاک کردن context یک کاربر"""
908
+ if not context.args or not context.args[0].isdigit():
909
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
910
+ return
911
+
912
+ user_id = int(context.args[0])
913
+ data_manager.clear_user_context(user_id)
914
+
915
+ await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
916
+
917
+ @admin_only
918
+ async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
919
+ """مشاهده context یک کاربر"""
920
+ if not context.args or not context.args[0].isdigit():
921
+ await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
922
+ return
923
+
924
+ user_id = int(context.args[0])
925
+ user_context = data_manager.get_user_context(user_id)
926
+
927
+ if not user_context:
928
+ await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
929
+ return
930
+
931
+ context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
932
+ total_tokens = 0
933
+ reply_count = 0
934
+
935
+ for i, msg in enumerate(user_context, 1):
936
+ role_emoji = "👤" if msg['role'] == 'user' else "🤖"
937
+ tokens = data_manager.count_tokens(msg['content'])
938
+ total_tokens += tokens
939
+
940
+ # بررسی ریپلای
941
+ has_reply = msg.get('has_reply', False)
942
+ if has_reply:
943
+ reply_count += 1
944
+ reply_emoji = "📎"
945
+ else:
946
+ reply_emoji = ""
947
+
948
+ content_preview = msg['content']
949
+ if len(content_preview) > 100:
950
+ content_preview = content_preview[:100] + "..."
951
+
952
+ context_text += f"{i}. {role_emoji} {reply_emoji} **{msg['role']}** ({tokens} توکن)\n"
953
+ context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
954
+
955
+ if has_reply:
956
+ context_text += f" 📎 ریپلای به: {msg.get('reply_to_user_name', 'Unknown')}\n"
957
+
958
+ context_text += f" 📝 {content_preview}\n\n"
959
+
960
+ context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن، {reply_count} ریپلای"
961
+
962
+ await update.message.reply_text(context_text, parse_mode='Markdown')
963
+
964
+ @admin_only
965
+ async def admin_view_replies(update: Update, context: ContextTypes.DEFAULT_TYPE):
966
+ """مشاهده ریپلای‌های یک کاربر یا گروه"""
967
+ if len(context.args) < 2:
968
+ await update.message.reply_text(
969
+ "⚠️ فرمت صحیح: `/view_replies [user|group] [آیدی]`\n"
970
+ "مثال: `/view_replies user 123456789`\n"
971
+ "مثال: `/view_replies group -1001234567890`"
972
+ )
973
+ return
974
+
975
+ entity_type = context.args[0].lower()
976
+ entity_id = context.args[1]
977
+
978
+ if entity_type == 'user':
979
+ try:
980
+ user_id = int(entity_id)
981
+ user_context = data_manager.get_user_context(user_id)
982
+ if not user_context:
983
+ await update.message.reply_text(f"کاربر `{entity_id}` context ندارد.")
984
+ return
985
+
986
+ replies = [msg for msg in user_context if msg.get('has_reply', False)]
987
+
988
+ if not replies:
989
+ await update.message.reply_text(f"کاربر `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
990
+ return
991
+
992
+ text = f"📋 **ریپلای‌های کاربر `{entity_id}`**\n\n"
993
+ for i, msg in enumerate(replies, 1):
994
+ text += f"{i}. **زمان:** {msg.get('timestamp', 'N/A')}\n"
995
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
996
+ if msg.get('is_reply_to_bot', False):
997
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
998
+ else:
999
+ text += f" **نوع:** ریپلای به کاربر\n"
1000
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1001
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1002
+
1003
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1004
+
1005
+ await update.message.reply_text(text, parse_mode='Markdown')
1006
+ except ValueError:
1007
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1008
+
1009
+ elif entity_type == 'group':
1010
+ try:
1011
+ chat_id = int(entity_id)
1012
+ group_context = data_manager.get_group_context(chat_id)
1013
+ if not group_context:
1014
+ await update.message.reply_text(f"گروه `{entity_id}` context ندارد.")
1015
+ return
1016
+
1017
+ replies = [msg for msg in group_context if msg.get('has_reply', False)]
1018
+
1019
+ if not replies:
1020
+ await update.message.reply_text(f"گروه `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
1021
+ return
1022
+
1023
+ text = f"📋 **ریپلای‌های گروه `{entity_id}`**\n\n"
1024
+ for i, msg in enumerate(replies, 1):
1025
+ user_name = msg.get('user_name', 'Unknown')
1026
+ text += f"{i}. **کاربر:** {user_name}\n"
1027
+ text += f" **زمان:** {msg.get('timestamp', 'N/A')}\n"
1028
+ text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
1029
+ if msg.get('is_reply_to_bot', False):
1030
+ text += f" **نوع:** ریپلای به ربات 🤖\n"
1031
+ else:
1032
+ text += f" **نوع:** ریپلای به کاربر\n"
1033
+ text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
1034
+ text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
1035
+
1036
+ text += f"📊 **مجموع:** {len(replies)} ریپلای"
1037
+
1038
+ await update.message.reply_text(text, parse_mode='Markdown')
1039
+ except ValueError:
1040
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1041
+
1042
+ else:
1043
+ await update.message.reply_text("⚠️ نوع نامعتبر. فقط 'user' یا 'group' مجاز است.")
1044
+
1045
+ # --- دستورات جدید برای مدیریت گروه‌ها ---
1046
+ @admin_only
1047
+ async def admin_set_context_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
1048
+ """تنظیم حالت context ربات"""
1049
+ if not context.args or context.args[0].lower() not in ['separate', 'group_shared', 'hybrid']:
1050
+ await update.message.reply_text(
1051
+ "⚠️ فرمت صحیح: `/set_context_mode [separate|group_shared|hybrid]`\n\n"
1052
+ "• **separate**: هر کاربر context جداگانه دارد (8192 توکن)\n"
1053
+ "• **group_shared**: همه کاربران در یک گروه context مشترک دارند (16384 توکن)\n"
1054
+ "• **hybrid**: ترکیبی از context شخصی و گروهی\n\n"
1055
+ "💡 **توجه:** حالت group_shared حافظه بیشتری برای گروه‌ها فراهم می‌کند."
1056
+ )
1057
+ return
1058
+
1059
+ mode = context.args[0].lower()
1060
+ if data_manager.set_context_mode(mode):
1061
+ await update.message.reply_text(f"✅ حالت context به `{mode}` تغییر یافت.")
1062
+ else:
1063
+ await update.message.reply_text("❌ خطا در تغییر حالت context.")
1064
+
1065
+ @admin_only
1066
+ async def admin_group_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
1067
+ """نمایش اطلاعات یک گروه"""
1068
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1069
+ await update.message.reply_text("⚠️ لطفاً آیدی عددی گروه را وارد کنید.\nمثال: `/group_info -1001234567890`")
1070
+ return
1071
+
1072
+ chat_id = int(context.args[0])
1073
+ group_info = data_manager.DATA['groups'].get(str(chat_id))
1074
+
1075
+ if not group_info:
1076
+ await update.message.reply_text(f"گروهی با آیدی `{chat_id}` در دیتابیس یافت نشد.")
1077
+ return
1078
+
1079
+ # تبدیل set اعضا به لیست برای نمایش
1080
+ members = list(group_info.get('members', set()))
1081
+ members_count = len(members)
1082
+
1083
+ # اطلاعات context گروه
1084
+ context_messages = len(group_info.get('context', []))
1085
+ total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info.get('context', []))
1086
+
1087
+ # تعداد ریپلای‌ها در گروه
1088
+ reply_count = 0
1089
+ if 'context' in group_info:
1090
+ reply_count = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1091
+
1092
+ # system instruction
1093
+ system_info = data_manager.get_system_instruction_info(chat_id=chat_id)
1094
+ has_system = "✅" if system_info['has_instruction'] and system_info['type'] == 'group' else "❌"
1095
+ system_type = system_info['type']
1096
+
1097
+ text = (
1098
+ f"📊 **اطلاعات گروه**\n\n"
1099
+ f"🆔 **آیدی:** `{chat_id}`\n"
1100
+ f"🏷️ **عنوان:** {group_info.get('title', 'N/A')}\n"
1101
+ f"📝 **تعداد پیام‌ها:** `{group_info.get('message_count', 0)}`\n"
1102
+ f"👥 **تعداد اعضا:** `{members_count}`\n"
1103
+ f"💭 **پیام‌های context:** `{context_messages}`\n"
1104
+ f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
1105
+ f"🔢 **توکن‌های context:** `{total_tokens}`\n"
1106
+ f"⚙️ **System Instruction:** {has_system} ({system_type})\n"
1107
+ f"📅 **اولین فعالیت:** {group_info.get('first_seen', 'N/A')}\n"
1108
+ f"🕒 **آخرین فعالیت:** {group_info.get('last_seen', 'N/A')}"
1109
+ )
1110
+
1111
+ await update.message.reply_text(text, parse_mode='Markdown')
1112
+
1113
+ @admin_only
1114
+ async def admin_clear_group_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
1115
+ """پاک کردن context یک گروه"""
1116
+ if not context.args or not context.args[0].lstrip('-').isdigit():
1117
+ await update.message.reply_text("⚠️ لطفاً آیدی گروه را وارد کنید.\nمثال: `/clear_group_context -1001234567890`")
1118
+ return
1119
+
1120
+ chat_id = int(context.args[0])
1121
+ data_manager.clear_group_context(chat_id)
1122
+
1123
+ await update.message.reply_text(f"✅ context گروه `{chat_id}` با موفقیت پاک شد.")
1124
+
1125
+ @admin_only
1126
+ async def admin_memory_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
1127
+ """نمایش وضعیت حافظه و context گروه‌ها"""
1128
+ groups = data_manager.DATA['groups']
1129
+
1130
+ if not groups:
1131
+ await update.message.reply_text("هیچ گروهی در دیتابیس وجود ندارد.")
1132
+ return
1133
+
1134
+ # محاسبه آمار
1135
+ total_groups = len(groups)
1136
+ groups_with_context = sum(1 for g in groups.values() if g.get('context'))
1137
+ total_context_messages = sum(len(g.get('context', [])) for g in groups.values())
1138
+ total_context_tokens = 0
1139
+ total_replies = 0
1140
+ groups_with_system = 0
1141
+
1142
+ for group_id, group_info in groups.items():
1143
+ if 'context' in group_info:
1144
+ total_context_tokens += sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1145
+ total_replies += sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1146
+
1147
+ # بررسی system instruction
1148
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1149
+ if system_info['has_instruction'] and system_info['type'] == 'group':
1150
+ groups_with_system += 1
1151
+
1152
+ # لیست گروه‌هایی که بیشترین استفاده از حافظه را دارند
1153
+ groups_by_tokens = []
1154
+ for group_id, group_info in groups.items():
1155
+ if 'context' in group_info:
1156
+ tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
1157
+ messages = len(group_info['context'])
1158
+ replies = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
1159
+
1160
+ # system instruction
1161
+ system_info = data_manager.get_system_instruction_info(chat_id=int(group_id))
1162
+ has_system = "⚙️" if system_info['has_instruction'] and system_info['type'] == 'group' else ""
1163
+
1164
+ groups_by_tokens.append((group_id, tokens, messages, replies, has_system))
1165
+
1166
+ # مرتب‌سازی بر اساس تعداد توکن
1167
+ groups_by_tokens.sort(key=lambda x: x[1], reverse=True)
1168
+
1169
+ status_text = (
1170
+ f"💾 **وضعیت حافظه گروه‌ها**\n\n"
1171
+ f"📊 **آمار کلی:**\n"
1172
+ f"• تعداد کل گروه‌ها: `{total_groups}`\n"
1173
+ f"• گروه‌های دارای context: `{groups_with_context}`\n"
1174
+ f"• گروه‌های دارای system instruction: `{groups_with_system}`\n"
1175
+ f"• کل پیام‌های context: `{total_context_messages}`\n"
1176
+ f"• کل ریپلای‌ها: `{total_replies}`\n"
1177
+ f"• کل توکن‌های استفاده شده: `{total_context_tokens}`\n"
1178
+ f"• میانگین توکن per گروه: `{total_context_tokens/max(1, groups_with_context):.0f}`\n\n"
1179
+ f"🏆 **گروه‌های با بیشترین استفاده از حافظه:**\n"
1180
+ )
1181
+
1182
+ for i, (group_id, tokens, messages, replies, has_system) in enumerate(groups_by_tokens[:10], 1):
1183
+ usage_percent = (tokens / 16384) * 100
1184
+ status_text += f"{i}. {has_system} گروه `{group_id}`: {messages} پیام، {replies} ریپلای، {tokens} توکن ({usage_percent:.1f}%)\n"
1185
+
1186
+ await update.message.reply_text(status_text, parse_mode='Markdown')
1187
+
1188
+ # --- دستورات مدیریت system instructions ---
1189
+ @admin_only
1190
+ async def admin_set_global_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1191
+ """تنظیم system instruction سراسری"""
1192
+ if not context.args:
1193
+ await update.message.reply_text(
1194
+ "⚠️ لطفاً system instruction سراسری را وارد کنید.\n\n"
1195
+ "مثال: `/set_global_system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n\n"
1196
+ "برای مشاهده وضعیت فعلی: `/system_status`"
1197
+ )
1198
+ return
1199
+
1200
+ instruction_text = " ".join(context.args)
1201
+
1202
+ if data_manager.set_global_system_instruction(instruction_text):
1203
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1204
+ await update.message.reply_text(
1205
+ f"✅ system instruction سراسری تنظیم شد:\n\n"
1206
+ f"{instruction_preview}\n\n"
1207
+ f"این دستور برای تمام کاربران و گروه‌هایی که دستور خاصی ندارند اعمال خواهد شد."
1208
+ )
1209
+ else:
1210
+ await update.message.reply_text("❌ خطا در تنظیم system instruction سراسری.")
1211
+
1212
+ @admin_only
1213
+ async def admin_set_group_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1214
+ """تنظیم system instruction برای گروه"""
1215
+ if len(context.args) < 2:
1216
+ await update.message.reply_text(
1217
+ "⚠️ فرمت صحیح: `/set_group_system [آیدی گروه] [متن]`\n\n"
1218
+ "مثال: `/set_group_system -1001234567890 تو در این گروه فقط باید به سوالات فنی پاسخ بدهی.`"
1219
+ )
1220
+ return
1221
+
1222
+ chat_id_str = context.args[0]
1223
+ if not chat_id_str.lstrip('-').isdigit():
1224
+ await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
1225
+ return
1226
+
1227
+ chat_id = int(chat_id_str)
1228
+ instruction_text = " ".join(context.args[1:])
1229
+ user_id = update.effective_user.id
1230
+
1231
+ if data_manager.set_group_system_instruction(chat_id, instruction_text, user_id):
1232
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1233
+ await update.message.reply_text(
1234
+ f"✅ system instruction برای گروه `{chat_id}` تنظیم شد:\n\n"
1235
+ f"{instruction_preview}"
1236
+ )
1237
+ else:
1238
+ await update.message.reply_text("❌ خطا در تنظیم system instruction گروه.")
1239
+
1240
+ @admin_only
1241
+ async def admin_set_user_system(update: Update, context: ContextTypes.DEFAULT_TYPE):
1242
+ """تنظیم system instruction برای کاربر"""
1243
+ if len(context.args) < 2:
1244
+ await update.message.reply_text(
1245
+ "⚠️ فرمت صحیح: `/set_user_system [آیدی کاربر] [متن]`\n\n"
1246
+ "مثال: `/set_user_system 123456789 تو برای این کاربر باید به زبان ساده و با مثال پاسخ بدهی.`"
1247
+ )
1248
+ return
1249
+
1250
+ user_id_str = context.args[0]
1251
+ if not user_id_str.isdigit():
1252
+ await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
1253
+ return
1254
+
1255
+ user_id = int(user_id_str)
1256
+ instruction_text = " ".join(context.args[1:])
1257
+ admin_id = update.effective_user.id
1258
+
1259
+ if data_manager.set_user_system_instruction(user_id, instruction_text, admin_id):
1260
+ instruction_preview = instruction_text[:150] + "..." if len(instruction_text) > 150 else instruction_text
1261
+ await update.message.reply_text(
1262
+ f"✅ system instruction برای کاربر `{user_id}` تنظیم شد:\n\n"
1263
+ f"{instruction_preview}"
1264
+ )
1265
+ else:
1266
+ await update.message.reply_text("❌ خطا در تنظیم system instruction کاربر.")
1267
+
1268
+ # در بخش admin_list_system_instructions:
1269
+ @admin_only
1270
+ async def admin_list_system_instructions(update: Update, context: ContextTypes.DEFAULT_TYPE):
1271
+ """نمایش لیست system instruction‌ها - فقط برای ادمین‌های ربات"""
1272
+ system_data = data_manager.DATA['system_instructions']
1273
+
1274
+ # نمایش system instruction سراسری
1275
+ global_instruction = system_data.get('global', '')
1276
+ global_preview = global_instruction[:150] + "..." if len(global_instruction) > 150 else global_instruction
1277
+
1278
+ text = (
1279
+ f"🌐 **Global System Instruction:**\n{global_preview}\n\n"
1280
+ f"⚠️ **توجه:** این اطلاعات فقط برای ادمین‌های ربات نمایش داده می‌شود.\n"
1281
+ f"ادمین‌های گروه فقط می‌توانند system instruction گروه خودشان را مشاهده کنند.\n\n"
1282
+ )
1283
+
1284
+ # نمایش system instruction گروه‌ها
1285
+ groups = system_data.get('groups', {})
1286
+ if groups:
1287
+ text += f"👥 **System Instruction گروه‌ها ({len(groups)}):**\n"
1288
+
1289
+ for i, (chat_id, group_data) in enumerate(groups.items(), 1):
1290
+ instruction = group_data.get('instruction', '')
1291
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1292
+ set_by = group_data.get('set_by', 'نامشخص')
1293
+ enabled = "✅" if group_data.get('enabled', True) else "❌"
1294
+
1295
+ text += f"{i}. گروه `{chat_id}` {enabled}\n"
1296
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1297
+ text += f" 📝 {preview}\n\n"
1298
+
1299
+ # نمایش system instruction کاربران
1300
+ users = system_data.get('users', {})
1301
+ if users:
1302
+ text += f"👤 **System Instruction کاربران ({len(users)}):**\n"
1303
+
1304
+ for i, (user_id, user_data) in enumerate(users.items(), 1):
1305
+ instruction = user_data.get('instruction', '')
1306
+ preview = instruction[:80] + "..." if len(instruction) > 80 else instruction
1307
+ set_by = user_data.get('set_by', 'نامشخص')
1308
+ enabled = "✅" if user_data.get('enabled', True) else "❌"
1309
+
1310
+ text += f"{i}. کاربر `{user_id}` {enabled}\n"
1311
+ text += f" 👤 تنظیم‌کننده: {set_by}\n"
1312
+ text += f" 📝 {preview}\n\n"
1313
+
1314
+ if not groups and not users:
1315
+ text += "⚠️ هیچ system instruction خاصی (گروهی یا کاربری) تنظیم نشده است."
1316
+
1317
+ await update.message.reply_text(text, parse_mode='Markdown')
1318
+
1319
+ # --- هندلر برای دکمه‌های صفحه‌بندی ---
1320
+ async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
1321
+ """پردازش دکمه‌های صفحه‌بندی لیست کاربران."""
1322
+ query = update.callback_query
1323
+ await query.answer()
1324
+
1325
+ if query.data.startswith("users_list:"):
1326
+ page = int(query.data.split(":")[1])
1327
+ context.args = [str(page)]
1328
+ await admin_users_list(update, context)
1329
+
1330
+ # --- تابع برای پردازش ارسال‌های برنامه‌ریزی شده ---
1331
+ async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
1332
+ """پردازش ارسال‌های برنامه‌ریزی شده و ارسال پیام‌ها در زمان مقرر."""
1333
+ now = datetime.now()
1334
+ broadcasts_to_send_indices = []
1335
+
1336
+ for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
1337
+ if broadcast['status'] == 'pending':
1338
+ broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
1339
+ if broadcast_time <= now:
1340
+ broadcasts_to_send_indices.append(i)
1341
+
1342
+ if not broadcasts_to_send_indices:
1343
+ return
1344
+
1345
+ user_ids = list(data_manager.DATA['users'].keys())
1346
+
1347
+ for index in broadcasts_to_send_indices:
1348
+ broadcast = data_manager.DATA['scheduled_broadcasts'][index]
1349
+ message_text = broadcast['message']
1350
+ total_sent, total_failed = 0, 0
1351
+
1352
+ for user_id_str in user_ids:
1353
+ try:
1354
+ await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
1355
+ total_sent += 1
1356
+ await asyncio.sleep(0.05)
1357
+ except TelegramError as e:
1358
+ logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
1359
+ total_failed += 1
1360
+
1361
+ # به‌روزرسانی وضعیت ارسال
1362
+ data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
1363
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
1364
+ data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
1365
+ data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
1366
+
1367
+ logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
1368
+
1369
+ data_manager.save_data()
1370
+
1371
+ # --- تابع راه‌اندازی هندلرها ---
1372
+ def setup_admin_handlers(application):
1373
+ """هندلرهای پنل ادمین را به اپلیکیشن اضافه می‌کند."""
1374
+ # هندلرهای اصلی
1375
+ application.add_handler(CommandHandler("commands", admin_commands))
1376
+ application.add_handler(CommandHandler("stats", admin_stats))
1377
+ application.add_handler(CommandHandler("broadcast", admin_broadcast))
1378
+ application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
1379
+ application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
1380
+ application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
1381
+ application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
1382
+ application.add_handler(CommandHandler("ban", admin_ban))
1383
+ application.add_handler(CommandHandler("unban", admin_unban))
1384
+ application.add_handler(CommandHandler("direct_message", admin_direct_message))
1385
+ application.add_handler(CommandHandler("user_info", admin_userinfo))
1386
+ application.add_handler(CommandHandler("logs", admin_logs))
1387
+ application.add_handler(CommandHandler("logs_file", admin_logs_file))
1388
+ application.add_handler(CommandHandler("users_list", admin_users_list))
1389
+ application.add_handler(CommandHandler("user_search", admin_user_search))
1390
+ application.add_handler(CommandHandler("backup", admin_backup))
1391
+ application.add_handler(CommandHandler("export_csv", admin_export_csv))
1392
+ application.add_handler(CommandHandler("maintenance", admin_maintenance))
1393
+ application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
1394
+ application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
1395
+ application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
1396
+ application.add_handler(CommandHandler("response_stats", admin_response_stats))
1397
+ application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
1398
+ application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
1399
+ application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
1400
+ application.add_handler(CommandHandler("system_info", admin_system_info))
1401
+ application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
1402
+
1403
+ # هندلرهای مدیریت context
1404
+ application.add_handler(CommandHandler("clear_context", admin_clear_context))
1405
+ application.add_handler(CommandHandler("view_context", admin_view_context))
1406
+ application.add_handler(CommandHandler("view_replies", admin_view_replies))
1407
+
1408
+ # هندلرهای جدید برای مدیریت گروه‌ها
1409
+ application.add_handler(CommandHandler("set_context_mode", admin_set_context_mode))
1410
+ application.add_handler(CommandHandler("group_info", admin_group_info))
1411
+ application.add_handler(CommandHandler("clear_group_context", admin_clear_group_context))
1412
+ application.add_handler(CommandHandler("memory_status", admin_memory_status))
1413
+
1414
+ # هندلرهای system instruction
1415
+ application.add_handler(CommandHandler("set_global_system", admin_set_global_system))
1416
+ application.add_handler(CommandHandler("set_group_system", admin_set_group_system))
1417
+ application.add_handler(CommandHandler("set_user_system", admin_set_user_system))
1418
+ application.add_handler(CommandHandler("list_system_instructions", admin_list_system_instructions))
1419
+
1420
+ # هندلر برای دکمه‌های صفحه‌بندی
1421
+ application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
1422
+
1423
+ # شروع وظیفه دوره‌ای برای بررسی ارسال‌های برنامه‌ریزی شده
1424
+ application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
1425
+
1426
+ logger.info("Admin panel handlers have been set up.")
BOT/render-main/data_manager.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # data_manager.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ from datetime import datetime, timedelta
7
+ import tiktoken
8
+
9
+ # --- تنظیمات مسیر فایل‌ها ---
10
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
11
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
12
+ LOG_FILE = os.path.join(BASE_DIR, "bot.log")
13
+
14
+ # --- کش داده‌های گلوبال ---
15
+ DATA = {
16
+ "users": {},
17
+ "groups": {},
18
+ "banned_users": set(),
19
+ "stats": {
20
+ "total_messages": 0,
21
+ "total_users": 0,
22
+ "total_groups": 0,
23
+ "avg_response_time": 0.0,
24
+ "max_response_time": 0.0,
25
+ "min_response_time": float('inf'),
26
+ "total_responses": 0
27
+ },
28
+ "welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
29
+ "group_welcome_message": "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید",
30
+ "goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
31
+ "maintenance_mode": False,
32
+ "blocked_words": [],
33
+ "scheduled_broadcasts": [],
34
+ "bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
35
+ "context_mode": "separate",
36
+ "system_instructions": {
37
+ "global": "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد. از کلمات فارسی صحیح استفاده کنید و در صورت نیاز توضیحات کامل ارائه دهید.",
38
+ "groups": {},
39
+ "users": {}
40
+ }
41
+ }
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # --- توابع کمکی ---
46
+ def count_tokens(text: str) -> int:
47
+ """شمارش تعداد توکن‌های متن با استفاده از tokenizer"""
48
+ try:
49
+ encoding = tiktoken.get_encoding("cl100k_base")
50
+ return len(encoding.encode(text))
51
+ except Exception as e:
52
+ logger.warning(f"Error counting tokens: {e}, using fallback")
53
+ return max(1, len(text) // 4)
54
+
55
+ def load_data():
56
+ """داده‌ها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره می‌کند."""
57
+ global DATA
58
+ try:
59
+ if not os.path.exists(DATA_FILE):
60
+ logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد می‌شود.")
61
+ save_data()
62
+ return
63
+
64
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
65
+ loaded_data = json.load(f)
66
+ loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
67
+
68
+ # اطمینان از وجود کلیدهای جدید
69
+ if 'groups' not in loaded_data: loaded_data['groups'] = {}
70
+ if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'separate'
71
+ if 'group_welcome_message' not in loaded_data:
72
+ loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..."
73
+ if 'total_groups' not in loaded_data.get('stats', {}):
74
+ if 'stats' not in loaded_data: loaded_data['stats'] = {}
75
+ loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {}))
76
+
77
+ # تبدیل اعضای گروه از list به set
78
+ for group_id in loaded_data.get('groups', {}):
79
+ if 'members' in loaded_data['groups'][group_id]:
80
+ # اگر members یک list است، آن را به set تبدیل کن
81
+ if isinstance(loaded_data['groups'][group_id]['members'], list):
82
+ loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members'])
83
+ elif not isinstance(loaded_data['groups'][group_id]['members'], set):
84
+ # اگر نه list است نه set، آن را set خالی کن
85
+ loaded_data['groups'][group_id]['members'] = set()
86
+ else:
87
+ loaded_data['groups'][group_id]['members'] = set()
88
+
89
+ # اطمینان از وجود context برای گروه‌های قدیمی
90
+ for group_id in loaded_data.get('groups', {}):
91
+ if 'context' not in loaded_data['groups'][group_id]:
92
+ loaded_data['groups'][group_id]['context'] = []
93
+
94
+ # اطمینان از وجود context برای کاربران قدیمی
95
+ for user_id in loaded_data.get('users', {}):
96
+ if 'context' not in loaded_data['users'][user_id]:
97
+ loaded_data['users'][user_id]['context'] = []
98
+
99
+ # اطمینان از وجود کلیدهای آمار پاسخگویی
100
+ if 'stats' in loaded_data:
101
+ stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses']
102
+ for key in stats_keys:
103
+ if key not in loaded_data['stats']:
104
+ if key == 'min_response_time':
105
+ loaded_data['stats'][key] = float('inf')
106
+ else:
107
+ loaded_data['stats'][key] = 0.0
108
+
109
+ # اطمینان از وجود system_instructions
110
+ if 'system_instructions' not in loaded_data:
111
+ loaded_data['system_instructions'] = {
112
+ 'global': DATA['system_instructions']['global'],
113
+ 'groups': {},
114
+ 'users': {}
115
+ }
116
+
117
+ DATA.update(loaded_data)
118
+ logger.info(f"داده‌ها با موفقیت از {DATA_FILE} بارگذاری شدند.")
119
+
120
+ except json.JSONDecodeError as e:
121
+ logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
122
+ except Exception as e:
123
+ logger.error(f"خطای غیرمنتظره هنگام بارگذاری داده‌ها: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
124
+
125
+ def save_data():
126
+ """کش گلوبال داده‌ها را در فایل JSON ذخیره می‌کند."""
127
+ global DATA
128
+ try:
129
+ data_to_save = DATA.copy()
130
+ data_to_save['banned_users'] = list(DATA['banned_users'])
131
+
132
+ # تبدیل set اعضای گروه به list برای ذخیره JSON
133
+ for group_id in data_to_save.get('groups', {}):
134
+ if 'members' in data_to_save['groups'][group_id]:
135
+ # اگر members یک set است، آن را به list تبدیل کن
136
+ if isinstance(data_to_save['groups'][group_id]['members'], set):
137
+ data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members'])
138
+ elif not isinstance(data_to_save['groups'][group_id]['members'], list):
139
+ # اگر نه set است نه list، آن را list خالی کن
140
+ data_to_save['groups'][group_id]['members'] = []
141
+
142
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
143
+ json.dump(data_to_save, f, indent=4, ensure_ascii=False)
144
+ logger.debug(f"داده‌ها با موفقیت در {DATA_FILE} ذخیره شدند.")
145
+ except Exception as e:
146
+ logger.error(f"خطای مهلک: امکان ذخیره داده‌ها در {DATA_FILE} وجود ندارد. خطا: {e}")
147
+
148
+ # --- توابع مدیریت کاربران ---
149
+ def update_user_stats(user_id: int, user):
150
+ """آمار کاربر را پس از هر پیام به‌روز کرده و داده‌ها را ذخیره می‌کند."""
151
+ global DATA
152
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
153
+ user_id_str = str(user_id)
154
+
155
+ if user_id_str not in DATA['users']:
156
+ DATA['users'][user_id_str] = {
157
+ 'first_name': user.first_name,
158
+ 'username': user.username,
159
+ 'first_seen': now_str,
160
+ 'message_count': 0,
161
+ 'context': []
162
+ }
163
+ DATA['stats']['total_users'] += 1
164
+ logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
165
+
166
+ DATA['users'][user_id_str]['last_seen'] = now_str
167
+ DATA['users'][user_id_str]['message_count'] += 1
168
+ DATA['stats']['total_messages'] += 1
169
+
170
+ save_data()
171
+
172
+ def update_response_stats(response_time: float):
173
+ """آمار زمان پاسخگویی را به‌روز می‌کند."""
174
+ global DATA
175
+
176
+ if DATA['stats']['total_responses'] == 0:
177
+ DATA['stats']['min_response_time'] = response_time
178
+
179
+ DATA['stats']['total_responses'] += 1
180
+
181
+ # محاسبه میانگین جدید
182
+ current_avg = DATA['stats']['avg_response_time']
183
+ total_responses = DATA['stats']['total_responses']
184
+ new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
185
+ DATA['stats']['avg_response_time'] = new_avg
186
+
187
+ # به‌روزرسانی حداکثر و حداقل زمان پاسخگویی
188
+ if response_time > DATA['stats']['max_response_time']:
189
+ DATA['stats']['max_response_time'] = response_time
190
+
191
+ if response_time < DATA['stats']['min_response_time']:
192
+ DATA['stats']['min_response_time'] = response_time
193
+
194
+ save_data()
195
+
196
+ # --- توابع مدیریت مسدودیت ---
197
+ def is_user_banned(user_id: int) -> bool:
198
+ """بررسی می‌کند آیا کاربر مسدود شده است یا خیر."""
199
+ return user_id in DATA['banned_users']
200
+
201
+ def ban_user(user_id: int):
202
+ """کاربر را مسدود کرده و ذخیره می‌کند."""
203
+ DATA['banned_users'].add(user_id)
204
+ save_data()
205
+
206
+ def unban_user(user_id: int):
207
+ """مسدودیت کاربر را برداشته و ذخیره می‌کند."""
208
+ DATA['banned_users'].discard(user_id)
209
+ save_data()
210
+
211
+ def contains_blocked_words(text: str) -> bool:
212
+ """بررسی می‌کند آیا متن حاوی کلمات مسدود شده است یا خیر."""
213
+ if not DATA['blocked_words']:
214
+ return False
215
+
216
+ text_lower = text.lower()
217
+ for word in DATA['blocked_words']:
218
+ if word in text_lower:
219
+ return True
220
+
221
+ return False
222
+
223
+ # --- توابع مدیریت کاربران و گروه‌ها ---
224
+ def get_active_users(days: int) -> list:
225
+ """لیست کاربران فعال در بازه زمانی مشخص را برمی‌گرداند."""
226
+ now = datetime.now()
227
+ cutoff_date = now - timedelta(days=days)
228
+
229
+ active_users = []
230
+ for user_id, user_info in DATA['users'].items():
231
+ if 'last_seen' in user_info:
232
+ try:
233
+ last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
234
+ if last_seen >= cutoff_date:
235
+ active_users.append(int(user_id))
236
+ except ValueError:
237
+ continue
238
+
239
+ return active_users
240
+
241
+ def get_users_by_message_count(min_count: int) -> list:
242
+ """لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمی‌گرداند."""
243
+ users = []
244
+ for user_id, user_info in DATA['users'].items():
245
+ if user_info.get('message_count', 0) >= min_count:
246
+ users.append(int(user_id))
247
+
248
+ return users
249
+
250
+ # --- توابع مدیریت context کاربران ---
251
+ def add_to_user_context(user_id: int, role: str, content: str):
252
+ """اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن"""
253
+ add_to_user_context_with_reply(user_id, role, content, None)
254
+
255
+ def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None):
256
+ """اضافه کردن پیام به context کاربر با اطلاعات ریپلای"""
257
+ user_id_str = str(user_id)
258
+
259
+ if user_id_str not in DATA['users']:
260
+ return
261
+
262
+ if 'context' not in DATA['users'][user_id_str]:
263
+ DATA['users'][user_id_str]['context'] = []
264
+
265
+ # اضافه کردن پیام جدید
266
+ message = {
267
+ 'role': role,
268
+ 'content': content,
269
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
270
+ 'has_reply': False
271
+ }
272
+
273
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
274
+ message['has_reply'] = True
275
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
276
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
277
+ message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
278
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
279
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
280
+
281
+ DATA['users'][user_id_str]['context'].append(message)
282
+
283
+ # محدود کردن context به 8192 توکن
284
+ trim_user_context(user_id, max_tokens=8192)
285
+
286
+ save_data()
287
+
288
+ def trim_user_context(user_id: int, max_tokens: int = 8192):
289
+ """کوتاه کردن context کاربر به تعداد توکن مشخص"""
290
+ user_id_str = str(user_id)
291
+
292
+ if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
293
+ return
294
+
295
+ context = DATA['users'][user_id_str]['context']
296
+
297
+ if not context:
298
+ return
299
+
300
+ # محاسبه توکن‌های کل
301
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
302
+
303
+ # حذف قدیمی‌ترین پیام‌ها تا زمانی که توکن‌ها زیر حد مجاز باشد
304
+ while total_tokens > max_tokens and len(context) > 1:
305
+ removed_message = context.pop(0)
306
+ total_tokens -= count_tokens(removed_message['content'])
307
+
308
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
309
+ if total_tokens > max_tokens and context:
310
+ last_message = context[-1]
311
+ content = last_message['content']
312
+
313
+ tokens = count_tokens(content)
314
+ if tokens > max_tokens:
315
+ context.pop()
316
+ else:
317
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
318
+ words = content.split()
319
+ if len(words) > 1:
320
+ content = ' '.join(words[:-1])
321
+ else:
322
+ content = content[:-1] if len(content) > 1 else ''
323
+ tokens = count_tokens(content)
324
+
325
+ if content:
326
+ context[-1]['content'] = content
327
+ else:
328
+ context.pop()
329
+
330
+ save_data()
331
+
332
+ def get_user_context(user_id: int) -> list:
333
+ """دریافت context کاربر"""
334
+ user_id_str = str(user_id)
335
+
336
+ if user_id_str not in DATA['users']:
337
+ return []
338
+
339
+ return DATA['users'][user_id_str].get('context', [])
340
+
341
+ def clear_user_context(user_id: int):
342
+ """پاک کردن context کاربر"""
343
+ user_id_str = str(user_id)
344
+
345
+ if user_id_str in DATA['users']:
346
+ if 'context' in DATA['users'][user_id_str]:
347
+ DATA['users'][user_id_str]['context'] = []
348
+ save_data()
349
+ logger.info(f"Context cleared for user {user_id}")
350
+
351
+ def get_context_summary(user_id: int) -> str:
352
+ """خلاصه‌ای از context کاربر"""
353
+ context = get_user_context(user_id)
354
+ if not context:
355
+ return "بدون تاریخچه"
356
+
357
+ total_messages = len(context)
358
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
359
+
360
+ # تعداد ریپلای‌ها
361
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
362
+
363
+ # نمایش آخرین پیام
364
+ last_message = context[-1] if context else {}
365
+ last_content = last_message.get('content', '')[:50]
366
+ if len(last_message.get('content', '')) > 50:
367
+ last_content += "..."
368
+
369
+ return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}"
370
+
371
+ def get_context_for_api(user_id: int) -> list:
372
+ """فرمت context برای ارسال به API"""
373
+ context = get_user_context(user_id)
374
+
375
+ api_context = []
376
+ for msg in context:
377
+ api_context.append({
378
+ 'role': msg['role'],
379
+ 'content': msg['content']
380
+ })
381
+
382
+ return api_context
383
+
384
+ def get_context_token_count(user_id: int) -> int:
385
+ """تعداد کل توکن‌های context کاربر"""
386
+ context = get_user_context(user_id)
387
+ return sum(count_tokens(msg['content']) for msg in context)
388
+
389
+ # --- توابع مدیریت گروه‌ها ---
390
+ def update_group_stats(chat_id: int, chat, user_id: int = None):
391
+ """آمار گروه را به‌روز کرده و داده‌ها را ذخیره می‌کند."""
392
+ global DATA
393
+ now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
394
+ chat_id_str = str(chat_id)
395
+
396
+ if chat_id_str not in DATA['groups']:
397
+ DATA['groups'][chat_id_str] = {
398
+ 'title': chat.title if hasattr(chat, 'title') else 'Private Group',
399
+ 'type': chat.type,
400
+ 'first_seen': now_str,
401
+ 'message_count': 0,
402
+ 'members': set(),
403
+ 'context': []
404
+ }
405
+ DATA['stats']['total_groups'] += 1
406
+ logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})")
407
+
408
+ DATA['groups'][chat_id_str]['last_seen'] = now_str
409
+ DATA['groups'][chat_id_str]['message_count'] += 1
410
+
411
+ # اضافه کردن کاربر به لیست اعضای گروه
412
+ if user_id is not None:
413
+ # اطمینان از اینکه members یک set است
414
+ if 'members' not in DATA['groups'][chat_id_str]:
415
+ DATA['groups'][chat_id_str]['members'] = set()
416
+ elif isinstance(DATA['groups'][chat_id_str]['members'], list):
417
+ # اگر members یک list است، آن را به set تبدیل کن
418
+ DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members'])
419
+
420
+ # اکنون اضافه کردن کاربر
421
+ DATA['groups'][chat_id_str]['members'].add(user_id)
422
+
423
+ save_data()
424
+
425
+ def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None):
426
+ """اضافه کردن پیام به context گروه و محدود کردن به 8192 توکن"""
427
+ add_to_group_context_with_reply(chat_id, role, content, user_name, None)
428
+
429
+ def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None):
430
+ """اضافه کردن پیام به context گروه با اطلاعات ریپلای"""
431
+ chat_id_str = str(chat_id)
432
+
433
+ if chat_id_str not in DATA['groups']:
434
+ return
435
+
436
+ if 'context' not in DATA['groups'][chat_id_str]:
437
+ DATA['groups'][chat_id_str]['context'] = []
438
+
439
+ # اضافه کردن نام کاربر به محتوا اگر مشخص باشد
440
+ if user_name and role == 'user':
441
+ content_with_name = f"{user_name}: {content}"
442
+ else:
443
+ content_with_name = content
444
+
445
+ # اضافه کردن پیام جدید با اطلاعات ریپلای
446
+ message = {
447
+ 'role': role,
448
+ 'content': content_with_name if role == 'user' else content,
449
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
450
+ 'user_name': user_name if role == 'user' else None,
451
+ 'has_reply': False
452
+ }
453
+
454
+ if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
455
+ message['has_reply'] = True
456
+ message['reply_to_user_id'] = reply_info.get('replied_user_id')
457
+ message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
458
+ message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
459
+ message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
460
+ message['reply_timestamp'] = reply_info.get('timestamp', time.time())
461
+
462
+ DATA['groups'][chat_id_str]['context'].append(message)
463
+
464
+ # محدود کردن context به 16384 توکن
465
+ trim_group_context(chat_id, max_tokens=16384)
466
+
467
+ save_data()
468
+
469
+ def optimize_group_context(chat_id: int):
470
+ """بهینه‌سازی context گروه برای حفظ مهم‌ترین پیام‌ها"""
471
+ chat_id_str = str(chat_id)
472
+
473
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
474
+ return
475
+
476
+ context = DATA['groups'][chat_id_str]['context']
477
+ if len(context) <= 10:
478
+ return
479
+
480
+ # محاسبه اهمیت هر پیام بر اساس عوامل مختلف
481
+ scored_messages = []
482
+ for i, msg in enumerate(context):
483
+ score = 0
484
+
485
+ # امتیاز بر اساس طول
486
+ content_length = len(msg['content'])
487
+ score += min(content_length / 100, 10)
488
+
489
+ # امتیاز بر اساس تازگی
490
+ recency = len(context) - i
491
+ score += min(recency / 10, 20)
492
+
493
+ # امتیاز بیشتر برای پاسخ‌های هوش مصنوعی
494
+ if msg['role'] == 'assistant':
495
+ score += 15
496
+
497
+ # امتیاز بیشتر برای پیام‌های دارای ریپلای (مهم‌تر هستند)
498
+ if msg.get('has_reply', False):
499
+ score += 10
500
+
501
+ # امتیاز منفی برای پیام‌های کوتاه و کم‌محتوا
502
+ if content_length < 20:
503
+ score -= 5
504
+
505
+ scored_messages.append((score, msg))
506
+
507
+ # مرتب‌سازی بر اساس امتیاز
508
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
509
+
510
+ # حفظ 70% از پیام‌های با بالاترین امتیاز
511
+ keep_count = int(len(scored_messages) * 0.7)
512
+ kept_messages = [msg for _, msg in scored_messages[:keep_count]]
513
+
514
+ # مرتب‌سازی مجدد بر اساس زمان
515
+ kept_messages.sort(key=lambda x: x.get('timestamp', ''))
516
+
517
+ DATA['groups'][chat_id_str]['context'] = kept_messages
518
+ save_data()
519
+
520
+ logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages")
521
+
522
+ def trim_group_context(chat_id: int, max_tokens: int = 16384):
523
+ """کوتاه کردن context گروه به تعداد توکن مشخص"""
524
+ chat_id_str = str(chat_id)
525
+
526
+ if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
527
+ return
528
+
529
+ context = DATA['groups'][chat_id_str]['context']
530
+
531
+ if not context:
532
+ return
533
+
534
+ # محاسبه توکن‌های کل
535
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
536
+
537
+ # اگر تعداد توکن‌ها بیش از حد مجاز است، ابتدا بهینه‌سازی کن
538
+ if total_tokens > max_tokens * 1.5:
539
+ optimize_group_context(chat_id)
540
+ context = DATA['groups'][chat_id_str]['context']
541
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
542
+
543
+ # حذف قدیمی‌ترین پیام‌ها
544
+ while total_tokens > max_tokens and len(context) > 1:
545
+ removed_message = context.pop(0)
546
+ total_tokens -= count_tokens(removed_message['content'])
547
+
548
+ # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
549
+ if total_tokens > max_tokens and context:
550
+ last_message = context[-1]
551
+ content = last_message['content']
552
+
553
+ tokens = count_tokens(content)
554
+ if tokens > max_tokens:
555
+ context.pop()
556
+ else:
557
+ while tokens > (max_tokens - (total_tokens - tokens)) and content:
558
+ words = content.split()
559
+ if len(words) > 1:
560
+ content = ' '.join(words[:-1])
561
+ else:
562
+ content = content[:-1] if len(content) > 1 else ''
563
+ tokens = count_tokens(content)
564
+
565
+ if content:
566
+ context[-1]['content'] = content
567
+ else:
568
+ context.pop()
569
+
570
+ save_data()
571
+
572
+ def get_group_context(chat_id: int) -> list:
573
+ """دریافت context گروه"""
574
+ chat_id_str = str(chat_id)
575
+
576
+ if chat_id_str not in DATA['groups']:
577
+ return []
578
+
579
+ return DATA['groups'][chat_id_str].get('context', [])
580
+
581
+ def get_context_for_api_group(chat_id: int) -> list:
582
+ """فرمت context گروه برای ارسال به API"""
583
+ context = get_group_context(chat_id)
584
+
585
+ api_context = []
586
+ for msg in context:
587
+ api_context.append({
588
+ 'role': msg['role'],
589
+ 'content': msg['content']
590
+ })
591
+
592
+ return api_context
593
+
594
+ def clear_group_context(chat_id: int):
595
+ """پاک کردن context گروه"""
596
+ chat_id_str = str(chat_id)
597
+
598
+ if chat_id_str in DATA['groups']:
599
+ if 'context' in DATA['groups'][chat_id_str]:
600
+ DATA['groups'][chat_id_str]['context'] = []
601
+ save_data()
602
+ logger.info(f"Context cleared for group {chat_id}")
603
+
604
+ def get_group_context_summary(chat_id: int) -> str:
605
+ """خلاصه‌ای از context گروه"""
606
+ context = get_group_context(chat_id)
607
+ if not context:
608
+ return "بدون تاریخچه"
609
+
610
+ total_messages = len(context)
611
+ total_tokens = sum(count_tokens(msg['content']) for msg in context)
612
+
613
+ # تعداد ریپلای‌ها
614
+ reply_count = sum(1 for msg in context if msg.get('has_reply', False))
615
+
616
+ last_message = context[-1] if context else {}
617
+ last_content = last_message.get('content', '')[:50]
618
+ if len(last_message.get('content', '')) > 50:
619
+ last_content += "..."
620
+
621
+ return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('user_name', last_message.get('role', ''))}: {last_content}"
622
+
623
+ # --- توابع ترکیبی (User + Group) ---
624
+ def add_to_hybrid_context(user_id: int, chat_id: int, role: str, content: str, user_name: str = None):
625
+ """
626
+ اضافه کردن پیام به context ترکیبی
627
+ هم در context کاربر و هم در context گروه ذخیره می‌شود
628
+ """
629
+ # ذخیره در context کاربر
630
+ add_to_user_context(user_id, role, content)
631
+
632
+ # ذخیره در context گروه
633
+ add_to_group_context(chat_id, role, content, user_name)
634
+
635
+ def add_to_hybrid_context_with_reply(user_id: int, chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None):
636
+ """
637
+ اضافه کردن پیام به context ترکیبی با اطلاعات ریپلای
638
+ هم در context کاربر و هم در context گروه ذخیره می‌شود
639
+ """
640
+ # ذخیره در context کاربر
641
+ add_to_user_context_with_reply(user_id, role, content, reply_info)
642
+
643
+ # ذخیره در context گروه
644
+ add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info)
645
+
646
+ def get_hybrid_context_for_api(user_id: int, chat_id: int) -> list:
647
+ """
648
+ دریافت context ترکیبی برای ارسال به API
649
+ اولویت با context گروه است، اما از context کاربر هم استفاده می‌کند
650
+ """
651
+ group_context = get_context_for_api_group(chat_id)
652
+ user_context = get_context_for_api(user_id)
653
+
654
+ # ترکیب context‌ها
655
+ combined_context = []
656
+
657
+ # ابتدا context گروه
658
+ combined_context.extend(group_context)
659
+
660
+ # سپس context کاربر - فقط پیام‌های اخیر کاربر
661
+ recent_user_messages = [msg for msg in user_context[-3:] if msg['role'] == 'user']
662
+ combined_context.extend(recent_user_messages)
663
+
664
+ return combined_context
665
+
666
+ # --- توابع مدیریت حالت context ---
667
+ def get_context_mode() -> str:
668
+ """دریافت حالت فعلی context"""
669
+ return DATA.get('context_mode', 'separate')
670
+
671
+ def set_context_mode(mode: str):
672
+ """تنظیم حالت context"""
673
+ valid_modes = ['separate', 'group_shared', 'hybrid']
674
+ if mode in valid_modes:
675
+ DATA['context_mode'] = mode
676
+ save_data()
677
+ logger.info(f"Context mode changed to: {mode}")
678
+ return True
679
+ return False
680
+
681
+ # --- توابع مدیریت system instructions ---
682
+ def get_system_instruction(user_id: int = None, chat_id: int = None) -> str:
683
+ """دریافت system instruction مناسب برای کاربر/گروه"""
684
+ # اولویت: کاربر > گروه > سراسری
685
+ user_id_str = str(user_id) if user_id else None
686
+ chat_id_str = str(chat_id) if chat_id else None
687
+
688
+ # بررسی برای کاربر
689
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
690
+ instruction_data = DATA['system_instructions']['users'][user_id_str]
691
+ if instruction_data.get('enabled', True):
692
+ return instruction_data.get('instruction', '')
693
+
694
+ # بررسی برای گروه
695
+ if chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
696
+ instruction_data = DATA['system_instructions']['groups'][chat_id_str]
697
+ if instruction_data.get('enabled', True):
698
+ return instruction_data.get('instruction', '')
699
+
700
+ # بازگشت به حالت سراسری
701
+ return DATA['system_instructions'].get('global', '')
702
+
703
+ def set_global_system_instruction(instruction: str) -> bool:
704
+ """تنظیم system instruction سراسری"""
705
+ DATA['system_instructions']['global'] = instruction
706
+ save_data()
707
+ return True
708
+
709
+ def set_group_system_instruction(chat_id: int, instruction: str, set_by_user_id: int) -> bool:
710
+ """تنظیم system instruction برای گروه"""
711
+ chat_id_str = str(chat_id)
712
+ DATA['system_instructions']['groups'][chat_id_str] = {
713
+ 'instruction': instruction,
714
+ 'set_by': set_by_user_id,
715
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
716
+ 'enabled': True
717
+ }
718
+ save_data()
719
+ return True
720
+
721
+ def set_user_system_instruction(user_id: int, instruction: str, set_by_user_id: int) -> bool:
722
+ """تنظیم system instruction برای کاربر"""
723
+ user_id_str = str(user_id)
724
+ DATA['system_instructions']['users'][user_id_str] = {
725
+ 'instruction': instruction,
726
+ 'set_by': set_by_user_id,
727
+ 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
728
+ 'enabled': True
729
+ }
730
+ save_data()
731
+ return True
732
+
733
+ def remove_group_system_instruction(chat_id: int) -> bool:
734
+ """حذف system instruction گروه"""
735
+ chat_id_str = str(chat_id)
736
+ if chat_id_str in DATA['system_instructions']['groups']:
737
+ del DATA['system_instructions']['groups'][chat_id_str]
738
+ save_data()
739
+ return True
740
+ return False
741
+
742
+ def remove_user_system_instruction(user_id: int) -> bool:
743
+ """حذف system instruction کاربر"""
744
+ user_id_str = str(user_id)
745
+ if user_id_str in DATA['system_instructions']['users']:
746
+ del DATA['system_instructions']['users'][user_id_str]
747
+ save_data()
748
+ return True
749
+ return False
750
+
751
+ def toggle_group_system_instruction(chat_id: int, enabled: bool) -> bool:
752
+ """فعال/غیرفعال کردن system instruction گروه"""
753
+ chat_id_str = str(chat_id)
754
+ if chat_id_str in DATA['system_instructions']['groups']:
755
+ DATA['system_instructions']['groups'][chat_id_str]['enabled'] = enabled
756
+ save_data()
757
+ return True
758
+ return False
759
+
760
+ def toggle_user_system_instruction(user_id: int, enabled: bool) -> bool:
761
+ """فعال/غیرفعال کردن system instruction کاربر"""
762
+ user_id_str = str(user_id)
763
+ if user_id_str in DATA['system_instructions']['users']:
764
+ DATA['system_instructions']['users'][user_id_str]['enabled'] = enabled
765
+ save_data()
766
+ return True
767
+ return False
768
+
769
+ def get_system_instruction_info(user_id: int = None, chat_id: int = None) -> dict:
770
+ """دریافت اطلاعات system instruction"""
771
+ user_id_str = str(user_id) if user_id else None
772
+ chat_id_str = str(chat_id) if chat_id else None
773
+
774
+ result = {
775
+ 'has_instruction': False,
776
+ 'type': 'global',
777
+ 'instruction': DATA['system_instructions'].get('global', ''),
778
+ 'details': None
779
+ }
780
+
781
+ if user_id_str and user_id_str in DATA['system_instructions']['users']:
782
+ user_data = DATA['system_instructions']['users'][user_id_str]
783
+ result.update({
784
+ 'has_instruction': True,
785
+ 'type': 'user',
786
+ 'instruction': user_data.get('instruction', ''),
787
+ 'details': user_data
788
+ })
789
+ elif chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
790
+ group_data = DATA['system_instructions']['groups'][chat_id_str]
791
+ result.update({
792
+ 'has_instruction': True,
793
+ 'type': 'group',
794
+ 'instruction': group_data.get('instruction', ''),
795
+ 'details': group_data
796
+ })
797
+
798
+ return result
799
+
800
+ # بارگذاری اولیه داده‌ها
801
+ load_data()
802
+
803
+ # برای جلوگیری از خطای time در توابع
804
+ import time
BOT/render-main/fix_data.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fix_data.py
2
+ import json
3
+ import os
4
+
5
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
6
+ DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
7
+
8
+ def fix_data_file():
9
+ """رفع مشکلات فایل داده‌های موجود"""
10
+ if not os.path.exists(DATA_FILE):
11
+ print(f"فایل داده در {DATA_FILE} یافت نشد.")
12
+ return
13
+
14
+ try:
15
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
16
+ data = json.load(f)
17
+
18
+ # رفع مشکل banned_users
19
+ if 'banned_users' in data and isinstance(data['banned_users'], list):
20
+ data['banned_users'] = list(set(data['banned_users'])) # حذف duplicates
21
+
22
+ # رفع مشکل groups و members
23
+ if 'groups' in data:
24
+ for group_id, group_info in data['groups'].items():
25
+ # رفع مشکل members
26
+ if 'members' in group_info:
27
+ if isinstance(group_info['members'], list):
28
+ # تبدیل list به set و سپس دوباره به list (حذف duplicates)
29
+ members_set = set(group_info['members'])
30
+ group_info['members'] = list(members_set)
31
+ elif isinstance(group_info['members'], set):
32
+ # اگر set است، به list تبدیل کن
33
+ group_info['members'] = list(group_info['members'])
34
+ else:
35
+ # اگر نه list است نه set، آن را list خالی کن
36
+ group_info['members'] = []
37
+
38
+ # اطمینان از وجود کلیدهای ضروری
39
+ if 'context' not in group_info:
40
+ group_info['context'] = []
41
+ if 'title' not in group_info:
42
+ group_info['title'] = 'Unknown Group'
43
+ if 'type' not in group_info:
44
+ group_info['type'] = 'group'
45
+
46
+ # رفع مشکل users
47
+ if 'users' in data:
48
+ for user_id, user_info in data['users'].items():
49
+ if 'context' not in user_info:
50
+ user_info['context'] = []
51
+
52
+ # ذخیره فایل اصلاح شده
53
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
54
+ json.dump(data, f, indent=4, ensure_ascii=False)
55
+
56
+ print(f"فایل داده در {DATA_FILE} با موفقیت اصلاح شد.")
57
+
58
+ # نمایش آمار
59
+ print("\n📊 آمار فایل اصلاح شده:")
60
+ print(f"تعداد کاربران: {len(data.get('users', {}))}")
61
+ print(f"تعداد گروه‌ها: {len(data.get('groups', {}))}")
62
+ print(f"کاربران مسدود شده: {len(data.get('banned_users', []))}")
63
+
64
+ # بررسی groups
65
+ groups_with_member_issues = 0
66
+ for group_id, group_info in data.get('groups', {}).items():
67
+ if 'members' in group_info and not isinstance(group_info['members'], list):
68
+ groups_with_member_issues += 1
69
+
70
+ if groups_with_member_issues > 0:
71
+ print(f"⚠️ {groups_with_member_issues} گروه دارای مشکل در members هستند.")
72
+ else:
73
+ print("✅ همه groups به درستی اصلاح شدند.")
74
+
75
+ except Exception as e:
76
+ print(f"خطا در اصلاح فایل داده: {e}")
77
+
78
+ if __name__ == "__main__":
79
+ fix_data_file()
BOT/render-main/keep_alive.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import threading
3
+ import time
4
+
5
+ def ping_service():
6
+ """ارسال درخواست پینگ به سرویس برای نگه داشتن آن فعال."""
7
+ url = "https://render-telegram-bot-2-bmin.onrender.com"
8
+ while True:
9
+ try:
10
+ requests.get(url)
11
+ print(f"Pinged {url} to keep service alive")
12
+ except Exception as e:
13
+ print(f"Error pinging service: {e}")
14
+
15
+ # هر 14 دقیقه یک بار پینگ بزن (زیر 15 دقیقه برای جلوگیری از خاموشی)
16
+ time.sleep(5 * 60)
17
+
18
+ # شروع ترد پینگ در پس‌زمینه
19
+ def start_keep_alive():
20
+ """شروع سرویس نگه داشتن ربات فعال."""
21
+ thread = threading.Thread(target=ping_service)
22
+ thread.daemon = True
23
+ thread.start()
BOT/render-main/main.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+
3
+ import os
4
+ import logging
5
+ import asyncio
6
+ import httpx
7
+ import time
8
+ from telegram import Update
9
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
10
+ from openai import AsyncOpenAI
11
+ from keep_alive import start_keep_alive
12
+
13
+ # وارد کردن مدیر داده‌ها و پنل ادمین
14
+ import data_manager
15
+ import admin_panel
16
+ import system_instruction_handlers
17
+
18
+ # شروع سرویس نگه داشتن ربات فعال
19
+ start_keep_alive()
20
+
21
+ # --- بهبود لاگینگ ---
22
+ logging.basicConfig(
23
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
24
+ level=logging.INFO,
25
+ filename=data_manager.LOG_FILE,
26
+ filemode='a'
27
+ )
28
+ logger = logging.getLogger(__name__)
29
+
30
+ try:
31
+ with open(data_manager.LOG_FILE, 'a') as f:
32
+ f.write("")
33
+ except Exception as e:
34
+ print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
35
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
36
+
37
+ # --- ایجاد یک کلاینت HTTP بهینه‌سازی‌شده ---
38
+ http_client = httpx.AsyncClient(
39
+ http2=True,
40
+ limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
41
+ timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
42
+ )
43
+
44
+ # کلاینت OpenAI (HuggingFace)
45
+ client = AsyncOpenAI(
46
+ base_url="https://router.huggingface.co/v1",
47
+ api_key=os.environ["HF_TOKEN"],
48
+ http_client=http_client
49
+ )
50
+
51
+ # --- دیکشنری برای مدیریت وظایف پس‌زمینه هر کاربر ---
52
+ user_tasks = {}
53
+ group_tasks = {}
54
+
55
+ # --- توابع کمکی برای مدیریت ریپلای ---
56
+ def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple:
57
+ """استخراج اطلاعات از ریپلای"""
58
+ message = update.message
59
+
60
+ # اگر ریپلای وجود نداشت
61
+ if not message or not message.reply_to_message:
62
+ return None, None, None, None
63
+
64
+ replied_message = message.reply_to_message
65
+
66
+ # اطلاعات پیام ریپلای شده
67
+ replied_user_id = replied_message.from_user.id if replied_message.from_user else None
68
+ replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown"
69
+
70
+ # استخراج متن پیام ریپلای شده
71
+ replied_text = ""
72
+ if replied_message.text:
73
+ replied_text = replied_message.text
74
+ elif replied_message.caption:
75
+ replied_text = replied_message.caption
76
+
77
+ # بررسی اینکه آیا ریپلای به ربات است
78
+ is_reply_to_bot = False
79
+ if replied_message.from_user:
80
+ # بررسی اینکه آیا پیام از خود ربات است
81
+ if replied_message.from_user.is_bot:
82
+ is_reply_to_bot = True
83
+ # یا آیا پیام حاوی منشن ربات است
84
+ elif context.bot and context.bot.username and replied_message.text:
85
+ if f"@{context.bot.username}" in replied_message.text:
86
+ is_reply_to_bot = True
87
+
88
+ return replied_user_id, replied_user_name, replied_text, is_reply_to_bot
89
+
90
+ def format_reply_message(user_message: str, replied_user_name: str, replied_text: str, is_reply_to_bot: bool = False, current_user_name: str = None) -> str:
91
+ """فرمت‌دهی پیام با در نظر گرفتن ریپلای"""
92
+ if not replied_text:
93
+ return user_message
94
+
95
+ # محدود کردن طول متن ریپلای شده
96
+ if len(replied_text) > 100:
97
+ replied_preview = replied_text[:97] + "..."
98
+ else:
99
+ replied_preview = replied_text
100
+
101
+ # حذف منشن ربات از متن ریپلای شده اگر وجود دارد
102
+ replied_preview = replied_preview.replace("@", "(at)") # جایگزین موقت برای جلوگیری از منشن
103
+
104
+ if is_reply_to_bot:
105
+ # ریپلای به ربات
106
+ if current_user_name:
107
+ return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}"
108
+ else:
109
+ return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}"
110
+ else:
111
+ # ریپلای به کاربر دیگر
112
+ if current_user_name:
113
+ return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
114
+ else:
115
+ return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
116
+
117
+ def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot):
118
+ """ایجاد دیکشنری اطلاعات ریپلای"""
119
+ if not replied_text:
120
+ return None
121
+
122
+ return {
123
+ 'replied_user_id': replied_user_id,
124
+ 'replied_user_name': replied_user_name,
125
+ 'replied_text': replied_text[:500], # محدود کردن طول
126
+ 'is_reply_to_bot': is_reply_to_bot,
127
+ 'timestamp': time.time()
128
+ }
129
+
130
+ # --- توابع کمکی برای مدیریت وظایف ---
131
+ def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int):
132
+ if task_id in task_dict and task_dict[task_id] == task:
133
+ del task_dict[task_id]
134
+ logger.info(f"Cleaned up finished task for ID {task_id}.")
135
+ try:
136
+ exception = task.exception()
137
+ if exception:
138
+ logger.error(f"Background task for ID {task_id} failed: {exception}")
139
+ except asyncio.CancelledError:
140
+ logger.info(f"Task for ID {task_id} was cancelled.")
141
+ except asyncio.InvalidStateError:
142
+ pass
143
+
144
+ async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
145
+ """پردازش درخواست کاربر در چت خصوصی"""
146
+ chat_id = update.effective_chat.id
147
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
148
+ user_id = update.effective_user.id
149
+
150
+ if not user_message:
151
+ logger.warning(f"No message content for user {user_id}")
152
+ return
153
+
154
+ # اگر reply_info از بیرون داده نشده، استخراج کن
155
+ if reply_info is None:
156
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
157
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
158
+
159
+ # اگر ریپلای وجود داشت، متن را فرمت کن
160
+ if reply_info and reply_info.get('replied_text'):
161
+ formatted_message = format_reply_message(
162
+ user_message,
163
+ reply_info.get('replied_user_name', 'Unknown'),
164
+ reply_info.get('replied_text'),
165
+ reply_info.get('is_reply_to_bot', False)
166
+ )
167
+ else:
168
+ formatted_message = user_message
169
+
170
+ start_time = time.time()
171
+
172
+ try:
173
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
174
+
175
+ # دریافت context کاربر
176
+ user_context = data_manager.get_context_for_api(user_id)
177
+
178
+ # اضافه کردن پیام کاربر به context (با فرمت ریپلای اگر وجود داشت)
179
+ data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
180
+
181
+ # دریافت system instruction
182
+ system_instruction = data_manager.get_system_instruction(user_id=user_id)
183
+
184
+ # ایجاد لیست پیام‌ها برای API
185
+ messages = []
186
+
187
+ # اضافه کردن system instruction اگر وجود دارد
188
+ if system_instruction:
189
+ messages.append({"role": "system", "content": system_instruction})
190
+
191
+ messages.extend(user_context.copy())
192
+ messages.append({"role": "user", "content": formatted_message})
193
+
194
+ logger.info(f"User {user_id} sending {len(messages)} messages to AI")
195
+ if reply_info and reply_info.get('replied_text'):
196
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
197
+
198
+ response = await client.chat.completions.create(
199
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
200
+ messages=messages,
201
+ temperature=0.7,
202
+ top_p=0.95,
203
+ stream=False,
204
+ )
205
+
206
+ end_time = time.time()
207
+ response_time = end_time - start_time
208
+ data_manager.update_response_stats(response_time)
209
+
210
+ ai_response = response.choices[0].message.content
211
+
212
+ # اضافه کردن پاسخ هوش مصنوعی به context
213
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
214
+
215
+ await update.message.reply_text(ai_response)
216
+ data_manager.update_user_stats(user_id, update.effective_user)
217
+
218
+ except httpx.TimeoutException:
219
+ logger.warning(f"Request timed out for user {user_id}.")
220
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
221
+ except Exception as e:
222
+ logger.error(f"Error while processing message for user {user_id}: {e}")
223
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
224
+
225
+ async def _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
226
+ """پردازش درخواست در گروه"""
227
+ chat_id = update.effective_chat.id
228
+ user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
229
+ user_id = update.effective_user.id
230
+ user_name = update.effective_user.first_name
231
+
232
+ if not user_message:
233
+ logger.warning(f"No message content for group {chat_id}, user {user_id}")
234
+ return
235
+
236
+ # اگر reply_info از بیرون داده نشده، استخراج کن
237
+ if reply_info is None:
238
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
239
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
240
+
241
+ # اگر ریپلای وجود داشت، متن را فرمت کن
242
+ if reply_info and reply_info.get('replied_text'):
243
+ formatted_message = format_reply_message(
244
+ user_message,
245
+ reply_info.get('replied_user_name', 'Unknown'),
246
+ reply_info.get('replied_text'),
247
+ reply_info.get('is_reply_to_bot', False),
248
+ user_name
249
+ )
250
+ else:
251
+ formatted_message = user_message
252
+
253
+ start_time = time.time()
254
+
255
+ try:
256
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
257
+
258
+ # بررسی حالت context
259
+ context_mode = data_manager.get_context_mode()
260
+
261
+ if context_mode == 'group_shared':
262
+ # حالت مشترک گروه: فقط از context گروه استفاده می‌شود
263
+ messages = data_manager.get_context_for_api_group(chat_id)
264
+ data_manager.add_to_group_context_with_reply(chat_id, "user", formatted_message, user_name, reply_info)
265
+
266
+ elif context_mode == 'hybrid':
267
+ # حالت ترکیبی: از هر دو context استفاده می‌شود
268
+ messages = data_manager.get_hybrid_context_for_api(user_id, chat_id)
269
+ data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "user", formatted_message, user_name, reply_info)
270
+
271
+ else: # separate (پیش‌فرض)
272
+ # حالت جداگانه: هر کاربر context خودش را دارد
273
+ messages = data_manager.get_context_for_api(user_id)
274
+ data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
275
+
276
+ # دریافت system instruction مناسب
277
+ system_instruction = data_manager.get_system_instruction(user_id=user_id, chat_id=chat_id)
278
+
279
+ # اضافه کردن system instruction به ابتدای messages
280
+ if system_instruction:
281
+ # اگر system instruction وجود دارد، آن را به ابتدای لیست اضافه کن
282
+ messages_with_system = [{"role": "system", "content": system_instruction}]
283
+ messages_with_system.extend(messages)
284
+ messages = messages_with_system
285
+
286
+ # اضافه کردن پیام جدید
287
+ if context_mode == 'group_shared':
288
+ messages.append({"role": "user", "content": f"{user_name}: {formatted_message}"})
289
+ else:
290
+ messages.append({"role": "user", "content": formatted_message})
291
+
292
+ logger.info(f"Group {chat_id} ({context_mode} mode) sending {len(messages)} messages to AI")
293
+ if reply_info and reply_info.get('replied_text'):
294
+ logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
295
+
296
+ response = await client.chat.completions.create(
297
+ model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
298
+ messages=messages,
299
+ temperature=0.7,
300
+ top_p=0.95,
301
+ stream=False,
302
+ )
303
+
304
+ end_time = time.time()
305
+ response_time = end_time - start_time
306
+ data_manager.update_response_stats(response_time)
307
+
308
+ ai_response = response.choices[0].message.content
309
+
310
+ # ذخیره پاسخ بر اساس حالت context
311
+ if context_mode == 'group_shared':
312
+ data_manager.add_to_group_context(chat_id, "assistant", ai_response)
313
+ elif context_mode == 'hybrid':
314
+ # برای پاسخ‌های هوش مصنوعی، reply_info را None می‌کنیم
315
+ data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "assistant", ai_response, None, None)
316
+ else:
317
+ data_manager.add_to_user_context(user_id, "assistant", ai_response)
318
+
319
+ # به‌روزرسانی آمار گروه با user_id
320
+ data_manager.update_group_stats(chat_id, update.effective_chat, user_id)
321
+
322
+ await update.message.reply_text(ai_response)
323
+
324
+ except httpx.TimeoutException:
325
+ logger.warning(f"Request timed out for group {chat_id}.")
326
+ await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
327
+ except Exception as e:
328
+ logger.error(f"Error while processing message for group {chat_id}: {e}")
329
+ await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
330
+
331
+ # --- هندلرهای اصلی ربات ---
332
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
333
+ user = update.effective_user
334
+ user_id = user.id
335
+ chat = update.effective_chat
336
+
337
+ if chat.type in ['group', 'supergroup']:
338
+ # در گروه
339
+ data_manager.update_group_stats(chat.id, chat, user_id)
340
+
341
+ welcome_msg = data_manager.DATA.get('group_welcome_message',
342
+ "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیام‌ها ریپلای کنید")
343
+
344
+ context_mode = data_manager.get_context_mode()
345
+ mode_info = ""
346
+ if context_mode == 'group_shared':
347
+ mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده می‌شود. همه کاربران تاریخچه مکالمه یکسانی دارند (تا 16384 توکن)."
348
+ elif context_mode == 'hybrid':
349
+ mode_info = "\n\n📝 **نکته:** در این گروه از context ترکیبی استفاده می‌شود."
350
+
351
+ # نمایش اطلاعات system instruction گروه
352
+ system_info = data_manager.get_system_instruction_info(chat_id=chat.id)
353
+ if system_info['type'] == 'group' and system_info['has_instruction']:
354
+ instruction_preview = system_info['instruction'][:100] + "..." if len(system_info['instruction']) > 100 else system_info['instruction']
355
+ mode_info += f"\n\n⚙️ **سیستم‌اینستراکشن:**\n{instruction_preview}"
356
+
357
+ await update.message.reply_html(
358
+ welcome_msg + mode_info,
359
+ disable_web_page_preview=True
360
+ )
361
+ else:
362
+ # در چت خصوصی
363
+ data_manager.update_user_stats(user_id, user)
364
+
365
+ welcome_msg = data_manager.DATA.get('welcome_message',
366
+ "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\n\n💡 **نکته:** می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.")
367
+
368
+ await update.message.reply_html(
369
+ welcome_msg.format(user_mention=user.mention_html()),
370
+ disable_web_page_preview=True
371
+ )
372
+
373
+ async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
374
+ """پاک کردن تاریخچه چت"""
375
+ user_id = update.effective_user.id
376
+ chat = update.effective_chat
377
+
378
+ if chat.type in ['group', 'supergroup']:
379
+ # پاک کردن context گروه
380
+ data_manager.clear_group_context(chat.id)
381
+
382
+ context_mode = data_manager.get_context_mode()
383
+ if context_mode == 'group_shared':
384
+ await update.message.reply_text(
385
+ "🧹 تاریخچه مکالمه گروه پاک شد.\n"
386
+ "از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد."
387
+ )
388
+ else:
389
+ await update.message.reply_text(
390
+ "🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n"
391
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
392
+ )
393
+ else:
394
+ # پاک کردن context کاربر
395
+ data_manager.clear_user_context(user_id)
396
+
397
+ await update.message.reply_text(
398
+ "🧹 تاریخچه مکالمه شما پاک شد.\n"
399
+ "از این لحظه مکالمه جدیدی شروع خواهد شد."
400
+ )
401
+
402
+ async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
403
+ """نمایش اطلاعات context"""
404
+ user_id = update.effective_user.id
405
+ chat = update.effective_chat
406
+
407
+ if chat.type in ['group', 'supergroup']:
408
+ context_mode = data_manager.get_context_mode()
409
+
410
+ if context_mode == 'group_shared':
411
+ context_summary = data_manager.get_group_context_summary(chat.id)
412
+ await update.message.reply_text(
413
+ f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n"
414
+ f"{context_summary}\n\n"
415
+ f"**حالت:** مشترک بین همه اعضای گروه\n"
416
+ f"**سقف توکن:** 16384 توکن\n"
417
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
418
+ )
419
+ elif context_mode == 'hybrid':
420
+ group_summary = data_manager.get_group_context_summary(chat.id)
421
+ user_summary = data_manager.get_context_summary(user_id)
422
+ await update.message.reply_text(
423
+ f"📊 **اطلاعات تاریخچه مکالمه (حالت ترکیبی):**\n\n"
424
+ f"**گروه:** {group_summary}\n"
425
+ f"**شخصی:** {user_summary}\n\n"
426
+ f"برای پ��ک کردن تاریخچه از دستور /clear استفاده کنید."
427
+ )
428
+ else:
429
+ context_summary = data_manager.get_context_summary(user_id)
430
+ await update.message.reply_text(
431
+ f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n"
432
+ f"{context_summary}\n\n"
433
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
434
+ )
435
+ else:
436
+ context_summary = data_manager.get_context_summary(user_id)
437
+
438
+ await update.message.reply_text(
439
+ f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
440
+ f"{context_summary}\n\n"
441
+ f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
442
+ )
443
+
444
+ # در بخش help_command:
445
+ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
446
+ """نمایش دستورات کمک"""
447
+ user_id = update.effective_user.id
448
+ chat = update.effective_chat
449
+
450
+ # بررسی مجوزها
451
+ is_admin_bot = user_id in admin_panel.ADMIN_IDS
452
+ is_admin_group = system_instruction_handlers.is_group_admin(update) if chat.type in ['group', 'supergroup'] else False
453
+
454
+ if chat.type in ['group', 'supergroup']:
455
+ help_text = (
456
+ "🤖 **دستورات ربات در گروه:**\n\n"
457
+ "🟢 `/start` - شروع کار با ربات در گروه\n"
458
+ "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
459
+ "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
460
+ "🟢 `/help` - نمایش این پیام راهنما\n\n"
461
+ "📝 **نکته:** ربات به سه صورت کار می‌کند:\n"
462
+ "1. پاسخ به پیام‌های مستقیم\n"
463
+ "2. پاسخ وقتی منشن می‌شوید\n"
464
+ "3. پاسخ به ریپلای‌ها (روی پیام‌های من یا دیگران)\n\n"
465
+ f"**حالت فعلی:** {data_manager.get_context_mode()}\n"
466
+ "• separate: هر کاربر تاریخچه جداگانه (8192 توکن)\n"
467
+ "• group_shared: تاریخچه مشترک برای همه (16384 توکن)\n"
468
+ "• hybrid: ترکیب هر دو\n\n"
469
+ "💡 **توجه:** در حالت group_shared، ربات می‌تواند تا 16384 توکن از تاریخچه مکالمه گروه را به خاطر بسپارد."
470
+ )
471
+
472
+ # اضافه کردن دستورات system instruction
473
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
474
+
475
+ if is_admin_bot or is_admin_group:
476
+ # برای ادمین‌ها
477
+ help_text += (
478
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
479
+ "• `/system clear` - حذف system instruction این گروه\n"
480
+ "• `/system_status` - نمایش وضعیت فعلی\n"
481
+ "• `/system_help` - نمایش راهنما\n\n"
482
+ )
483
+
484
+ if is_admin_bot:
485
+ help_text += "🎯 **دسترسی ادمین ربات:**\n"
486
+ help_text += "- می‌توانید Global System Instruction را مدیریت کنید\n"
487
+ help_text += "- برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n"
488
+ else:
489
+ help_text += "🎯 **دسترسی ادمین گروه:**\n"
490
+ help_text += "- فقط می‌توانید system instruction همین گروه را مدیریت کنید\n"
491
+ else:
492
+ # برای کاربران عادی
493
+ help_text += (
494
+ "این دستورات فقط برای ادمین‌های گروه در دسترس است.\n"
495
+ "برای تنظیم شخصیت ربات در این گروه، با ادمین‌های گروه تماس بگیرید."
496
+ )
497
+
498
+ else:
499
+ # در چت خصوصی
500
+ help_text = (
501
+ "🤖 **دستورات ربات:**\n\n"
502
+ "🟢 `/start` - شروع کار با ربات\n"
503
+ "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
504
+ "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
505
+ "🟢 `/help` - نمایش این پیام راهنما\n\n"
506
+ "📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۲۰۴۸ توکن ذخیره می‌کند. "
507
+ "می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n"
508
+ "برای شروع مکالمه جدید از دستور /clear استفاده کنید."
509
+ )
510
+
511
+ # اضافه کردن دستورات system instruction
512
+ help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
513
+
514
+ if is_admin_bot:
515
+ help_text += (
516
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
517
+ "• `/system_help` - نمایش راهنما\n\n"
518
+ "🎯 **دسترسی ادمین ربات:**\n"
519
+ "- می‌توانید Global System Instruction را مدیریت کنید\n"
520
+ "- از پنل ادمین برای تنظیمات پیشرفته استفاده کنید"
521
+ )
522
+ else:
523
+ help_text += "این دستورات فقط برای ادمین‌های ربات در دسترس است."
524
+
525
+ await update.message.reply_text(help_text, parse_mode='Markdown')
526
+
527
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
528
+ # بررسی وجود پیام
529
+ if not update.message:
530
+ return
531
+
532
+ user_id = update.effective_user.id
533
+ chat = update.effective_chat
534
+
535
+ # بررسی مسدود بودن کاربر
536
+ if data_manager.is_user_banned(user_id):
537
+ logger.info(f"Banned user {user_id} tried to send a message.")
538
+ return
539
+
540
+ # بررسی حالت نگهداری
541
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
542
+ await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
543
+ return
544
+
545
+ # بررسی کلمات مسدود شده
546
+ message_text = update.message.text or update.message.caption or ""
547
+ if not message_text:
548
+ return
549
+
550
+ if data_manager.contains_blocked_words(message_text):
551
+ logger.info(f"User {user_id} sent a message with a blocked word.")
552
+ return
553
+
554
+ if chat.type in ['group', 'supergroup']:
555
+ # پردازش در گروه
556
+ if chat.id in group_tasks and not group_tasks[chat.id].done():
557
+ group_tasks[chat.id].cancel()
558
+ logger.info(f"Cancelled previous task for group {chat.id} to start a new one.")
559
+
560
+ task = asyncio.create_task(_process_group_request(update, context))
561
+ group_tasks[chat.id] = task
562
+ task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id))
563
+ else:
564
+ # پردازش در چت خصوصی
565
+ if user_id in user_tasks and not user_tasks[user_id].done():
566
+ user_tasks[user_id].cancel()
567
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
568
+
569
+ task = asyncio.create_task(_process_user_request(update, context))
570
+ user_tasks[user_id] = task
571
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
572
+
573
+ async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
574
+ """هندلر برای زمانی که ربات در گروه منشن می‌شود"""
575
+ if not update.message:
576
+ return
577
+
578
+ if update.effective_chat.type in ['group', 'supergroup']:
579
+ # استخراج اطلاعات ریپلای
580
+ replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
581
+ reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
582
+
583
+ # حذف منشن از متن
584
+ message_text = update.message.text or ""
585
+ bot_username = context.bot.username
586
+
587
+ # حذف منشن ربات از متن
588
+ if bot_username and f"@{bot_username}" in message_text:
589
+ message_text = message_text.replace(f"@{bot_username}", "").strip()
590
+
591
+ if message_text:
592
+ # پردازش پیام مانند حالت عادی اما با متن فرمت‌شده
593
+ user_name = update.effective_user.first_name
594
+
595
+ # اگر ریپلای وجود داشت، متن را فرمت کن
596
+ if reply_info and reply_info.get('replied_text'):
597
+ formatted_message = format_reply_message(
598
+ message_text,
599
+ reply_info.get('replied_user_name', 'Unknown'),
600
+ reply_info.get('replied_text'),
601
+ reply_info.get('is_reply_to_bot', False),
602
+ user_name
603
+ )
604
+ else:
605
+ formatted_message = message_text
606
+
607
+ # پردازش درخواست
608
+ if update.effective_chat.id in group_tasks and not group_tasks[update.effective_chat.id].done():
609
+ group_tasks[update.effective_chat.id].cancel()
610
+ logger.info(f"Cancelled previous task for group {update.effective_chat.id} to start a new one.")
611
+
612
+ task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info))
613
+ group_tasks[update.effective_chat.id] = task
614
+ task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, update.effective_chat.id))
615
+ else:
616
+ await update.message.reply_text("بله؟ چگونه می‌توانم کمک کنم؟")
617
+
618
+ async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
619
+ """هندلر مخصوص ریپلای‌ها"""
620
+ # بررسی وجود پیام
621
+ if not update.message:
622
+ return
623
+
624
+ # فقط ریپلای‌هایی که متن دارند
625
+ message_text = update.message.text or update.message.caption or ""
626
+ if not message_text:
627
+ return
628
+
629
+ user_id = update.effective_user.id
630
+ chat = update.effective_chat
631
+
632
+ # بررسی مسدود بودن کاربر
633
+ if data_manager.is_user_banned(user_id):
634
+ return
635
+
636
+ # بررسی حالت نگهداری
637
+ if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
638
+ return
639
+
640
+ # بررسی کلمات مسدود شده
641
+ if data_manager.contains_blocked_words(message_text):
642
+ return
643
+
644
+ if chat.type in ['group', 'supergroup']:
645
+ # پردازش در گروه
646
+ if chat.id in group_tasks and not group_tasks[chat.id].done():
647
+ group_tasks[chat.id].cancel()
648
+ logger.info(f"Cancelled previous task for group {chat.id} to start a new one.")
649
+
650
+ task = asyncio.create_task(_process_group_request(update, context))
651
+ group_tasks[chat.id] = task
652
+ task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id))
653
+ else:
654
+ # پردازش در چت خصوصی
655
+ if user_id in user_tasks and not user_tasks[user_id].done():
656
+ user_tasks[user_id].cancel()
657
+ logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
658
+
659
+ task = asyncio.create_task(_process_user_request(update, context))
660
+ user_tasks[user_id] = task
661
+ task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
662
+
663
+ def main() -> None:
664
+ token = os.environ.get("BOT_TOKEN")
665
+ if not token:
666
+ logger.error("BOT_TOKEN not set in environment variables!")
667
+ return
668
+
669
+ application = (
670
+ Application.builder()
671
+ .token(token)
672
+ .concurrent_updates(True)
673
+ .build()
674
+ )
675
+
676
+ # هندلرهای کاربران
677
+ application.add_handler(CommandHandler("start", start))
678
+ application.add_handler(CommandHandler("clear", clear_chat))
679
+ application.add_handler(CommandHandler("context", context_info))
680
+ application.add_handler(CommandHandler("help", help_command))
681
+
682
+ # هندلر برای ریپلای‌ها
683
+ application.add_handler(MessageHandler(
684
+ filters.TEXT & filters.REPLY,
685
+ reply_handler
686
+ ))
687
+
688
+ # هندلر برای منشن در گروه
689
+ application.add_handler(MessageHandler(
690
+ filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS,
691
+ mention_handler
692
+ ))
693
+
694
+ # هندلر برای پیام‌های متنی معمولی (بدون ریپلای و بدون منشن)
695
+ application.add_handler(MessageHandler(
696
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY,
697
+ handle_message
698
+ ))
699
+
700
+ # هندلر برای پیام‌های متنی در گروه (بدون منشن و بدون ریپلای)
701
+ application.add_handler(MessageHandler(
702
+ filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS & ~filters.Entity("mention") & ~filters.REPLY,
703
+ handle_message
704
+ ))
705
+
706
+ # راه‌اندازی و ثبت هندلرهای پنل ادمین
707
+ admin_panel.setup_admin_handlers(application)
708
+
709
+ # راه‌اندازی هندلرهای system instruction
710
+ system_instruction_handlers.setup_system_instruction_handlers(application)
711
+
712
+ # تنظیم هندلر خطا
713
+ async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
714
+ logger.error(f"Exception while handling an update: {context.error}")
715
+ try:
716
+ if update and update.message:
717
+ await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.")
718
+ except:
719
+ pass
720
+
721
+ application.add_error_handler(error_handler)
722
+
723
+ port = int(os.environ.get("PORT", 8443))
724
+ webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
725
+
726
+ if webhook_url:
727
+ application.run_webhook(
728
+ listen="0.0.0.0",
729
+ port=port,
730
+ webhook_url=webhook_url,
731
+ url_path="webhook"
732
+ )
733
+ else:
734
+ application.run_polling()
735
+
736
+ if __name__ == "__main__":
737
+ main()
BOT/render-main/render.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ - type: web
3
+ name: telegram-ai-bot
4
+ env: python
5
+ buildCommand: pip install -r requirements.txt
6
+ startCommand: python main.py
7
+ plan: free # می‌توانید از پلن رایگان استفاده کنید
8
+ envVars:
9
+ - key: BOT_TOKEN
10
+ sync: false # مقدار این متغیر را باید در داشبورد Render وارد کنید
11
+ - key: HF_TOKEN
12
+ sync: false # مقدار این متغیر را نیز در داشبورد Render وارد کنید
BOT/render-main/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-telegram-bot[job-queue]
2
+ python-telegram-bot[webhooks]
3
+ openai
4
+ requests
5
+ huggingface_hub
6
+ aiohttp
7
+ httpx[http2]
8
+ matplotlib
9
+ pandas
10
+ psutil
11
+ tiktoken
BOT/render-main/restart.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # restart.py
2
+ import os
3
+ import sys
4
+ import subprocess
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def restart_bot():
10
+ """ریستارت کردن ربات"""
11
+ logger.info("Restarting bot...")
12
+ python = sys.executable
13
+ os.execl(python, python, *sys.argv)
BOT/render-main/smart_context.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # smart_context.py
2
+
3
+ import os
4
+ import json
5
+ import logging
6
+ import asyncio
7
+ import hashlib
8
+ import numpy as np
9
+ from datetime import datetime, timedelta
10
+ from typing import List, Dict, Any, Optional, Tuple, Set
11
+ from collections import defaultdict, deque
12
+ import pickle
13
+ from dataclasses import dataclass, field
14
+ from enum import Enum
15
+ import re
16
+ import heapq
17
+
18
+ # برای embeddings (در صورت نبود کتابخانه، از روش جایگزین استفاده می‌شود)
19
+ try:
20
+ from sentence_transformers import SentenceTransformer
21
+ HAS_SBERT = True
22
+ except ImportError:
23
+ HAS_SBERT = False
24
+ from sklearn.feature_extraction.text import TfidfVectorizer
25
+ import warnings
26
+ warnings.filterwarnings("ignore")
27
+
28
+ # وارد کردن مدیر داده‌ها
29
+ import data_manager
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # ==================== ENUMS و DataClasses ====================
34
+
35
+ class MemoryPriority(Enum):
36
+ """اولویت حافظه"""
37
+ LOW = 1
38
+ MEDIUM = 2
39
+ HIGH = 3
40
+ CRITICAL = 4
41
+
42
+ class MessageType(Enum):
43
+ """نوع پیام"""
44
+ FACT = "fact"
45
+ PREFERENCE = "preference"
46
+ EMOTION = "emotion"
47
+ QUESTION = "question"
48
+ ANSWER = "answer"
49
+ DECISION = "decision"
50
+ ACTION = "action"
51
+ CHITCHAT = "chitchat"
52
+
53
+ class EmotionType(Enum):
54
+ """نوع احساس"""
55
+ POSITIVE = "positive"
56
+ NEUTRAL = "neutral"
57
+ NEGATIVE = "negative"
58
+ EXCITED = "excited"
59
+ ANGRY = "angry"
60
+ CONFUSED = "confused"
61
+
62
+ @dataclass
63
+ class MessageNode:
64
+ """گره پیام در گراف حافظه"""
65
+ id: str
66
+ content: str
67
+ role: str
68
+ timestamp: datetime
69
+ message_type: MessageType
70
+ importance_score: float = 0.5
71
+ emotion_score: Dict[EmotionType, float] = field(default_factory=dict)
72
+ tokens: int = 0
73
+ embeddings: Optional[np.ndarray] = None
74
+ metadata: Dict[str, Any] = field(default_factory=dict)
75
+
76
+ def __hash__(self):
77
+ return hash(self.id)
78
+
79
+ def __eq__(self, other):
80
+ return self.id == other.id
81
+
82
+ @dataclass
83
+ class MemoryConnection:
84
+ """اتصال بین پیام‌ها در گراف حافظه"""
85
+ source_id: str
86
+ target_id: str
87
+ connection_type: str # 'semantic', 'temporal', 'causal', 'contextual'
88
+ strength: float = 1.0
89
+ metadata: Dict[str, Any] = field(default_factory=dict)
90
+
91
+ @dataclass
92
+ class UserProfile:
93
+ """پروفایل کاربر"""
94
+ user_id: int
95
+ personality_traits: Dict[str, float] = field(default_factory=dict)
96
+ interests: Set[str] = field(default_factory=set)
97
+ preferences: Dict[str, Any] = field(default_factory=dict)
98
+ conversation_style: str = "balanced"
99
+ knowledge_level: Dict[str, float] = field(default_factory=dict)
100
+ emotional_patterns: Dict[str, List[float]] = field(default_factory=dict)
101
+ learning_style: Optional[str] = None
102
+
103
+ def update_from_message(self, message: str, analysis: Dict[str, Any]):
104
+ """به‌روزرسانی پروفایل بر اساس پیام جدید"""
105
+ if 'personality_clues' in analysis:
106
+ for trait, score in analysis['personality_clues'].items():
107
+ current = self.personality_traits.get(trait, 0.5)
108
+ self.personality_traits[trait] = 0.7 * current + 0.3 * score
109
+
110
+ if 'interests' in analysis:
111
+ self.interests.update(analysis['interests'])
112
+
113
+ if 'preferences' in analysis:
114
+ self.preferences.update(analysis['preferences'])
115
+
116
+ # ==================== کلاس Embedding Manager ====================
117
+
118
+ class EmbeddingManager:
119
+ """مدیریت embeddings برای جستجوی معنایی"""
120
+
121
+ def __init__(self, model_name: str = None):
122
+ self.model = None
123
+ self.vectorizer = None
124
+ self.use_sbert = HAS_SBERT
125
+
126
+ if self.use_sbert:
127
+ try:
128
+ self.model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
129
+ logger.info("Loaded multilingual sentence transformer")
130
+ except Exception as e:
131
+ logger.warning(f"Failed to load sentence transformer: {e}")
132
+ self.use_sbert = False
133
+
134
+ if not self.use_sbert:
135
+ try:
136
+ from sklearn.feature_extraction.text import TfidfVectorizer
137
+ self.vectorizer = TfidfVectorizer(max_features=1000)
138
+ logger.info("Using TF-IDF for embeddings")
139
+ except ImportError:
140
+ logger.warning("scikit-learn not available, using simple word vectors")
141
+ self.vectorizer = None
142
+
143
+ def get_embedding(self, text: str) -> np.ndarray:
144
+ """دریافت embedding برای متن"""
145
+ if self.use_sbert and self.model:
146
+ return self.model.encode([text])[0]
147
+ elif self.vectorizer:
148
+ # برای TF-IDF نیاز به fit داریم، فقط بردار ساده برمی‌گردانیم
149
+ words = text.lower().split()
150
+ unique_words = list(set(words))
151
+ embedding = np.zeros(100)
152
+ for i, word in enumerate(unique_words[:100]):
153
+ embedding[i] = hash(word) % 100 / 100.0
154
+ return embedding
155
+ else:
156
+ # روش ساده‌تر
157
+ text_lower = text.lower()
158
+ embedding = np.zeros(50)
159
+ # وزن بر اساس طول و محتوا
160
+ embedding[0] = len(text) / 1000.0
161
+ embedding[1] = text.count('؟') / 5.0
162
+ embedding[2] = text.count('!') / 5.0
163
+ # ویژگی‌های ساده
164
+ embedding[3] = 1.0 if 'چه' in text_lower else 0.0
165
+ embedding[4] = 1.0 if 'چرا' in text_lower else 0.0
166
+ embedding[5] = 1.0 if 'چگونه' in text_lower else 0.0
167
+ return embedding
168
+
169
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
170
+ """محاسبه cosine similarity"""
171
+ norm1 = np.linalg.norm(vec1)
172
+ norm2 = np.linalg.norm(vec2)
173
+ if norm1 == 0 or norm2 == 0:
174
+ return 0.0
175
+ return np.dot(vec1, vec2) / (norm1 * norm2)
176
+
177
+ # ==================== کلاس Memory Graph ====================
178
+
179
+ class MemoryGraph:
180
+ """گراف حافظه برای ذخیره و بازیابی ارتباطات"""
181
+
182
+ def __init__(self):
183
+ self.nodes: Dict[str, MessageNode] = {}
184
+ self.connections: List[MemoryConnection] = []
185
+ self.adjacency: Dict[str, List[MemoryConnection]] = defaultdict(list)
186
+ self.topic_clusters: Dict[str, Set[str]] = defaultdict(set)
187
+ self.time_index: List[Tuple[datetime, str]] = []
188
+
189
+ def add_node(self, node: MessageNode):
190
+ """افزودن گره جدید"""
191
+ self.nodes[node.id] = node
192
+ self.time_index.append((node.timestamp, node.id))
193
+ self.time_index.sort(key=lambda x: x[0])
194
+
195
+ def add_connection(self, connection: MemoryConnection):
196
+ """افزودن اتصال جدید"""
197
+ self.connections.append(connection)
198
+ self.adjacency[connection.source_id].append(connection)
199
+
200
+ def find_similar_nodes(self, query_embedding: np.ndarray,
201
+ threshold: float = 0.7,
202
+ max_results: int = 5) -> List[Tuple[str, float]]:
203
+ """یافتن گره‌های مشابه"""
204
+ similarities = []
205
+ for node_id, node in self.nodes.items():
206
+ if node.embeddings is not None:
207
+ similarity = self._cosine_similarity(query_embedding, node.embeddings)
208
+ if similarity > threshold:
209
+ similarities.append((node_id, similarity))
210
+
211
+ similarities.sort(key=lambda x: x[1], reverse=True)
212
+ return similarities[:max_results]
213
+
214
+ def get_temporal_neighbors(self, node_id: str,
215
+ time_window: timedelta = timedelta(hours=24)) -> List[str]:
216
+ """یافتن همسایه‌های زمانی"""
217
+ if node_id not in self.nodes:
218
+ return []
219
+
220
+ node_time = self.nodes[node_id].timestamp
221
+ neighbors = []
222
+
223
+ for timestamp, nid in self.time_index:
224
+ if nid != node_id and abs(timestamp - node_time) <= time_window:
225
+ neighbors.append(nid)
226
+
227
+ return neighbors
228
+
229
+ def get_semantic_cluster(self, node_id: str, min_similarity: float = 0.6) -> Set[str]:
230
+ """دریافت خوشه معنایی یک گره"""
231
+ cluster = {node_id}
232
+
233
+ if node_id not in self.nodes or self.nodes[node_id].embeddings is None:
234
+ return cluster
235
+
236
+ query_embedding = self.nodes[node_id].embeddings
237
+
238
+ for other_id, other_node in self.nodes.items():
239
+ if other_id != node_id and other_node.embeddings is not None:
240
+ similarity = self._cosine_similarity(query_embedding, other_node.embeddings)
241
+ if similarity > min_similarity:
242
+ cluster.add(other_id)
243
+
244
+ return cluster
245
+
246
+ def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
247
+ """محاسبه cosine similarity"""
248
+ norm1 = np.linalg.norm(vec1)
249
+ norm2 = np.linalg.norm(vec2)
250
+ if norm1 == 0 or norm2 == 0:
251
+ return 0.0
252
+ return np.dot(vec1, vec2) / (norm1 * norm2)
253
+
254
+ # ==================== کلاس Context Analyzer ====================
255
+
256
+ class ContextAnalyzer:
257
+ """آنالیزور هوشمند context"""
258
+
259
+ def __init__(self):
260
+ self.keyword_patterns = {
261
+ 'name': [r'نام\s+من\s+(.*?)(?:است|می‌باشد)', r'اسم\s+من\s+(.*?)'],
262
+ 'age': [r'سن\s+من\s+(\d+)', r'(\d+)\s+سالمه'],
263
+ 'location': [r'اهل\s+(.*?)\s+هستم', r'د��\s+(.*?)\s+زندگی می‌کنم'],
264
+ 'preference': [r'دوست\s+دارم\s+(.*?)', r'علاقه\s+دارم\s+(.*?)', r'ترجیح\s+می‌دهم\s+(.*?)'],
265
+ 'dislike': [r'دوست\s+ندارم\s+(.*?)', r'مخالف\s+(.*?)\s+هستم'],
266
+ 'goal': [r'می‌خواهم\s+(.*?)', r'هدف\s+من\s+(.*?)\s+است'],
267
+ 'question': [r'(چرا|چگونه|چه|کجا|کی|آیا)\s+.*?\?'],
268
+ 'decision': [r'تصمیم\s+گرفتم\s+(.*?)', r'قصد\s+دارم\s+(.*?)'],
269
+ 'emotion': [r'احساس\s+(.*?)\s+دارم', r'(خوشحالم|ناراحتم|عصبانی‌ام|خستهام)']
270
+ }
271
+
272
+ self.emotion_keywords = {
273
+ EmotionType.POSITIVE: ['خوب', 'عالی', 'خوشحال', 'عالی', 'ممنون', 'مرسی', 'دوست دارم', 'عالیه'],
274
+ EmotionType.NEGATIVE: ['بد', 'بدی', 'ناراحت', 'غمگین', 'عصبانی', 'مشکل', 'خطا', 'اشتباه'],
275
+ EmotionType.EXCITED: ['هیجان‌زده', 'هیجان', 'جالب', 'شگفت‌انگیز', 'عالی', 'وای'],
276
+ EmotionType.ANGRY: ['عصبانی', 'خشمگین', 'ناراحت', 'اعصاب', 'دیوانه'],
277
+ EmotionType.CONFUSED: ['سردرگم', 'گیج', 'نمی‌فهمم', 'مشکل دارم', 'کمک']
278
+ }
279
+
280
+ def analyze_message(self, text: str, role: str) -> Dict[str, Any]:
281
+ """آنالیز پیام و استخراج اطلاعات"""
282
+ analysis = {
283
+ 'type': self._detect_message_type(text, role),
284
+ 'entities': self._extract_entities(text),
285
+ 'keywords': self._extract_keywords(text),
286
+ 'emotion': self._analyze_emotion(text),
287
+ 'importance': self._calculate_importance(text, role),
288
+ 'topics': self._extract_topics(text),
289
+ 'intent': self._detect_intent(text),
290
+ 'complexity': self._calculate_complexity(text),
291
+ 'has_personal_info': False,
292
+ 'personal_info': {}
293
+ }
294
+
295
+ # استخراج اطلاعات شخصی
296
+ personal_info = self._extract_personal_info(text)
297
+ if personal_info:
298
+ analysis['has_personal_info'] = True
299
+ analysis['personal_info'] = personal_info
300
+
301
+ # استخراج ترجیحات
302
+ preferences = self._extract_preferences(text)
303
+ if preferences:
304
+ analysis['preferences'] = preferences
305
+
306
+ return analysis
307
+
308
+ def _detect_message_type(self, text: str, role: str) -> MessageType:
309
+ """تشخیص نوع پیام"""
310
+ text_lower = text.lower()
311
+
312
+ if role == 'user':
313
+ if any(q in text_lower for q in ['؟', '?', 'چرا', 'چگونه', 'چه', 'کجا']):
314
+ return MessageType.QUESTION
315
+ elif any(e in text_lower for e in ['احساس', 'حالم', 'خوشحالم', 'ناراحتم']):
316
+ return MessageType.EMOTION
317
+ elif any(d in text_lower for d in ['تصمیم', 'قصد', 'می‌خواهم']):
318
+ return MessageType.DECISION
319
+ elif any(p in text_lower for p in ['دوست دارم', 'علاقه', 'ترجیح']):
320
+ return MessageType.PREFERENCE
321
+ else:
322
+ return MessageType.FACT
323
+ else:
324
+ if '؟' in text_lower:
325
+ return MessageType.QUESTION
326
+ elif any(a in text_lower for a in ['پاسخ', 'جواب', 'راه حل']):
327
+ return MessageType.ANSWER
328
+ else:
329
+ return MessageType.FACT
330
+
331
+ def _extract_entities(self, text: str) -> List[str]:
332
+ """استخراج موجودیت‌ها"""
333
+ entities = []
334
+ # الگوهای ساده برای اسامی
335
+ name_patterns = [
336
+ r'نام\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
337
+ r'اسم\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
338
+ ]
339
+
340
+ for pattern in name_patterns:
341
+ matches = re.findall(pattern, text)
342
+ entities.extend(matches)
343
+
344
+ return entities
345
+
346
+ def _extract_keywords(self, text: str) -> List[str]:
347
+ """استخراج کلمات کلیدی"""
348
+ # حذف کلمات توقف فارسی
349
+ stopwords = {'و', 'در', 'با', 'به', 'از', 'که', 'این', 'آن', 'را', 'برای', 'اما', 'یا'}
350
+ words = re.findall(r'\b[\wآ-ی]+\b', text.lower())
351
+ keywords = [w for w in words if w not in stopwords and len(w) > 2]
352
+
353
+ return list(set(keywords))[:10]
354
+
355
+ def _analyze_emotion(self, text: str) -> Dict[EmotionType, float]:
356
+ """تحلیل احساسات متن"""
357
+ emotion_scores = {e: 0.0 for e in EmotionType}
358
+ text_lower = text.lower()
359
+
360
+ for emotion_type, keywords in self.emotion_keywords.items():
361
+ score = 0.0
362
+ for keyword in keywords:
363
+ if keyword in text_lower:
364
+ score += 1.0
365
+ emotion_scores[emotion_type] = min(score / 3.0, 1.0)
366
+
367
+ # تشخیص احساس کلی
368
+ if sum(emotion_scores.values()) == 0:
369
+ emotion_scores[EmotionType.NEUTRAL] = 1.0
370
+
371
+ return emotion_scores
372
+
373
+ def _calculate_importance(self, text: str, role: str) -> float:
374
+ """محاسبه اهمیت پیام"""
375
+ score = 0.0
376
+
377
+ # امتیاز بر اساس نقش
378
+ if role == 'user':
379
+ score += 0.3
380
+
381
+ # امتیاز بر اساس طول
382
+ length = len(text)
383
+ if length > 200:
384
+ score += 0.3
385
+ elif length > 100:
386
+ score += 0.2
387
+ elif length > 50:
388
+ score += 0.1
389
+
390
+ # امتیاز بر اساس سوال بودن
391
+ if '؟' in text or '?' in text:
392
+ score += 0.2
393
+
394
+ # امتیاز بر اساس کلمات کلیدی مهم
395
+ important_words = ['مهم', 'لطفا', 'فوری', 'ضروری', 'لازم', 'حتما']
396
+ for word in important_words:
397
+ if word in text.lower():
398
+ score += 0.2
399
+ break
400
+
401
+ # امتیاز بر اساس اطلاعات شخصی
402
+ if any(pattern in text for pattern in ['نام من', 'سن من', 'اهل']):
403
+ score += 0.3
404
+
405
+ return min(score, 1.0)
406
+
407
+ def _extract_topics(self, text: str) -> List[str]:
408
+ """استخراج موضوعات"""
409
+ topics = []
410
+
411
+ # دسته‌بندی موضوعات بر اساس کلمات کلیدی
412
+ topic_categories = {
413
+ 'ورزش': ['فوتبال', 'ورزش', 'تمرین', 'مسابقه', 'تیم'],
414
+ 'تکنولوژی': ['کامپیوتر', 'برنامه', 'کد', 'پایتون', 'هوش مصنوعی'],
415
+ 'هنر': ['فیلم', 'موسیقی', 'نقاشی', 'کتاب', 'خواننده'],
416
+ 'علم': ['تحقیق', 'دانش', 'کشف', 'آزمایش', 'نظریه'],
417
+ 'غذا': ['غذا', 'رستوران', 'پخت', 'خوراک', 'ناهار'],
418
+ 'سفر': ['سفر', 'مسافرت', 'کشور', 'شهر', 'هتل'],
419
+ 'سلامتی': ['سلامت', 'بیماری', 'درمان', 'دکتر', 'بیمارستان'],
420
+ 'کاری': ['کار', 'شغل', 'شرکت', 'مصاحبه', 'پروژه'],
421
+ 'تحصیل': ['درس', 'دانشگاه', 'مدرسه', 'آموزش', 'یادگیری'],
422
+ }
423
+
424
+ text_lower = text.lower()
425
+ for topic, keywords in topic_categories.items():
426
+ if any(keyword in text_lower for keyword in keywords):
427
+ topics.append(topic)
428
+
429
+ return topics[:3]
430
+
431
+ def _detect_intent(self, text: str) -> str:
432
+ """تشخیص قصد کاربر"""
433
+ text_lower = text.lower()
434
+
435
+ if any(q in text_lower for q in ['چطور', 'چگونه', 'راهنمایی']):
436
+ return 'guidance'
437
+ elif any(q in text_lower for q in ['چه', 'اطلاعات', 'معرفی']):
438
+ return 'information'
439
+ elif any(q in text_lower for q in ['چرا', 'دلیل', 'علت']):
440
+ return 'explanation'
441
+ elif any(q in text_lower for q in ['کمک', 'راه حل', 'مشکل']):
442
+ return 'help'
443
+ elif any(q in text_lower for q in ['توصیه', 'پیشنهاد', 'نظر']):
444
+ return 'advice'
445
+ elif any(q in text_lower for q in ['بحث', 'بحث کنیم', 'نظرت']):
446
+ return 'discussion'
447
+ else:
448
+ return 'general'
449
+
450
+ def _calculate_complexity(self, text: str) -> float:
451
+ """محاسبه پیچیدگی متن"""
452
+ # میانگین طول کلمات
453
+ words = text.split()
454
+ if not words:
455
+ return 0.0
456
+
457
+ avg_word_length = sum(len(w) for w in words) / len(words)
458
+
459
+ # تعداد جملات
460
+ sentences = re.split(r'[.!?]', text)
461
+ num_sentences = max(len(sentences), 1)
462
+
463
+ # نسبت کلمات منحصر به فرد
464
+ unique_words = len(set(words))
465
+ diversity = unique_words / len(words) if words else 0
466
+
467
+ complexity = (avg_word_length / 10.0 + diversity + min(len(words) / 50.0, 1.0)) / 3.0
468
+
469
+ return min(complexity, 1.0)
470
+
471
+ def _extract_personal_info(self, text: str) -> Dict[str, Any]:
472
+ """استخراج اطلاعات شخصی"""
473
+ info = {}
474
+
475
+ for info_type, patterns in self.keyword_patterns.items():
476
+ for pattern in patterns:
477
+ matches = re.findall(pattern, text)
478
+ if matches:
479
+ info[info_type] = matches[0]
480
+ break
481
+
482
+ return info
483
+
484
+ def _extract_preferences(self, text: str) -> Dict[str, Any]:
485
+ """استخراج ترجیحات"""
486
+ preferences = {}
487
+ text_lower = text.lower()
488
+
489
+ # ترجیحات ساده
490
+ if 'دوست دارم' in text_lower:
491
+ parts = text_lower.split('دوست دارم')
492
+ if len(parts) > 1:
493
+ preference = parts[1].split('.')[0].strip()
494
+ if preference:
495
+ preferences['likes'] = preferences.get('likes', []) + [preference]
496
+
497
+ if 'دوست ندارم' in text_lower:
498
+ parts = text_lower.split('دوست ندارم')
499
+ if len(parts) > 1:
500
+ preference = parts[1].split('.')[0].strip()
501
+ if preference:
502
+ preferences['dislikes'] = preferences.get('dislikes', []) + [preference]
503
+
504
+ return preferences
505
+
506
+ # ==================== کلاس Intelligent Context Manager ====================
507
+
508
+ class IntelligentContextManager:
509
+ """مدیر هوشمند context"""
510
+
511
+ def __init__(self, user_id: int):
512
+ self.user_id = user_id
513
+ self.embedding_manager = EmbeddingManager()
514
+ self.analyzer = ContextAnalyzer()
515
+ self.memory_graph = MemoryGraph()
516
+ self.user_profile = UserProfile(user_id=user_id)
517
+
518
+ # لایه‌های حافظه
519
+ self.memory_layers = {
520
+ 'ephemeral': deque(maxlen=20), # حافظه زودگذر (چند دقیقه)
521
+ 'working': deque(maxlen=50), # حافظه فعال (مکالمه جاری)
522
+ 'recent': deque(maxlen=100), # حافظه اخیر (چند روز)
523
+ 'long_term': [], # حافظه بلندمدت (اهمیت بالا)
524
+ 'core': [] # حافظه هسته (اطلاعات حیاتی)
525
+ }
526
+
527
+ # تنظیمات
528
+ self.max_working_tokens = 512
529
+ self.max_context_tokens = 2048
530
+ self.min_importance_threshold = 0.3
531
+ self.semantic_similarity_threshold = 0.7
532
+
533
+ # آمار
534
+ self.stats = {
535
+ 'total_messages': 0,
536
+ 'compressed_messages': 0,
537
+ 'retrieved_memories': 0,
538
+ 'profile_updates': 0,
539
+ 'average_importance': 0.0
540
+ }
541
+
542
+ # بارگذاری داده‌های ذخیره شده
543
+ self._load_saved_data()
544
+
545
+ def _load_saved_data(self):
546
+ """بارگذاری داده‌های ذخیره شده"""
547
+ try:
548
+ # بارگذاری از data_manager
549
+ user_data = data_manager.DATA['users'].get(str(self.user_id), {})
550
+
551
+ if 'smart_context' in user_data:
552
+ saved_data = user_data['smart_context']
553
+
554
+ # بارگذاری پروفایل کاربر
555
+ if 'profile' in saved_data:
556
+ self.user_profile = UserProfile(**saved_data['profile'])
557
+
558
+ # بارگذاری آمار
559
+ if 'stats' in saved_data:
560
+ self.stats.update(saved_data['stats'])
561
+
562
+ logger.info(f"Loaded smart context for user {self.user_id}")
563
+ except Exception as e:
564
+ logger.error(f"Error loading saved context data: {e}")
565
+
566
+ def _save_data(self):
567
+ """ذخیره داده‌ها"""
568
+ try:
569
+ user_id_str = str(self.user_id)
570
+ if user_id_str not in data_manager.DATA['users']:
571
+ data_manager.DATA['users'][user_id_str] = {}
572
+
573
+ # ذخیره داده‌های هوشمند
574
+ data_manager.DATA['users'][user_id_str]['smart_context'] = {
575
+ 'profile': {
576
+ 'user_id': self.user_profile.user_id,
577
+ 'personality_traits': dict(self.user_profile.personality_traits),
578
+ 'interests': list(self.user_profile.interests),
579
+ 'preferences': dict(self.user_profile.preferences),
580
+ 'conversation_style': self.user_profile.conversation_style,
581
+ 'knowledge_level': dict(self.user_profile.knowledge_level),
582
+ 'emotional_patterns': dict(self.user_profile.emotional_patterns),
583
+ 'learning_style': self.user_profile.learning_style
584
+ },
585
+ 'stats': self.stats,
586
+ 'last_updated': datetime.now().isoformat()
587
+ }
588
+
589
+ data_manager.save_data()
590
+ except Exception as e:
591
+ logger.error(f"Error saving smart context data: {e}")
592
+
593
+ async def process_message(self, role: str, content: str) -> Dict[str, Any]:
594
+ """پرداش کامل یک پیام جدید"""
595
+ start_time = datetime.now()
596
+
597
+ # 1. تحلیل پیام
598
+ analysis = self.analyzer.analyze_message(content, role)
599
+
600
+ # 2. ایجاد گره حافظه
601
+ message_id = self._generate_message_id(content)
602
+
603
+ # ایجاد embedding به صورت غیرهمزمان
604
+ embedding_task = asyncio.create_task(
605
+ self._get_embedding_async(content)
606
+ )
607
+
608
+ node = MessageNode(
609
+ id=message_id,
610
+ content=content,
611
+ role=role,
612
+ timestamp=datetime.now(),
613
+ message_type=analysis['type'],
614
+ importance_score=analysis['importance'],
615
+ emotion_score=analysis['emotion'],
616
+ tokens=data_manager.count_tokens(content),
617
+ embeddings=None, # موقتاً None
618
+ metadata={
619
+ 'analysis': analysis,
620
+ 'topics': analysis['topics'],
621
+ 'intent': analysis['intent'],
622
+ 'complexity': analysis['complexity']
623
+ }
624
+ )
625
+
626
+ # دریافت embedding (اگر موجود باشد)
627
+ try:
628
+ node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
629
+ except asyncio.TimeoutError:
630
+ logger.warning(f"Embedding generation timeout for message {message_id}")
631
+ node.embeddings = self.embedding_manager.get_embedding(content)
632
+
633
+ # 3. افزودن به حافظه و گراف
634
+ await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
635
+ await asyncio.to_thread(self.memory_graph.add_node, node)
636
+
637
+ # 4. ایجاد ارتباطات
638
+ await asyncio.to_thread(self._create_memory_connections, node)
639
+
640
+ # 5. به‌روزرسانی پروفایل کاربر
641
+ if role == 'user':
642
+ await asyncio.to_thread(self._update_user_profile, content, analysis)
643
+
644
+ # 6. بهینه‌سازی حافظه
645
+ await asyncio.to_thread(self._optimize_memory)
646
+
647
+ # 7. به‌روزرسانی آمار
648
+ self.stats['total_messages'] += 1
649
+ self.stats['average_importance'] = (
650
+ self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
651
+ analysis['importance']
652
+ ) / self.stats['total_messages']
653
+
654
+ # 8. ذخیره داده‌ها
655
+ await asyncio.to_thread(self._save_data)
656
+
657
+ processing_time = (datetime.now() - start_time).total_seconds()
658
+ logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
659
+
660
+ return {
661
+ 'node_id': message_id,
662
+ 'analysis': analysis,
663
+ 'processing_time': processing_time
664
+ }
665
+
666
+ async def _get_embedding_async(self, text: str) -> np.ndarray:
667
+ """دریافت embedding به صورت async"""
668
+ loop = asyncio.get_event_loop()
669
+ return await loop.run_in_executor(
670
+ None,
671
+ self.embedding_manager.get_embedding,
672
+ text
673
+ )
674
+
675
+ def _generate_message_id(self, content: str) -> str:
676
+ """تولید شناسه منحصر به فرد برای پیام"""
677
+ timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
678
+ content_hash = hashlib.md5(content.encode()).hexdigest()[:8]
679
+ return f"{self.user_id}_{timestamp}_{content_hash}"
680
+
681
+ def _add_to_memory_layers(self, node: MessageNode, analysis: Dict[str, Any]):
682
+ """افزودن پیام به لایه‌های حافظه مناسب"""
683
+
684
+ # همیشه به حافظه زودگذر و فعال اضافه می‌شود
685
+ self.memory_layers['ephemeral'].append(node)
686
+ self.memory_layers['working'].append(node)
687
+
688
+ # بررسی برای حافظه اخیر
689
+ if analysis['importance'] > 0.2:
690
+ self.memory_layers['recent'].append(node)
691
+
692
+ # بررسی برای حافظه بلندمدت
693
+ if analysis['importance'] > self.min_importance_threshold:
694
+ self.memory_layers['long_term'].append(node)
695
+
696
+ # بررسی برای حافظه هسته (اطلاعات حیاتی)
697
+ if analysis.get('has_personal_info', False) or analysis['importance'] > 0.8:
698
+ core_entry = {
699
+ 'node': node,
700
+ 'info': analysis.get('personal_info', {}),
701
+ 'timestamp': datetime.now()
702
+ }
703
+ self.memory_layers['core'].append(core_entry)
704
+
705
+ def _create_memory_connections(self, node: MessageNode):
706
+ """ایجاد ارتباطات حافظه برای گره جدید"""
707
+
708
+ # اگر گره‌های قبلی وجود دارند، ارتباط ایجاد کن
709
+ if len(self.memory_graph.nodes) > 1:
710
+ # ارتباط زمانی با آخرین گره
711
+ last_nodes = list(self.memory_graph.nodes.values())[-5:]
712
+ for last_node in last_nodes:
713
+ if last_node.id != node.id:
714
+ temporal_conn = MemoryConnection(
715
+ source_id=last_node.id,
716
+ target_id=node.id,
717
+ connection_type='temporal',
718
+ strength=0.8
719
+ )
720
+ self.memory_graph.add_connection(temporal_conn)
721
+
722
+ # ارتباط معنایی با گره‌های مشابه
723
+ if node.embeddings is not None:
724
+ similar_nodes = self.memory_graph.find_similar_nodes(
725
+ node.embeddings,
726
+ threshold=self.semantic_similarity_threshold
727
+ )
728
+
729
+ for similar_id, similarity in similar_nodes:
730
+ semantic_conn = MemoryConnection(
731
+ source_id=node.id,
732
+ target_id=similar_id,
733
+ connection_type='semantic',
734
+ strength=similarity
735
+ )
736
+ self.memory_graph.add_connection(semantic_conn)
737
+
738
+ def _update_user_profile(self, content: str, analysis: Dict[str, Any]):
739
+ """به‌روزرسانی پروفایل کاربر"""
740
+
741
+ # به‌روزرسانی علاقه‌مندی‌ها
742
+ if 'topics' in analysis:
743
+ for topic in analysis['topics']:
744
+ self.user_profile.interests.add(topic)
745
+
746
+ # به‌روزرسانی ترجیحات
747
+ if 'preferences' in analysis:
748
+ self.user_profile.preferences.update(analysis['preferences'])
749
+
750
+ # تشخیص سبک مکالمه
751
+ complexity = analysis.get('complexity', 0.5)
752
+ if complexity > 0.7:
753
+ self.user_profile.conversation_style = "detailed"
754
+ elif complexity < 0.3:
755
+ self.user_profile.conversation_style = "concise"
756
+
757
+ # به‌روزرسانی الگوهای احساسی
758
+ emotion = analysis.get('emotion', {})
759
+ for emotion_type, score in emotion.items():
760
+ if score > 0.3:
761
+ emotion_name = emotion_type.value if hasattr(emotion_type, 'value') else str(emotion_type)
762
+ if emotion_name not in self.user_profile.emotional_patterns:
763
+ self.user_profile.emotional_patterns[emotion_name] = []
764
+ self.user_profile.emotional_patterns[emotion_name].append(score)
765
+
766
+ self.stats['profile_updates'] += 1
767
+
768
+ def _optimize_memory(self):
769
+ """بهینه‌سازی و فشرده‌سازی حافظه"""
770
+
771
+ # فشرده‌سازی حافظه فعال اگر توکن‌ها زیاد شد
772
+ working_tokens = sum(node.tokens for node in self.memory_layers['working'])
773
+ if working_tokens > self.max_working_tokens:
774
+ self._compress_working_memory()
775
+ self.stats['compressed_messages'] += 1
776
+
777
+ # پاکسازی حافظه زودگذر قدیمی
778
+ if len(self.memory_layers['ephemeral']) > 50:
779
+ self.memory_layers['ephemeral'].clear()
780
+
781
+ # مرتب‌سازی حافظه بلندمدت بر اساس اهمیت
782
+ self.memory_layers['long_term'].sort(key=lambda x: x.importance_score, reverse=True)
783
+ if len(self.memory_layers['long_term']) > 100:
784
+ self.memory_layers['long_term'] = self.memory_layers['long_term'][:100]
785
+
786
+ def _compress_working_memory(self):
787
+ """فشرده‌سازی هوشمند حافظه فعال"""
788
+ if len(self.memory_layers['working']) <= 10:
789
+ return
790
+
791
+ working_memory = list(self.memory_layers['working'])
792
+
793
+ # 1. محاسبه امتیاز برای هر پیام
794
+ scored_messages = []
795
+ for i, node in enumerate(working_memory):
796
+ score = self._calculate_compression_score(node, i, len(working_memory))
797
+ scored_messages.append((score, node))
798
+
799
+ # 2. مرتب‌سازی بر اساس امتیاز
800
+ scored_messages.sort(key=lambda x: x[0], reverse=True)
801
+
802
+ # 3. انتخاب پیام‌های برتر تا سقف توکن
803
+ compressed = []
804
+ total_tokens = 0
805
+
806
+ for score, node in scored_messages:
807
+ if total_tokens + node.tokens <= self.max_working_tokens:
808
+ compressed.append(node)
809
+ total_tokens += node.tokens
810
+ else:
811
+ break
812
+
813
+ # 4. مرتب‌سازی دوباره بر اساس زمان
814
+ compressed.sort(key=lambda x: x.timestamp)
815
+
816
+ # 5. جایگزینی حافظه فعال
817
+ self.memory_layers['working'] = deque(compressed, maxlen=50)
818
+
819
+ logger.info(f"Compressed working memory: {len(working_memory)} -> {len(compressed)} messages")
820
+
821
+ def _calculate_compression_score(self, node: MessageNode, index: int, total: int) -> float:
822
+ """محاسبه امتیاز فشرده‌سازی برای یک پیام"""
823
+ score = 0.0
824
+
825
+ # 1. اهمیت پیام
826
+ score += node.importance_score * 0.4
827
+
828
+ # 2. تازگی (پیام‌های جدیدتر مهم‌تر)
829
+ recency = (index / total) * 0.3
830
+ score += recency
831
+
832
+ # 3. تنوع اطلاعات (بر اساس topics)
833
+ topics = node.metadata.get('topics', [])
834
+ topic_diversity = min(len(topics) / 3.0, 0.2)
835
+ score += topic_diversity
836
+
837
+ # 4. نوع پیام
838
+ type_weights = {
839
+ MessageType.QUESTION: 0.2,
840
+ MessageType.PREFERENCE: 0.2,
841
+ MessageType.DECISION: 0.2,
842
+ MessageType.EMOTION: 0.1,
843
+ MessageType.FACT: 0.1,
844
+ MessageType.ANSWER: 0.1,
845
+ MessageType.ACTION: 0.2,
846
+ MessageType.CHITCHAT: 0.05
847
+ }
848
+ score += type_weights.get(node.message_type, 0.1)
849
+
850
+ # 5. اطلاعات شخصی
851
+ if 'has_personal_info' in node.metadata.get('analysis', {}):
852
+ if node.metadata['analysis']['has_personal_info']:
853
+ score += 0.2
854
+
855
+ return score
856
+
857
+ async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
858
+ """بازیابی هوشمند context مرتبط با query"""
859
+ try:
860
+ if max_tokens is None:
861
+ max_tokens = self.max_context_tokens
862
+
863
+ start_time = datetime.now()
864
+
865
+ # دریافت embedding با timeout
866
+ try:
867
+ embedding_task = asyncio.create_task(
868
+ self._get_embedding_async(query)
869
+ )
870
+ query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
871
+ except asyncio.TimeoutError:
872
+ logger.warning(f"Embedding timeout for query: {query[:50]}")
873
+ query_embedding = self.embedding_manager.get_embedding(query)
874
+
875
+ # بازیابی از حافظه‌های مختلف به صورت موازی
876
+ tasks = []
877
+
878
+ # حافظه فعال
879
+ tasks.append(asyncio.create_task(
880
+ asyncio.to_thread(self._retrieve_from_working_memory)
881
+ ))
882
+
883
+ # حافظه معنایی
884
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
885
+ tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
886
+
887
+ # حافظه هسته
888
+ tasks.append(asyncio.create_task(
889
+ asyncio.to_thread(self._retrieve_core_memories, query)
890
+ ))
891
+
892
+ # اجرای موازی همه tasks
893
+ results = await asyncio.gather(*tasks, return_exceptions=True)
894
+
895
+ # جمع‌آوری نتایج
896
+ retrieved_memories = []
897
+ for result in results:
898
+ if isinstance(result, Exception):
899
+ logger.error(f"Error retrieving memory: {result}")
900
+ continue
901
+ retrieved_memories.extend(result)
902
+
903
+ except Exception as e:
904
+ logger.error(f"Error in retrieve_context: {e}")
905
+ # Fallback: برگرداندن حافظه فعال
906
+ return self._retrieve_from_working_memory()
907
+
908
+ # 1. دریافت embedding برای query
909
+ query_embedding = self.embedding_manager.get_embedding(query)
910
+
911
+ # 2. بازیابی از لایه‌های مختلف حافظه
912
+ retrieved_memories = []
913
+
914
+ # از حافظه فعال (همیشه)
915
+ retrieved_memories.extend(self._retrieve_from_working_memory())
916
+
917
+ # از حافظه اخیر (بر اساس شباهت)
918
+ recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
919
+ retrieved_memories.extend(recent_memories)
920
+
921
+ # از حافظه بلندمدت (اطلاعات مهم)
922
+ long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
923
+ retrieved_memories.extend(long_term_memories)
924
+
925
+ # از حافظه هسته (اطلاعات حیاتی کاربر)
926
+ core_memories = self._retrieve_core_memories(query)
927
+ retrieved_memories.extend(core_memories)
928
+
929
+ # 3. حذف تکراری‌ها و مرتب‌سازی
930
+ unique_memories = self._deduplicate_memories(retrieved_memories)
931
+ prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
932
+
933
+ # 4. انتخاب تا سقف توکن
934
+ final_context = []
935
+ total_tokens = 0
936
+
937
+ for memory in prioritized_memories:
938
+ memory_tokens = memory['node'].tokens if 'node' in memory else 50
939
+
940
+ if total_tokens + memory_tokens <= max_tokens:
941
+ final_context.append(memory)
942
+ total_tokens += memory_tokens
943
+ else:
944
+ break
945
+
946
+ # 5. به‌روزرسانی آمار
947
+ self.stats['retrieved_memories'] += len(final_context)
948
+
949
+ retrieval_time = (datetime.now() - start_time).total_seconds()
950
+ logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
951
+
952
+ return final_context
953
+
954
+
955
+ def _retrieve_from_working_memory(self) -> List[Dict[str, Any]]:
956
+ """بازیابی از حافظه فعال"""
957
+ memories = []
958
+
959
+ for node in list(self.memory_layers['working'])[-10:]: # 10 پیام آخر
960
+ memories.append({
961
+ 'node': node,
962
+ 'source': 'working',
963
+ 'relevance': 1.0,
964
+ 'recency': 1.0
965
+ })
966
+
967
+ return memories
968
+
969
+ async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
970
+ layer: str) -> List[Dict[str, Any]]:
971
+ """بازیابی حافظه‌های معنایی"""
972
+ memories = []
973
+
974
+ if layer not in self.memory_layers:
975
+ return memories
976
+
977
+ layer_memories = self.memory_layers[layer]
978
+
979
+ for item in layer_memories:
980
+ node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
981
+
982
+ if node and node.embeddings is not None:
983
+ similarity = self.embedding_manager.cosine_similarity(
984
+ query_embedding, node.embeddings
985
+ )
986
+
987
+ if similarity > self.semantic_similarity_threshold:
988
+ recency_weight = 1.0 if layer == 'working' else 0.7
989
+
990
+ memories.append({
991
+ 'node': node,
992
+ 'source': layer,
993
+ 'relevance': similarity,
994
+ 'recency': recency_weight,
995
+ 'importance': node.importance_score
996
+ })
997
+
998
+ return memories
999
+
1000
+ def _retrieve_core_memories(self, query: str) -> List[Dict[str, Any]]:
1001
+ """بازیابی حافظه‌های هسته"""
1002
+ memories = []
1003
+ query_lower = query.lower()
1004
+
1005
+ for core_entry in self.memory_layers['core']:
1006
+ node = core_entry['node']
1007
+ info = core_entry.get('info', {})
1008
+
1009
+ # بررسی تطابق با query
1010
+ relevance = 0.0
1011
+
1012
+ # تطابق با اطلاعات شخصی
1013
+ for key, value in info.items():
1014
+ if isinstance(value, str) and value.lower() in query_lower:
1015
+ relevance = 0.9
1016
+ break
1017
+
1018
+ # تطابق با محتوای پیام
1019
+ if relevance == 0.0 and node.content.lower() in query_lower:
1020
+ relevance = 0.7
1021
+
1022
+ if relevance > 0.5:
1023
+ memories.append({
1024
+ 'node': node,
1025
+ 'source': 'core',
1026
+ 'relevance': relevance,
1027
+ 'recency': 0.8,
1028
+ 'importance': 1.0,
1029
+ 'personal_info': info
1030
+ })
1031
+
1032
+ return memories
1033
+
1034
+ def _deduplicate_memories(self, memories: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1035
+ """حذف حافظه‌های تکراری"""
1036
+ seen_ids = set()
1037
+ unique_memories = []
1038
+
1039
+ for memory in memories:
1040
+ node = memory.get('node')
1041
+ if node and node.id not in seen_ids:
1042
+ seen_ids.add(node.id)
1043
+ unique_memories.append(memory)
1044
+
1045
+ return unique_memories
1046
+
1047
+ def _prioritize_memories(self, memories: List[Dict[str, Any]],
1048
+ query_embedding: np.ndarray) -> List[Dict[str, Any]]:
1049
+ """اولویت‌بندی حافظه‌های بازیابی شده"""
1050
+
1051
+ def calculate_priority(memory: Dict[str, Any]) -> float:
1052
+ """محاسبه اولویت برای یک حافظه"""
1053
+ priority = 0.0
1054
+
1055
+ # 1. ارتباط معنایی
1056
+ priority += memory.get('relevance', 0.0) * 0.4
1057
+
1058
+ # 2. تازگی
1059
+ priority += memory.get('recency', 0.0) * 0.3
1060
+
1061
+ # 3. اهمیت
1062
+ priority += memory.get('importance', 0.5) * 0.2
1063
+
1064
+ # 4. منبع (حافظه هسته اولویت بالاتری دارد)
1065
+ source = memory.get('source', '')
1066
+ if source == 'core':
1067
+ priority += 0.2
1068
+ elif source == 'long_term':
1069
+ priority += 0.1
1070
+
1071
+ return priority
1072
+
1073
+ # محاسبه اولویت و مرتب‌سازی
1074
+ prioritized = []
1075
+ for memory in memories:
1076
+ priority = calculate_priority(memory)
1077
+ prioritized.append((priority, memory))
1078
+
1079
+ prioritized.sort(key=lambda x: x[0], reverse=True)
1080
+
1081
+ return [memory for _, memory in prioritized]
1082
+
1083
+ async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
1084
+ """تهیه context برای ارسال به API"""
1085
+
1086
+ # اگر query داریم، context هوشمند بازیابی کن
1087
+ if query:
1088
+ retrieved = await self.retrieve_context(query)
1089
+
1090
+ # تبدیل به فرمت API
1091
+ api_messages = []
1092
+
1093
+ # ابتدا اطلاعات پروفایل کاربر
1094
+ api_messages.append({
1095
+ 'role': 'system',
1096
+ 'content': f"User profile: {self._format_user_profile()}"
1097
+ })
1098
+
1099
+ # سپس حافظه‌های بازیابی شده
1100
+ for memory in retrieved:
1101
+ node = memory['node']
1102
+ api_messages.append({
1103
+ 'role': node.role,
1104
+ 'content': node.content
1105
+ })
1106
+
1107
+ return api_messages
1108
+
1109
+ else:
1110
+ # حالت ساده: فقط حافظه فعال
1111
+ api_messages = []
1112
+
1113
+ for node in list(self.memory_layers['working'])[-6:]:
1114
+ api_messages.append({
1115
+ 'role': node.role,
1116
+ 'content': node.content
1117
+ })
1118
+
1119
+ return api_messages
1120
+
1121
+ def _format_user_profile(self) -> str:
1122
+ """قالب‌بندی پروفایل کاربر برای سیستم"""
1123
+ profile_parts = []
1124
+
1125
+ if self.user_profile.interests:
1126
+ interests_str = ', '.join(list(self.user_profile.interests)[:5])
1127
+ profile_parts.append(f"Interests: {interests_str}")
1128
+
1129
+ if self.user_profile.preferences:
1130
+ prefs = list(self.user_profile.preferences.items())[:3]
1131
+ prefs_str = ', '.join(f"{k}: {v}" for k, v in prefs)
1132
+ profile_parts.append(f"Preferences: {prefs_str}")
1133
+
1134
+ if self.user_profile.conversation_style:
1135
+ profile_parts.append(f"Conversation style: {self.user_profile.conversation_style}")
1136
+
1137
+ if self.user_profile.learning_style:
1138
+ profile_parts.append(f"Learning style: {self.user_profile.learning_style}")
1139
+
1140
+ if profile_parts:
1141
+ return ' | '.join(profile_parts)
1142
+ else:
1143
+ return "New user, minimal profile information available."
1144
+
1145
+ def get_summary(self) -> Dict[str, Any]:
1146
+ """دریافت خلاصه وضعیت"""
1147
+ return {
1148
+ 'user_id': self.user_id,
1149
+ 'total_messages': self.stats['total_messages'],
1150
+ 'working_memory': len(self.memory_layers['working']),
1151
+ 'recent_memory': len(self.memory_layers['recent']),
1152
+ 'long_term_memory': len(self.memory_layers['long_term']),
1153
+ 'core_memory': len(self.memory_layers['core']),
1154
+ 'profile_interests': list(self.user_profile.interests)[:10],
1155
+ 'average_importance': self.stats['average_importance'],
1156
+ 'compression_ratio': self.stats.get('compressed_messages', 0) / max(self.stats['total_messages'], 1),
1157
+ 'retrieval_efficiency': self.stats.get('retrieved_memories', 0) / max(self.stats['total_messages'], 1)
1158
+ }
1159
+
1160
+ def clear_context(self):
1161
+ """پاک کردن context کاربر"""
1162
+ self.memory_layers['working'].clear()
1163
+ self.memory_layers['ephemeral'].clear()
1164
+
1165
+ # حافظه هسته و بلندمدت پاک نمی‌شوند
1166
+ logger.info(f"Cleared context for user {self.user_id}")
1167
+
1168
+ def export_debug_info(self) -> Dict[str, Any]:
1169
+ """دریافت اطلاعات دیباگ"""
1170
+ return {
1171
+ 'memory_graph_size': len(self.memory_graph.nodes),
1172
+ 'memory_graph_connections': len(self.memory_graph.connections),
1173
+ 'user_profile': {
1174
+ 'interests_count': len(self.user_profile.interests),
1175
+ 'preferences_count': len(self.user_profile.preferences),
1176
+ 'personality_traits': dict(self.user_profile.personality_traits)
1177
+ },
1178
+ 'layer_sizes': {k: len(v) for k, v in self.memory_layers.items()},
1179
+ 'stats': dict(self.stats)
1180
+ }
BOT/render-main/system_instruction_handlers.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # system_instruction_handlers.py
2
+
3
+ import logging
4
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
5
+ from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
6
+ from datetime import datetime
7
+ import data_manager
8
+ from admin_panel import ADMIN_IDS
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ def is_group_admin(update: Update) -> bool:
13
+ """بررسی اینکه آیا کاربر ادمین گروه است یا خیر"""
14
+ if not update.effective_chat.type in ['group', 'supergroup']:
15
+ return False
16
+
17
+ try:
18
+ chat_id = update.effective_chat.id
19
+ user_id = update.effective_user.id
20
+
21
+ # دریافت لیست ادمین‌های گروه
22
+ chat_admins = update.effective_chat.get_administrators()
23
+
24
+ # بررسی اینکه کاربر در لیست ادمین‌ها باشد
25
+ for admin in chat_admins:
26
+ if admin.user.id == user_id:
27
+ return True
28
+
29
+ # بررسی اینکه آیا کاربر ادمین ربات است
30
+ if user_id in ADMIN_IDS:
31
+ return True
32
+
33
+ return False
34
+
35
+ except Exception as e:
36
+ logger.error(f"Error checking group admin status: {e}")
37
+ return False
38
+
39
+ def check_admin_permission(update: Update) -> tuple:
40
+ """
41
+ بررسی مجوز کاربر برای دسترسی به system instruction
42
+ بازگشت: (is_allowed, is_admin_bot, is_admin_group, message)
43
+ """
44
+ user_id = update.effective_user.id
45
+ chat = update.effective_chat
46
+
47
+ is_admin_bot = user_id in ADMIN_IDS
48
+ is_admin_group = is_group_admin(update)
49
+
50
+ if chat.type in ['group', 'supergroup']:
51
+ # در گروه: باید ادمین گروه یا ادمین ربات باشد
52
+ if not (is_admin_bot or is_admin_group):
53
+ return False, False, False, "⛔️ فقط ادمین‌های گروه یا ربات می‌توانند از دستورات System Instruction استفاده کنند."
54
+ else:
55
+ # در چت خصوصی: فقط ادمین ربات مجاز است
56
+ if not is_admin_bot:
57
+ return False, False, False, "⛔️ فقط ادمین‌های ربات می‌توانند از دستورات System Instruction استفاده کنند."
58
+
59
+ return True, is_admin_bot, is_admin_group, ""
60
+
61
+ def check_global_permission(update: Update) -> tuple:
62
+ """
63
+ بررسی مجوز برای دسترسی به global instruction
64
+ فقط ادمین ربات مجاز است
65
+ """
66
+ user_id = update.effective_user.id
67
+
68
+ if user_id not in ADMIN_IDS:
69
+ return False, False, "⛔️ فقط ادمین‌های ربات می‌توانند به Global System Instruction دسترسی داشته باشند."
70
+
71
+ return True, True, ""
72
+
73
+ async def set_system_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
74
+ """تنظیم system instruction - فقط برای ادمین‌ها"""
75
+ # بررسی مجوز
76
+ allowed, is_admin_bot, is_admin_group, message = check_admin_permission(update)
77
+ if not allowed:
78
+ await update.message.reply_text(message)
79
+ return
80
+
81
+ user_id = update.effective_user.id
82
+ chat = update.effective_chat
83
+
84
+ if not context.args:
85
+ await update.message.reply_text(
86
+ "⚠️ لطفاً دستور system instruction را وارد کنید.\n\n"
87
+ "مثال:\n"
88
+ "/system تو یک دستیار فارسی هستی. همیشه با ادب و مفید پاسخ بده.\n\n"
89
+ "برای حذف:\n"
90
+ "/system clear\n\n"
91
+ "برای مشاهده وضعیت فعلی:\n"
92
+ "/system_status"
93
+ )
94
+ return
95
+
96
+ instruction_text = " ".join(context.args)
97
+
98
+ if instruction_text.lower() == 'clear':
99
+ # حذف system instruction
100
+ if chat.type in ['group', 'supergroup']:
101
+ # حذف برای گروه
102
+ if is_admin_bot or is_admin_group:
103
+ if data_manager.remove_group_system_instruction(chat.id):
104
+ await update.message.reply_text("✅ system instruction گروه حذف شد.")
105
+ else:
106
+ await update.message.reply_text("⚠️ system instruction گروه وجود نداشت.")
107
+ else:
108
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
109
+ else:
110
+ # حذف برای کاربر (فقط ادمین ربات)
111
+ if is_admin_bot:
112
+ if data_manager.remove_user_system_instruction(user_id):
113
+ await update.message.reply_text("✅ system instruction شخصی شما حذف شد.")
114
+ else:
115
+ await update.message.reply_text("⚠️ system instruction شخصی وجود نداشت.")
116
+ else:
117
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی را حذف کنند.")
118
+ return
119
+
120
+ # تنظیم system instruction جدید
121
+ if chat.type in ['group', 'supergroup']:
122
+ # تنظیم برای گروه
123
+ if is_admin_bot or is_admin_group:
124
+ if data_manager.set_group_system_instruction(chat.id, instruction_text, user_id):
125
+ instruction_preview = instruction_text[:100] + "..." if len(instruction_text) > 100 else instruction_text
126
+ await update.message.reply_text(
127
+ f"✅ system instruction گروه تنظیم شد:\n\n"
128
+ f"{instruction_preview}\n\n"
129
+ f"از این پس تمام پاسخ‌های ربات در این گروه با این دستور تنظیم خواهد شد."
130
+ )
131
+ else:
132
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
133
+ else:
134
+ await update.message.reply_text("⛔️ فقط ادمین‌های گروه یا ربات می‌توانند system instruction را تنظیم کنند.")
135
+ else:
136
+ # تنظیم برای کاربر (فقط ادمین ربات)
137
+ if is_admin_bot:
138
+ if data_manager.set_user_system_instruction(user_id, instruction_text, user_id):
139
+ instruction_preview = instruction_text[:100] + "..." if len(instruction_text) > 100 else instruction_text
140
+ await update.message.reply_text(
141
+ f"✅ system instruction شخصی تنظیم شد:\n\n"
142
+ f"{instruction_preview}\n\n"
143
+ f"از این پس تمام پاسخ‌های ربات به شما با این دستور تنظیم خواهد شد."
144
+ )
145
+ else:
146
+ await update.message.reply_text("❌ خطا در تنظیم system instruction.")
147
+ else:
148
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction شخصی تنظیم کنند.")
149
+
150
+ async def system_instruction_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
151
+ """نمایش وضعیت system instruction فعلی - با محدودیت دسترسی"""
152
+ user_id = update.effective_user.id
153
+ chat = update.effective_chat
154
+
155
+ is_admin_bot = user_id in ADMIN_IDS
156
+ is_admin_group = is_group_admin(update)
157
+
158
+ if chat.type in ['group', 'supergroup']:
159
+ # در گروه
160
+ if not (is_admin_bot or is_admin_group):
161
+ await update.message.reply_text(
162
+ "⚙️ **System Instruction گروه:**\n\n"
163
+ "تنظیمات System Instruction فقط برای ادمین‌های گروه قابل مشاهده است.\n"
164
+ "برای مشاهده وضعیت فعلی، با ادمین‌های گروه تماس بگیرید."
165
+ )
166
+ return
167
+
168
+ # کاربر مجاز است (ادمین ربات یا ادمین گروه)
169
+ if is_admin_bot:
170
+ # ادمین ربات: می‌تواند global و group instruction را ببیند
171
+ await show_admin_bot_status(update, context, chat.id, user_id, in_group=True)
172
+ else:
173
+ # ادمین گروه (نه ادمین ربات): فقط group instruction گروه خودش را می‌بیند
174
+ await show_group_admin_status(update, context, chat.id)
175
+ else:
176
+ # در چت خصوصی
177
+ if not is_admin_bot:
178
+ await update.message.reply_text(
179
+ "⚙️ **System Instruction:**\n\n"
180
+ "تنظیمات System Instruction فقط برای ادمین‌های ربات قابل مشاهده است."
181
+ )
182
+ return
183
+
184
+ # ادمین ربات در چت خصوصی
185
+ await show_admin_bot_status(update, context, None, user_id, in_group=False)
186
+
187
+ async def show_group_admin_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int):
188
+ """نمایش وضعیت برای ادمین گروه (نه ادمین ربات)"""
189
+ # فقط system instruction گروه را نشان بده
190
+ info = data_manager.get_system_instruction_info(chat_id=chat_id)
191
+
192
+ if info['type'] == 'group' and info['has_instruction']:
193
+ # نمایش اطلاعات group instruction
194
+ details = info['details']
195
+ instruction_preview = info['instruction'][:200] + "..." if len(info['instruction']) > 200 else info['instruction']
196
+ set_at = details.get('set_at', 'نامشخص')
197
+ set_by = details.get('set_by', 'نامشخص')
198
+ enabled = details.get('enabled', True)
199
+
200
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
201
+
202
+ status_text = (
203
+ f"👥 **System Instruction گروه شما:**\n\n"
204
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
205
+ f"📅 **زمان تنظیم:** {set_at}\n"
206
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
207
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
208
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
209
+ )
210
+
211
+ # دکمه‌های مدیریت فقط برای group instruction
212
+ keyboard = [
213
+ [
214
+ InlineKeyboardButton("✏️ ویرایش", callback_data=f"system_edit:group:{chat_id}"),
215
+ InlineKeyboardButton("🗑️ حذف", callback_data=f"system_delete:group:{chat_id}")
216
+ ]
217
+ ]
218
+
219
+ if enabled:
220
+ keyboard.append([
221
+ InlineKeyboardButton("🚫 غیرفعال", callback_data=f"system_toggle:group:{chat_id}")
222
+ ])
223
+ else:
224
+ keyboard.append([
225
+ InlineKeyboardButton("✅ فعال", callback_data=f"system_toggle:group:{chat_id}")
226
+ ])
227
+
228
+ reply_markup = InlineKeyboardMarkup(keyboard)
229
+ else:
230
+ # هیچ system instruction برای گروه تنظیم نشده
231
+ status_text = (
232
+ f"👥 **System Instruction گروه شما:**\n\n"
233
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
234
+ f"برای تنظیم از دستور زیر استفاده کنید:\n"
235
+ f"`/system [متن دستور]`\n\n"
236
+ f"در حال حاضر از تنظیمات global ربات استفاده می‌شود."
237
+ )
238
+
239
+ # فقط دکمه تنظیم
240
+ keyboard = [
241
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")]
242
+ ]
243
+ reply_markup = InlineKeyboardMarkup(keyboard)
244
+
245
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
246
+
247
+ async def show_admin_bot_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int = None, user_id: int = None, in_group: bool = False):
248
+ """نمایش وضعیت برای ادمین ربات"""
249
+ if in_group and chat_id:
250
+ # ادمین ربات در گروه
251
+ group_info = data_manager.get_system_instruction_info(chat_id=chat_id)
252
+ global_info = data_manager.get_system_instruction_info()
253
+
254
+ if group_info['type'] == 'group' and group_info['has_instruction']:
255
+ # گروه system instruction دارد
256
+ details = group_info['details']
257
+ instruction_preview = group_info['instruction'][:200] + "..." if len(group_info['instruction']) > 200 else group_info['instruction']
258
+ set_at = details.get('set_at', 'نامشخص')
259
+ set_by = details.get('set_by', 'نامشخص')
260
+ enabled = details.get('enabled', True)
261
+
262
+ enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
263
+
264
+ status_text = (
265
+ f"👥 **System Instruction گروه:**\n\n"
266
+ f"📝 **محتوا:**\n{instruction_preview}\n\n"
267
+ f"📅 **زمان تنظیم:** {set_at}\n"
268
+ f"👤 **تنظیم‌کننده:** {set_by}\n"
269
+ f"🔄 **وضعیت:** {enabled_status}\n\n"
270
+ f"ℹ️ این تنظیمات فقط برای این گروه اعمال می‌شود."
271
+ )
272
+
273
+ # دکمه‌های مدیریت برای group instruction
274
+ keyboard = [
275
+ [
276
+ InlineKeyboardButton("✏️ ویرایش گروه", callback_data=f"system_edit:group:{chat_id}"),
277
+ InlineKeyboardButton("🗑️ حذف گروه", callback_data=f"system_delete:group:{chat_id}")
278
+ ]
279
+ ]
280
+
281
+ if enabled:
282
+ keyboard.append([
283
+ InlineKeyboardButton("🚫 غیرفعال گروه", callback_data=f"system_toggle:group:{chat_id}")
284
+ ])
285
+ else:
286
+ keyboard.append([
287
+ InlineKeyboardButton("✅ فعال گروه", callback_data=f"system_toggle:group:{chat_id}")
288
+ ])
289
+
290
+ # دکمه برای مشاهده global instruction
291
+ keyboard.append([
292
+ InlineKeyboardButton("🌐 مشاهده Global", callback_data="system_show_global")
293
+ ])
294
+
295
+ reply_markup = InlineKeyboardMarkup(keyboard)
296
+ else:
297
+ # گروه system instruction ندارد
298
+ global_preview = global_info['instruction'][:200] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
299
+
300
+ status_text = (
301
+ f"👥 **System Instruction گروه:**\n\n"
302
+ f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
303
+ f"🌐 **در حال استفاده از Global:**\n"
304
+ f"{global_preview}\n\n"
305
+ f"برای تنظیم system instruction مخصوص این گروه از دستور `/system [متن]` استفاده کنید."
306
+ )
307
+
308
+ keyboard = [
309
+ [InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")],
310
+ [InlineKeyboardButton("🌐 مشاهده کامل Global", callback_data="system_show_global")]
311
+ ]
312
+ reply_markup = InlineKeyboardMarkup(keyboard)
313
+ else:
314
+ # ادمین ربات در چت خصوصی
315
+ global_info = data_manager.get_system_instruction_info()
316
+ global_preview = global_info['instruction'][:200] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
317
+
318
+ status_text = (
319
+ f"🌐 **Global System Instruction:**\n\n"
320
+ f"📝 **محتوا:**\n{global_preview}\n\n"
321
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
322
+ )
323
+
324
+ keyboard = [
325
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
326
+ ]
327
+ reply_markup = InlineKeyboardMarkup(keyboard)
328
+
329
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
330
+
331
+ async def show_global_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
332
+ """نمایش کامل global instruction - فقط برای ادمین ربات"""
333
+ query = update.callback_query
334
+ if query:
335
+ await query.answer()
336
+ user_id = query.from_user.id
337
+ else:
338
+ user_id = update.effective_user.id
339
+
340
+ # بررسی مجوز
341
+ if user_id not in ADMIN_IDS:
342
+ if query:
343
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
344
+ else:
345
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مشاهده کنند.")
346
+ return
347
+
348
+ global_info = data_manager.get_system_instruction_info()
349
+ global_preview = global_info['instruction']
350
+
351
+ if len(global_preview) > 1000:
352
+ global_preview = global_preview[:1000] + "...\n\n(متن کامل به دلیل طولانی بودن نمایش داده نشد)"
353
+
354
+ status_text = (
355
+ f"🌐 **Global System Instruction (کامل):**\n\n"
356
+ f"📝 **محتوا:**\n{global_preview}\n\n"
357
+ f"ℹ️ این تنظیمات برای تمام کاربران و گروه‌هایی که تنظیمات خاصی ندارند اعمال می‌شود."
358
+ )
359
+
360
+ keyboard = [
361
+ [InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
362
+ ]
363
+ reply_markup = InlineKeyboardMarkup(keyboard)
364
+
365
+ if query:
366
+ await query.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
367
+ else:
368
+ await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
369
+
370
+ async def system_instruction_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
371
+ """نمایش راهنمای system instruction - با محدودیت دسترسی"""
372
+ user_id = update.effective_user.id
373
+ chat = update.effective_chat
374
+
375
+ is_admin_bot = user_id in ADMIN_IDS
376
+ is_admin_group = is_group_admin(update)
377
+
378
+ if chat.type in ['group', 'supergroup']:
379
+ # در گروه
380
+ if not (is_admin_bot or is_admin_group):
381
+ await update.message.reply_text(
382
+ "🤖 **راهنمای System Instruction**\n\n"
383
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
384
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های گروه یا ربات در دسترس است.\n\n"
385
+ "برای تنظیم System Instruction در این گروه، با ادمین‌های گروه تماس بگیرید."
386
+ )
387
+ return
388
+
389
+ # کاربر مجاز است
390
+ help_text = (
391
+ "🤖 **راهنمای System Instruction**\n\n"
392
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
393
+ "📋 **دستورات:**\n"
394
+ "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
395
+ "• `/system clear` - ح��ف system instruction این گروه\n"
396
+ "• `/system_status` - نمایش وضعیت فعلی\n"
397
+ "• `/system_help` - نمایش این راهنما\n\n"
398
+ )
399
+
400
+ if is_admin_bot:
401
+ help_text += (
402
+ "🎯 **دسترسی ادمین ربات:**\n"
403
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
404
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
405
+ "• برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n\n"
406
+ )
407
+ else:
408
+ help_text += (
409
+ "🎯 **دسترسی ادمین گروه:**\n"
410
+ "• فقط می‌توانید system instruction همین گروه را مشاهده و تنظیم کنید\n"
411
+ "• نمی‌توانید Global System Instruction را مشاهده کنید\n\n"
412
+ )
413
+
414
+ help_text += (
415
+ "💡 **مثال‌ها:**\n"
416
+ "• `/system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n"
417
+ "• `/system تو یک ربات جوک‌گو هستی. به هر سوالی با یک جوک پاسخ بده.`\n\n"
418
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
419
+ )
420
+ else:
421
+ # در چت خصوصی
422
+ if not is_admin_bot:
423
+ await update.message.reply_text(
424
+ "🤖 **راهنمای System Instruction**\n\n"
425
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
426
+ "⚠️ **دسترسی:** این دستورات فقط برای ادمین‌های ربات در دسترس است."
427
+ )
428
+ return
429
+
430
+ # ادمین ربات
431
+ help_text = (
432
+ "🤖 **راهنمای System Instruction**\n\n"
433
+ "System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین می‌کنند.\n\n"
434
+ "📋 **دستورات:**\n"
435
+ "• `/system_status` - نمایش وضعیت Global System Instruction\n"
436
+ "• `/system_help` - نمایش این راهنما\n\n"
437
+ "🎯 **دسترسی ادمین ربات:**\n"
438
+ "• می‌توانید Global System Instruction را مشاهده و تنظیم کنید\n"
439
+ "• می‌توانید برای هر گروه system instruction تنظیم کنید\n"
440
+ "• می‌توانید برای هر کاربر system instruction تنظیم کنید\n\n"
441
+ "🔧 **دستورات ادمین پنل برای System Instruction:**\n"
442
+ "• `/set_global_system [متن]` - تنظیم Global System Instruction\n"
443
+ "• `/set_group_system [آیدی گروه] [متن]` - تنظیم برای گروه\n"
444
+ "• `/set_user_system [آیدی کاربر] [متن]` - تنظیم برای کاربر\n"
445
+ "• `/list_system_instructions` - نمایش لیست تمام system instruction‌ها\n\n"
446
+ "⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال می‌شود و بر تمام پاسخ‌ها تأثیر می‌گذارد."
447
+ )
448
+
449
+ await update.message.reply_text(help_text, parse_mode='Markdown')
450
+
451
+ async def system_callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
452
+ """پردازش کلیک‌های دکمه‌های system instruction"""
453
+ query = update.callback_query
454
+ await query.answer()
455
+
456
+ data_parts = query.data.split(":")
457
+ action = data_parts[0]
458
+ user_id = query.from_user.id
459
+
460
+ if action == 'system_show_global':
461
+ # نمایش global instruction
462
+ await show_global_instruction(update, context)
463
+ return
464
+
465
+ if len(data_parts) < 3:
466
+ await query.message.reply_text("❌ خطا در پردازش درخواست.")
467
+ return
468
+
469
+ entity_type = data_parts[1]
470
+ entity_id = data_parts[2]
471
+
472
+ # بررسی مجوزها
473
+ if entity_type == 'global':
474
+ # فقط ادمین ربات می‌تواند global را مدیریت کند
475
+ if user_id not in ADMIN_IDS:
476
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را مدیریت کنند.")
477
+ return
478
+
479
+ entity_id_int = 0 # global entity
480
+ elif entity_type == 'group':
481
+ # بررسی اینکه آیا کاربر ادمین گروه یا ادمین ربات است
482
+ chat = query.message.chat
483
+ is_admin_bot = user_id in ADMIN_IDS
484
+ is_admin_group = is_group_admin(update)
485
+
486
+ if not (is_admin_bot or is_admin_group):
487
+ await query.message.reply_text("⛔️ شما مجوز لازم برای این کار را ندارید.")
488
+ return
489
+
490
+ try:
491
+ entity_id_int = int(entity_id)
492
+ except ValueError:
493
+ await query.message.reply_text("❌ شناسه گروه نامعتبر است.")
494
+ return
495
+ else: # user
496
+ # فقط ادمین ربات می‌تواند system instruction کاربران را تغییر دهد
497
+ if user_id not in ADMIN_IDS:
498
+ await query.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را تغییر دهند.")
499
+ return
500
+
501
+ try:
502
+ entity_id_int = int(entity_id)
503
+ except ValueError:
504
+ await query.message.reply_text("❌ شناسه کاربر نامعتبر است.")
505
+ return
506
+
507
+ if action == 'system_delete':
508
+ # حذف system instruction
509
+ if entity_type == 'global':
510
+ # حذف global (در واقع تنظیم مجدد به پیش‌فرض)
511
+ default_instruction = "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد."
512
+ if data_manager.set_global_system_instruction(default_instruction):
513
+ await query.message.reply_text("✅ Global System Instruction به حالت پیش‌فرض بازگردانده شد.")
514
+ else:
515
+ await query.message.reply_text("❌ خطا در بازگرداندن Global System Instruction.")
516
+ elif entity_type == 'group':
517
+ success = data_manager.remove_group_system_instruction(entity_id_int)
518
+ message = "✅ system instruction گروه حذف شد." if success else "⚠️ system instruction گروه وجود نداشت."
519
+ else:
520
+ success = data_manager.remove_user_system_instruction(entity_id_int)
521
+ message = "✅ system instruction کاربر حذف شد." if success else "⚠️ system instruction کاربر وجود نداشت."
522
+
523
+ if entity_type != 'global':
524
+ await query.message.reply_text(message)
525
+
526
+ await query.message.delete()
527
+
528
+ elif action == 'system_toggle':
529
+ # فعال/غیرفعال کردن system instruction
530
+ if entity_type == 'global':
531
+ await query.message.reply_text("⚠️ Global System Instruction را نمی‌توان غیرفعال کرد.")
532
+ return
533
+
534
+ info = data_manager.get_system_instruction_info(
535
+ user_id=entity_id_int if entity_type == 'user' else None,
536
+ chat_id=entity_id_int if entity_type == 'group' else None
537
+ )
538
+
539
+ if info['type'] == entity_type and info['details']:
540
+ current_enabled = info['details'].get('enabled', True)
541
+ new_enabled = not current_enabled
542
+
543
+ if entity_type == 'group':
544
+ success = data_manager.toggle_group_system_instruction(entity_id_int, new_enabled)
545
+ else:
546
+ success = data_manager.toggle_user_system_instruction(entity_id_int, new_enabled)
547
+
548
+ if success:
549
+ status = "✅ فعال شد" if new_enabled else "🚫 غیرفعال شد"
550
+ await query.message.reply_text(f"system instruction {status}.")
551
+
552
+ # به‌روزرسانی پیام اصلی
553
+ if entity_type == 'group':
554
+ await show_group_admin_status(update, context, entity_id_int)
555
+ else:
556
+ await system_instruction_status(update, context)
557
+ else:
558
+ await query.message.reply_text("❌ خطا در تغییر وضعیت system instruction.")
559
+
560
+ elif action == 'system_edit':
561
+ # ویرایش system instruction
562
+ if entity_type == 'global':
563
+ instruction_type = "Global"
564
+ elif entity_type == 'group':
565
+ instruction_type = "گروه"
566
+ else:
567
+ instruction_type = "کاربر"
568
+
569
+ await query.message.reply_text(
570
+ f"لطفاً system instruction جدید برای {instruction_type} را وارد کنید:\n\n"
571
+ "برای لغو: /cancel"
572
+ )
573
+
574
+ # ذخیره اطلاعات برای مرحله بعد
575
+ context.user_data['system_edit'] = {
576
+ 'entity_type': entity_type,
577
+ 'entity_id': entity_id_int,
578
+ 'message_id': query.message.message_id
579
+ }
580
+
581
+ async def handle_system_edit(update: Update, context: ContextTypes.DEFAULT_TYPE):
582
+ """پردازش ویرایش system instruction"""
583
+ # بررسی مجوز اولیه
584
+ user_id = update.effective_user.id
585
+ chat = update.effective_chat
586
+
587
+ if 'system_edit' not in context.user_data:
588
+ return
589
+
590
+ if update.message.text.lower() == '/cancel':
591
+ del context.user_data['system_edit']
592
+ await update.message.reply_text("ویرایش system instruction لغو شد.")
593
+ return
594
+
595
+ edit_data = context.user_data['system_edit']
596
+ entity_type = edit_data['entity_type']
597
+ entity_id = edit_data['entity_id']
598
+
599
+ # بررسی مجوزهای خاص
600
+ if entity_type == 'global':
601
+ if user_id not in ADMIN_IDS:
602
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند Global System Instruction را ویرایش کنند.")
603
+ del context.user_data['system_edit']
604
+ return
605
+ elif entity_type == 'group':
606
+ is_admin_bot = user_id in ADMIN_IDS
607
+ is_admin_group = is_group_admin(update)
608
+
609
+ if not (is_admin_bot or is_admin_group):
610
+ await update.message.reply_text("⛔️ شما مجوز لازم برای ویرایش system instruction این گروه را ندارید.")
611
+ del context.user_data['system_edit']
612
+ return
613
+ else: # user
614
+ if user_id not in ADMIN_IDS:
615
+ await update.message.reply_text("⛔️ فقط ادمین‌های ربات می‌توانند system instruction کاربران را ویرایش کنند.")
616
+ del context.user_data['system_edit']
617
+ return
618
+
619
+ instruction_text = update.message.text
620
+
621
+ if entity_type == 'global':
622
+ success = data_manager.set_global_system_instruction(instruction_text)
623
+ message = "✅ Global System Instruction به‌روزرسانی شد."
624
+ elif entity_type == 'group':
625
+ success = data_manager.set_group_system_instruction(entity_id, instruction_text, user_id)
626
+ message = "✅ system instruction گروه به‌روزرسانی شد."
627
+ else:
628
+ success = data_manager.set_user_system_instruction(entity_id, instruction_text, user_id)
629
+ message = "✅ system instruction کاربر به‌روزرسانی شد."
630
+
631
+ if success:
632
+ await update.message.reply_text(message)
633
+ del context.user_data['system_edit']
634
+
635
+ # نمایش وضعیت جدید
636
+ await system_instruction_status(update, context)
637
+ else:
638
+ await update.message.reply_text("❌ خطا در به‌روزرسانی system instruction.")
639
+
640
+ def setup_system_instruction_handlers(application):
641
+ """تنظیم هندلرهای system instruction"""
642
+ application.add_handler(CommandHandler("system", set_system_instruction))
643
+ application.add_handler(CommandHandler("system_status", system_instruction_status))
644
+ application.add_handler(CommandHandler("system_help", system_instruction_help))
645
+
646
+ # هندلر برای نمایش global instruction
647
+ application.add_handler(CommandHandler("show_global", show_global_instruction))
648
+
649
+ application.add_handler(CallbackQueryHandler(system_callback_handler, pattern="^system_"))
650
+
651
+ # هندلر برای ویرایش system instruction
652
+ application.add_handler(MessageHandler(
653
+ filters.TEXT & ~filters.COMMAND,
654
+ handle_system_edit
655
+ ))
656
+
657
+ logger.info("System instruction handlers have been set up.")
BOT/render-main/test.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+
3
+ client = OpenAI(
4
+ base_url="https://api.featherless.ai/v1",
5
+ api_key="rc_4bb6c9bd28931d1a92836edd6a91f971da5ce2d4477a693eb2d760eb37f02c4b",
6
+ )
7
+
8
+ response = client.chat.completions.create(
9
+ model='mlabonne/NeuralDaredevil-8B-abliterated',
10
+ messages=[
11
+ {"role": "system", "content": "تو یک دستیار فارسی زبان هستی"},
12
+ {"role": "user", "content": "سلام"}
13
+ ],
14
+ )
15
+ print(response.model_dump()['choices'][0]['message']['content'])