Datasets:
Download BOT/2/data_manager.py from ysn-rfd/text-dataset-tiny-code-script-py-format: direct link, hf CLI and curl.
- Browser
- Download file 36 kB
-
https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/BOT/2/data_manager.py
- Command line
-
hf download hf://datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/BOT/2/data_manager.py
-
curl -L -o data_manager.py https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/BOT/2/data_manager.py
36 kB
| # data_manager.py | |
| import os | |
| import json | |
| import logging | |
| from datetime import datetime, timedelta | |
| import tiktoken | |
| import threading | |
| # --- افزودن قفل برای ایمنی thread-safe --- | |
| DATA_LOCK = threading.Lock() | |
| # --- تنظیمات مسیر فایلها --- | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| DATA_FILE = os.path.join(BASE_DIR, "bot_data.json") | |
| LOG_FILE = os.path.join(BASE_DIR, "bot.log") | |
| # --- کش دادههای گلوبال --- | |
| DATA = { | |
| "users": {}, | |
| "groups": {}, | |
| "banned_users": set(), | |
| "stats": { | |
| "total_messages": 0, | |
| "total_users": 0, | |
| "total_groups": 0, | |
| "avg_response_time": 0.0, | |
| "max_response_time": 0.0, | |
| "min_response_time": float('inf'), | |
| "total_responses": 0 | |
| }, | |
| "welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.", | |
| "group_welcome_message": "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید", | |
| "goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!", | |
| "maintenance_mode": False, | |
| "blocked_words": [], | |
| "scheduled_broadcasts": [], | |
| "bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| "context_mode": "separate", | |
| "system_instructions": { | |
| "global": "شما یک دستیار هوشمند فارسی هستید. پاسخهای شما باید مفید، دقیق و دوستانه باشد. از کلمات فارسی صحیح استفاده کنید و در صورت نیاز توضیحات کامل ارائه دهید.", | |
| "groups": {}, | |
| "users": {} | |
| } | |
| } | |
| logger = logging.getLogger(__name__) | |
| # --- توابع کمکی --- | |
| def count_tokens(text: str) -> int: | |
| """شمارش تعداد توکنهای متن با استفاده از tokenizer""" | |
| try: | |
| encoding = tiktoken.get_encoding("cl100k_base") | |
| return len(encoding.encode(text)) | |
| except Exception as e: | |
| logger.warning(f"Error counting tokens: {e}, using fallback") | |
| return max(1, len(text) // 4) | |
| def load_data(): | |
| """دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند.""" | |
| global DATA | |
| with DATA_LOCK: | |
| try: | |
| if not os.path.exists(DATA_FILE): | |
| logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.") | |
| save_data() | |
| return | |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: | |
| loaded_data = json.load(f) | |
| loaded_data['banned_users'] = set(loaded_data.get('banned_users', [])) | |
| # اطمینان از وجود کلیدهای جدید | |
| if 'groups' not in loaded_data: loaded_data['groups'] = {} | |
| if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'separate' | |
| if 'group_welcome_message' not in loaded_data: | |
| loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..." | |
| if 'total_groups' not in loaded_data.get('stats', {}): | |
| if 'stats' not in loaded_data: loaded_data['stats'] = {} | |
| loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {})) | |
| # تبدیل اعضای گروه از list به set | |
| for group_id in loaded_data.get('groups', {}): | |
| if 'members' in loaded_data['groups'][group_id]: | |
| # اگر members یک list است، آن را به set تبدیل کن | |
| if isinstance(loaded_data['groups'][group_id]['members'], list): | |
| loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members']) | |
| elif not isinstance(loaded_data['groups'][group_id]['members'], set): | |
| # اگر نه list است نه set، آن را set خالی کن | |
| loaded_data['groups'][group_id]['members'] = set() | |
| else: | |
| loaded_data['groups'][group_id]['members'] = set() | |
| # اطمینان از وجود context برای گروههای قدیمی | |
| for group_id in loaded_data.get('groups', {}): | |
| if 'context' not in loaded_data['groups'][group_id]: | |
| loaded_data['groups'][group_id]['context'] = [] | |
| # اطمینان از وجود context برای کاربران قدیمی | |
| for user_id in loaded_data.get('users', {}): | |
| if 'context' not in loaded_data['users'][user_id]: | |
| loaded_data['users'][user_id]['context'] = [] | |
| # اطمینان از وجود کلیدهای آمار پاسخگویی | |
| if 'stats' in loaded_data: | |
| stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses'] | |
| for key in stats_keys: | |
| if key not in loaded_data['stats']: | |
| if key == 'min_response_time': | |
| loaded_data['stats'][key] = float('inf') | |
| else: | |
| loaded_data['stats'][key] = 0.0 | |
| # اطمینان از وجود system_instructions | |
| if 'system_instructions' not in loaded_data: | |
| loaded_data['system_instructions'] = { | |
| 'global': DATA['system_instructions']['global'], | |
| 'groups': {}, | |
| 'users': {} | |
| } | |
| if 'added_admins' not in loaded_data: | |
| loaded_data['added_admins'] = [] | |
| DATA.update(loaded_data) | |
| logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.") | |
| except json.JSONDecodeError as e: | |
| logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.") | |
| except Exception as e: | |
| logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.") | |
| def save_data(): | |
| """کش گلوبال دادهها را در فایل JSON ذخیره میکند.""" | |
| global DATA | |
| try: | |
| data_to_save = DATA.copy() | |
| data_to_save['banned_users'] = list(DATA['banned_users']) | |
| # تبدیل set اعضای گروه به list برای ذخیره JSON | |
| for group_id in data_to_save.get('groups', {}): | |
| if 'members' in data_to_save['groups'][group_id]: | |
| # اگر members یک set است، آن را به list تبدیل کن | |
| if isinstance(data_to_save['groups'][group_id]['members'], set): | |
| data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members']) | |
| elif not isinstance(data_to_save['groups'][group_id]['members'], list): | |
| # اگر نه set است نه list، آن را list خالی کن | |
| data_to_save['groups'][group_id]['members'] = [] | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(data_to_save, f, indent=4, ensure_ascii=False) | |
| logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.") | |
| except Exception as e: | |
| logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}") | |
| # --- توابع مدیریت کاربران --- | |
| def update_user_stats(user_id: int, user): | |
| """آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند.""" | |
| global DATA | |
| now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| user_id_str = str(user_id) | |
| if user_id_str not in DATA['users']: | |
| DATA['users'][user_id_str] = { | |
| 'first_name': user.first_name, | |
| 'username': user.username, | |
| 'first_seen': now_str, | |
| 'message_count': 0, | |
| 'context': [] | |
| } | |
| DATA['stats']['total_users'] += 1 | |
| logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})") | |
| DATA['users'][user_id_str]['last_seen'] = now_str | |
| DATA['users'][user_id_str]['message_count'] += 1 | |
| DATA['stats']['total_messages'] += 1 | |
| save_data() | |
| def update_response_stats(response_time: float): | |
| """آمار زمان پاسخگویی را بهروز میکند.""" | |
| global DATA | |
| if DATA['stats']['total_responses'] == 0: | |
| DATA['stats']['min_response_time'] = response_time | |
| DATA['stats']['total_responses'] += 1 | |
| # محاسبه میانگین جدید | |
| current_avg = DATA['stats']['avg_response_time'] | |
| total_responses = DATA['stats']['total_responses'] | |
| new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses | |
| DATA['stats']['avg_response_time'] = new_avg | |
| # بهروزرسانی حداکثر و حداقل زمان پاسخگویی | |
| if response_time > DATA['stats']['max_response_time']: | |
| DATA['stats']['max_response_time'] = response_time | |
| if response_time < DATA['stats']['min_response_time']: | |
| DATA['stats']['min_response_time'] = response_time | |
| save_data() | |
| # --- توابع مدیریت مسدودیت --- | |
| def is_user_banned(user_id: int) -> bool: | |
| """بررسی میکند آیا کاربر مسدود شده است یا خیر.""" | |
| return user_id in DATA['banned_users'] | |
| def ban_user(user_id: int): | |
| """کاربر را مسدود کرده و ذخیره میکند.""" | |
| DATA['banned_users'].add(user_id) | |
| save_data() | |
| def unban_user(user_id: int): | |
| """مسدودیت کاربر را برداشته و ذخیره میکند.""" | |
| DATA['banned_users'].discard(user_id) | |
| save_data() | |
| def contains_blocked_words(text: str) -> bool: | |
| """بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر.""" | |
| if not DATA['blocked_words']: | |
| return False | |
| text_lower = text.lower() | |
| for word in DATA['blocked_words']: | |
| if word in text_lower: | |
| return True | |
| return False | |
| # --- توابع مدیریت کاربران و گروهها --- | |
| def get_active_users(days: int) -> list: | |
| """لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند.""" | |
| now = datetime.now() | |
| cutoff_date = now - timedelta(days=days) | |
| active_users = [] | |
| for user_id, user_info in DATA['users'].items(): | |
| if 'last_seen' in user_info: | |
| try: | |
| last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S') | |
| if last_seen >= cutoff_date: | |
| active_users.append(int(user_id)) | |
| except ValueError: | |
| continue | |
| return active_users | |
| def get_users_by_message_count(min_count: int) -> list: | |
| """لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند.""" | |
| users = [] | |
| for user_id, user_info in DATA['users'].items(): | |
| if user_info.get('message_count', 0) >= min_count: | |
| users.append(int(user_id)) | |
| return users | |
| # --- توابع مدیریت context کاربران --- | |
| def add_to_user_context(user_id: int, role: str, content: str): | |
| """اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن""" | |
| add_to_user_context_with_reply(user_id, role, content, None) | |
| def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None): | |
| """اضافه کردن پیام به context کاربر با اطلاعات ریپلای""" | |
| user_id_str = str(user_id) | |
| if user_id_str not in DATA['users']: | |
| return | |
| if 'context' not in DATA['users'][user_id_str]: | |
| DATA['users'][user_id_str]['context'] = [] | |
| # اضافه کردن پیام جدید | |
| message = { | |
| 'role': role, | |
| 'content': content, | |
| 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| 'has_reply': False | |
| } | |
| if reply_info and 'replied_text' in reply_info and reply_info['replied_text']: | |
| message['has_reply'] = True | |
| message['reply_to_user_id'] = reply_info.get('replied_user_id') | |
| message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown') | |
| message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن | |
| message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False) | |
| message['reply_timestamp'] = reply_info.get('timestamp', time.time()) | |
| DATA['users'][user_id_str]['context'].append(message) | |
| # محدود کردن context به 16384 توکن | |
| trim_user_context(user_id, max_tokens=16384) | |
| save_data() | |
| def trim_user_context(user_id: int, max_tokens: int = 16384): | |
| """کوتاه کردن context کاربر به تعداد توکن مشخص""" | |
| user_id_str = str(user_id) | |
| if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]: | |
| return | |
| context = DATA['users'][user_id_str]['context'] | |
| if not context: | |
| return | |
| # محاسبه توکنهای کل | |
| total_tokens = sum(count_tokens(msg['content']) for msg in context) | |
| # حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد | |
| while total_tokens > max_tokens and len(context) > 1: | |
| removed_message = context.pop(0) | |
| total_tokens -= count_tokens(removed_message['content']) | |
| # اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن | |
| if total_tokens > max_tokens and context: | |
| last_message = context[-1] | |
| content = last_message['content'] | |
| tokens = count_tokens(content) | |
| if tokens > max_tokens: | |
| context.pop() | |
| else: | |
| while tokens > (max_tokens - (total_tokens - tokens)) and content: | |
| words = content.split() | |
| if len(words) > 1: | |
| content = ' '.join(words[:-1]) | |
| else: | |
| content = content[:-1] if len(content) > 1 else '' | |
| tokens = count_tokens(content) | |
| if content: | |
| context[-1]['content'] = content | |
| else: | |
| context.pop() | |
| save_data() | |
| def get_user_context(user_id: int) -> list: | |
| """دریافت context کاربر""" | |
| user_id_str = str(user_id) | |
| if user_id_str not in DATA['users']: | |
| return [] | |
| return DATA['users'][user_id_str].get('context', []) | |
| def clear_user_context(user_id: int): | |
| """پاک کردن context کاربر""" | |
| user_id_str = str(user_id) | |
| if user_id_str in DATA['users']: | |
| if 'context' in DATA['users'][user_id_str]: | |
| DATA['users'][user_id_str]['context'] = [] | |
| save_data() | |
| logger.info(f"Context cleared for user {user_id}") | |
| def get_context_summary(user_id: int) -> str: | |
| """خلاصهای از context کاربر""" | |
| context = get_user_context(user_id) | |
| if not context: | |
| return "بدون تاریخچه" | |
| total_messages = len(context) | |
| total_tokens = sum(count_tokens(msg['content']) for msg in context) | |
| # تعداد ریپلایها | |
| reply_count = sum(1 for msg in context if msg.get('has_reply', False)) | |
| # نمایش آخرین پیام | |
| last_message = context[-1] if context else {} | |
| last_content = last_message.get('content', '')[:50] | |
| if len(last_message.get('content', '')) > 50: | |
| last_content += "..." | |
| return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}" | |
| def get_context_for_api(user_id: int) -> list: | |
| """فرمت context برای ارسال به API""" | |
| context = get_user_context(user_id) | |
| api_context = [] | |
| for msg in context: | |
| api_context.append({ | |
| 'role': msg['role'], | |
| 'content': msg['content'] | |
| }) | |
| return api_context | |
| def get_context_token_count(user_id: int) -> int: | |
| """تعداد کل توکنهای context کاربر""" | |
| context = get_user_context(user_id) | |
| return sum(count_tokens(msg['content']) for msg in context) | |
| # --- توابع مدیریت گروهها --- | |
| def update_group_stats(chat_id: int, chat, user_id: int = None): | |
| """آمار گروه را بهروز کرده و دادهها را ذخیره میکند.""" | |
| global DATA | |
| now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| chat_id_str = str(chat_id) | |
| if chat_id_str not in DATA['groups']: | |
| DATA['groups'][chat_id_str] = { | |
| 'title': chat.title if hasattr(chat, 'title') else 'Private Group', | |
| 'type': chat.type, | |
| 'first_seen': now_str, | |
| 'message_count': 0, | |
| 'members': set(), | |
| 'context': [] | |
| } | |
| DATA['stats']['total_groups'] += 1 | |
| logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})") | |
| DATA['groups'][chat_id_str]['last_seen'] = now_str | |
| DATA['groups'][chat_id_str]['message_count'] += 1 | |
| # اضافه کردن کاربر به لیست اعضای گروه | |
| if user_id is not None: | |
| # اطمینان از اینکه members یک set است | |
| if 'members' not in DATA['groups'][chat_id_str]: | |
| DATA['groups'][chat_id_str]['members'] = set() | |
| elif isinstance(DATA['groups'][chat_id_str]['members'], list): | |
| # اگر members یک list است، آن را به set تبدیل کن | |
| DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members']) | |
| # اکنون اضافه کردن کاربر | |
| DATA['groups'][chat_id_str]['members'].add(user_id) | |
| save_data() | |
| def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None): | |
| """اضافه کردن پیام به context گروه و محدود کردن به 16384 توکن""" | |
| add_to_group_context_with_reply(chat_id, role, content, user_name, None) | |
| def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None): | |
| """اضافه کردن پیام به context گروه با اطلاعات ریپلای""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str not in DATA['groups']: | |
| return | |
| if 'context' not in DATA['groups'][chat_id_str]: | |
| DATA['groups'][chat_id_str]['context'] = [] | |
| # اضافه کردن نام کاربر به محتوا اگر مشخص باشد | |
| if user_name and role == 'user': | |
| content_with_name = f"{user_name}: {content}" | |
| else: | |
| content_with_name = content | |
| # اضافه کردن پیام جدید با اطلاعات ریپلای | |
| message = { | |
| 'role': role, | |
| 'content': content_with_name if role == 'user' else content, | |
| 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| 'user_name': user_name if role == 'user' else None, | |
| 'has_reply': False | |
| } | |
| if reply_info and 'replied_text' in reply_info and reply_info['replied_text']: | |
| message['has_reply'] = True | |
| message['reply_to_user_id'] = reply_info.get('replied_user_id') | |
| message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown') | |
| message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن | |
| message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False) | |
| message['reply_timestamp'] = reply_info.get('timestamp', time.time()) | |
| DATA['groups'][chat_id_str]['context'].append(message) | |
| # محدود کردن context به 32768 توکن | |
| trim_group_context(chat_id, max_tokens=32768) | |
| save_data() | |
| def optimize_group_context(chat_id: int): | |
| """بهینهسازی context گروه برای حفظ مهمترین پیامها""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]: | |
| return | |
| context = DATA['groups'][chat_id_str]['context'] | |
| if len(context) <= 10: | |
| return | |
| # محاسبه اهمیت هر پیام بر اساس عوامل مختلف | |
| scored_messages = [] | |
| for i, msg in enumerate(context): | |
| score = 0 | |
| # امتیاز بر اساس طول | |
| content_length = len(msg['content']) | |
| score += min(content_length / 100, 10) | |
| # امتیاز بر اساس تازگی | |
| recency = len(context) - i | |
| score += min(recency / 10, 20) | |
| # امتیاز بیشتر برای پاسخهای هوش مصنوعی | |
| if msg['role'] == 'assistant': | |
| score += 15 | |
| # امتیاز بیشتر برای پیامهای دارای ریپلای (مهمتر هستند) | |
| if msg.get('has_reply', False): | |
| score += 10 | |
| # امتیاز منفی برای پیامهای کوتاه و کممحتوا | |
| if content_length < 20: | |
| score -= 5 | |
| scored_messages.append((score, msg)) | |
| # مرتبسازی بر اساس امتیاز | |
| scored_messages.sort(key=lambda x: x[0], reverse=True) | |
| # حفظ 70% از پیامهای با بالاترین امتیاز | |
| keep_count = int(len(scored_messages) * 0.9) | |
| kept_messages = [msg for _, msg in scored_messages[:keep_count]] | |
| # مرتبسازی مجدد بر اساس زمان | |
| kept_messages.sort(key=lambda x: x.get('timestamp', '')) | |
| DATA['groups'][chat_id_str]['context'] = kept_messages | |
| save_data() | |
| logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages") | |
| def trim_group_context(chat_id: int, max_tokens: int = 32768): | |
| """کوتاه کردن context گروه به تعداد توکن مشخص""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]: | |
| return | |
| context = DATA['groups'][chat_id_str]['context'] | |
| if not context: | |
| return | |
| # محاسبه توکنهای کل | |
| total_tokens = sum(count_tokens(msg['content']) for msg in context) | |
| # اگر تعداد توکنها بیش از حد مجاز است، ابتدا بهینهسازی کن | |
| if total_tokens > max_tokens * 1.5: | |
| optimize_group_context(chat_id) | |
| context = DATA['groups'][chat_id_str]['context'] | |
| total_tokens = sum(count_tokens(msg['content']) for msg in context) | |
| # حذف قدیمیترین پیامها | |
| while total_tokens > max_tokens and len(context) > 1: | |
| removed_message = context.pop(0) | |
| total_tokens -= count_tokens(removed_message['content']) | |
| # اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن | |
| if total_tokens > max_tokens and context: | |
| last_message = context[-1] | |
| content = last_message['content'] | |
| tokens = count_tokens(content) | |
| if tokens > max_tokens: | |
| context.pop() | |
| else: | |
| while tokens > (max_tokens - (total_tokens - tokens)) and content: | |
| words = content.split() | |
| if len(words) > 1: | |
| content = ' '.join(words[:-1]) | |
| else: | |
| content = content[:-1] if len(content) > 1 else '' | |
| tokens = count_tokens(content) | |
| if content: | |
| context[-1]['content'] = content | |
| else: | |
| context.pop() | |
| save_data() | |
| def get_group_context(chat_id: int) -> list: | |
| """دریافت context گروه""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str not in DATA['groups']: | |
| return [] | |
| return DATA['groups'][chat_id_str].get('context', []) | |
| def get_context_for_api_group(chat_id: int) -> list: | |
| """فرمت context گروه برای ارسال به API""" | |
| context = get_group_context(chat_id) | |
| api_context = [] | |
| for msg in context: | |
| api_context.append({ | |
| 'role': msg['role'], | |
| 'content': msg['content'] | |
| }) | |
| return api_context | |
| def clear_group_context(chat_id: int): | |
| """پاک کردن context گروه""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str in DATA['groups']: | |
| if 'context' in DATA['groups'][chat_id_str]: | |
| DATA['groups'][chat_id_str]['context'] = [] | |
| save_data() | |
| logger.info(f"Context cleared for group {chat_id}") | |
| def get_group_context_summary(chat_id: int) -> str: | |
| """خلاصهای از context گروه""" | |
| context = get_group_context(chat_id) | |
| if not context: | |
| return "بدون تاریخچه" | |
| total_messages = len(context) | |
| total_tokens = sum(count_tokens(msg['content']) for msg in context) | |
| # تعداد ریپلایها | |
| reply_count = sum(1 for msg in context if msg.get('has_reply', False)) | |
| last_message = context[-1] if context else {} | |
| last_content = last_message.get('content', '')[:50] | |
| if len(last_message.get('content', '')) > 50: | |
| last_content += "..." | |
| return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('user_name', last_message.get('role', ''))}: {last_content}" | |
| # --- توابع ترکیبی (User + Group) --- | |
| def add_to_hybrid_context(user_id: int, chat_id: int, role: str, content: str, user_name: str = None): | |
| """ | |
| اضافه کردن پیام به context ترکیبی | |
| هم در context کاربر و هم در context گروه ذخیره میشود | |
| """ | |
| # ذخیره در context کاربر | |
| add_to_user_context(user_id, role, content) | |
| # ذخیره در context گروه | |
| add_to_group_context(chat_id, role, content, user_name) | |
| 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): | |
| """ | |
| اضافه کردن پیام به context ترکیبی با اطلاعات ریپلای | |
| هم در context کاربر و هم در context گروه ذخیره میشود | |
| """ | |
| # ذخیره در context کاربر | |
| add_to_user_context_with_reply(user_id, role, content, reply_info) | |
| # ذخیره در context گروه | |
| add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info) | |
| def get_hybrid_context_for_api(user_id: int, chat_id: int) -> list: | |
| """ | |
| دریافت context ترکیبی برای ارسال به API | |
| ترکیب هوشمندانه context کاربر و گروه | |
| """ | |
| group_context = get_context_for_api_group(chat_id) | |
| user_context = get_context_for_api(user_id) | |
| # ترکیب contextها به صورت هوشمند | |
| combined_context = [] | |
| # ابتدا system instruction (اگر در context گروه یا کاربر وجود دارد) | |
| system_messages = [] | |
| for msg in group_context: | |
| if msg['role'] == 'system': | |
| system_messages.append(msg) | |
| for msg in user_context: | |
| if msg['role'] == 'system' and msg not in system_messages: | |
| system_messages.append(msg) | |
| # اضافه کردن system instructionها | |
| combined_context.extend(system_messages) | |
| # ترکیب پیامهای گروه و کاربر | |
| # برای حفظ جریان مکالمه، به ترتیب زمانی ترکیب میکنیم | |
| all_messages = [] | |
| # پیامهای گروه با اطلاعات زمان | |
| for msg in group_context: | |
| if msg['role'] != 'system': | |
| all_messages.append({ | |
| 'source': 'group', | |
| 'role': msg['role'], | |
| 'content': msg['content'], | |
| 'timestamp': msg.get('timestamp', '') | |
| }) | |
| # پیامهای کاربر با اطلاعات زمان | |
| for msg in user_context: | |
| if msg['role'] != 'system': | |
| all_messages.append({ | |
| 'source': 'user', | |
| 'role': msg['role'], | |
| 'content': msg['content'], | |
| 'timestamp': msg.get('timestamp', '') | |
| }) | |
| # مرتبسازی بر اساس زمان | |
| all_messages.sort(key=lambda x: x.get('timestamp', '')) | |
| # محدود کردن به 30 پیام آخر برای حفظ کارایی | |
| recent_messages = all_messages[-30:] if len(all_messages) > 30 else all_messages | |
| # تبدیل به فرمت API | |
| for msg in recent_messages: | |
| # در حالت hybrid، نام کاربر در محتوای پیامهای user ذخیره میشود | |
| if msg['source'] == 'group' and 'user_name:' in msg['content']: | |
| # پیامهای گروه که حاوی نام کاربر هستند | |
| combined_context.append({ | |
| 'role': msg['role'], | |
| 'content': msg['content'] | |
| }) | |
| elif msg['source'] == 'user': | |
| # پیامهای شخصی کاربر | |
| combined_context.append({ | |
| 'role': msg['role'], | |
| 'content': msg['content'] | |
| }) | |
| # اگر تعداد پیامها کم است، از context گروه استفاده کن | |
| if len(combined_context) < 5 and group_context: | |
| # فقط پیامهای اخیر گروه | |
| recent_group = [msg for msg in group_context if msg['role'] != 'system'][-10:] | |
| combined_context.extend(recent_group) | |
| return combined_context | |
| # --- توابع مدیریت حالت context --- | |
| def get_context_mode() -> str: | |
| """دریافت حالت فعلی context""" | |
| return DATA.get('context_mode', 'separate') | |
| def set_context_mode(mode: str): | |
| """تنظیم حالت context""" | |
| valid_modes = ['separate', 'group_shared', 'hybrid'] | |
| if mode in valid_modes: | |
| DATA['context_mode'] = mode | |
| save_data() | |
| logger.info(f"Context mode changed to: {mode}") | |
| return True | |
| return False | |
| # --- توابع مدیریت system instructions --- | |
| def get_system_instruction(user_id: int = None, chat_id: int = None) -> str: | |
| """دریافت system instruction مناسب برای کاربر/گروه""" | |
| # اولویت: کاربر > گروه > سراسری | |
| user_id_str = str(user_id) if user_id else None | |
| chat_id_str = str(chat_id) if chat_id else None | |
| # بررسی برای کاربر | |
| if user_id_str and user_id_str in DATA['system_instructions']['users']: | |
| instruction_data = DATA['system_instructions']['users'][user_id_str] | |
| if instruction_data.get('enabled', True): | |
| return instruction_data.get('instruction', '') | |
| # بررسی برای گروه | |
| if chat_id_str and chat_id_str in DATA['system_instructions']['groups']: | |
| instruction_data = DATA['system_instructions']['groups'][chat_id_str] | |
| if instruction_data.get('enabled', True): | |
| return instruction_data.get('instruction', '') | |
| # بازگشت به حالت سراسری | |
| return DATA['system_instructions'].get('global', '') | |
| def set_global_system_instruction(instruction: str) -> bool: | |
| """تنظیم system instruction سراسری""" | |
| DATA['system_instructions']['global'] = instruction | |
| save_data() | |
| return True | |
| def set_group_system_instruction(chat_id: int, instruction: str, set_by_user_id: int) -> bool: | |
| """تنظیم system instruction برای گروه""" | |
| chat_id_str = str(chat_id) | |
| DATA['system_instructions']['groups'][chat_id_str] = { | |
| 'instruction': instruction, | |
| 'set_by': set_by_user_id, | |
| 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| 'enabled': True | |
| } | |
| save_data() | |
| return True | |
| def set_user_system_instruction(user_id: int, instruction: str, set_by_user_id: int) -> bool: | |
| """تنظیم system instruction برای کاربر""" | |
| user_id_str = str(user_id) | |
| DATA['system_instructions']['users'][user_id_str] = { | |
| 'instruction': instruction, | |
| 'set_by': set_by_user_id, | |
| 'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| 'enabled': True | |
| } | |
| save_data() | |
| return True | |
| def remove_group_system_instruction(chat_id: int) -> bool: | |
| """حذف system instruction گروه""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str in DATA['system_instructions']['groups']: | |
| del DATA['system_instructions']['groups'][chat_id_str] | |
| save_data() | |
| return True | |
| return False | |
| def remove_user_system_instruction(user_id: int) -> bool: | |
| """حذف system instruction کاربر""" | |
| user_id_str = str(user_id) | |
| if user_id_str in DATA['system_instructions']['users']: | |
| del DATA['system_instructions']['users'][user_id_str] | |
| save_data() | |
| return True | |
| return False | |
| def toggle_group_system_instruction(chat_id: int, enabled: bool) -> bool: | |
| """فعال/غیرفعال کردن system instruction گروه""" | |
| chat_id_str = str(chat_id) | |
| if chat_id_str in DATA['system_instructions']['groups']: | |
| DATA['system_instructions']['groups'][chat_id_str]['enabled'] = enabled | |
| save_data() | |
| return True | |
| return False | |
| def toggle_user_system_instruction(user_id: int, enabled: bool) -> bool: | |
| """فعال/غیرفعال کردن system instruction کاربر""" | |
| user_id_str = str(user_id) | |
| if user_id_str in DATA['system_instructions']['users']: | |
| DATA['system_instructions']['users'][user_id_str]['enabled'] = enabled | |
| save_data() | |
| return True | |
| return False | |
| def get_system_instruction_info(user_id: int = None, chat_id: int = None) -> dict: | |
| """دریافت اطلاعات system instruction""" | |
| user_id_str = str(user_id) if user_id else None | |
| chat_id_str = str(chat_id) if chat_id else None | |
| result = { | |
| 'has_instruction': False, | |
| 'type': 'global', | |
| 'instruction': DATA['system_instructions'].get('global', ''), | |
| 'details': None | |
| } | |
| if user_id_str and user_id_str in DATA['system_instructions']['users']: | |
| user_data = DATA['system_instructions']['users'][user_id_str] | |
| result.update({ | |
| 'has_instruction': True, | |
| 'type': 'user', | |
| 'instruction': user_data.get('instruction', ''), | |
| 'details': user_data | |
| }) | |
| elif chat_id_str and chat_id_str in DATA['system_instructions']['groups']: | |
| group_data = DATA['system_instructions']['groups'][chat_id_str] | |
| result.update({ | |
| 'has_instruction': True, | |
| 'type': 'group', | |
| 'instruction': group_data.get('instruction', ''), | |
| 'details': group_data | |
| }) | |
| return result | |
| # بارگذاری اولیه دادهها | |
| load_data() | |
| # برای جلوگیری از خطای time در توابع | |
| import time |