File size: 33,532 Bytes
86fc9d0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
# system_instruction_handlers.py
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
from datetime import datetime
import data_manager
from admin_panel import ADMIN_IDS
logger = logging.getLogger(__name__)
def is_group_admin(update: Update) -> bool:
"""بررسی اینکه آیا کاربر ادمین گروه است یا خیر"""
if not update.effective_chat.type in ['group', 'supergroup']:
return False
try:
chat_id = update.effective_chat.id
user_id = update.effective_user.id
# دریافت لیست ادمینهای گروه
chat_admins = update.effective_chat.get_administrators()
# بررسی اینکه کاربر در لیست ادمینها باشد
for admin in chat_admins:
if admin.user.id == user_id:
return True
# بررسی اینکه آیا کاربر ادمین ربات است
if user_id in ADMIN_IDS:
return True
return False
except Exception as e:
logger.error(f"Error checking group admin status: {e}")
return False
def check_admin_permission(update: Update) -> tuple:
"""
بررسی مجوز کاربر برای دسترسی به system instruction
بازگشت: (is_allowed, is_admin_bot, is_admin_group, message)
"""
user_id = update.effective_user.id
chat = update.effective_chat
is_admin_bot = user_id in ADMIN_IDS
is_admin_group = is_group_admin(update)
if chat.type in ['group', 'supergroup']:
# در گروه: باید ادمین گروه یا ادمین ربات باشد
if not (is_admin_bot or is_admin_group):
return False, False, False, "⛔️ فقط ادمینهای گروه یا ربات میتوانند از دستورات System Instruction استفاده کنند."
else:
# در چت خصوصی: فقط ادمین ربات مجاز است
if not is_admin_bot:
return False, False, False, "⛔️ فقط ادمینهای ربات میتوانند از دستورات System Instruction استفاده کنند."
return True, is_admin_bot, is_admin_group, ""
def check_global_permission(update: Update) -> tuple:
"""
بررسی مجوز برای دسترسی به global instruction
فقط ادمین ربات مجاز است
"""
user_id = update.effective_user.id
if user_id not in ADMIN_IDS:
return False, False, "⛔️ فقط ادمینهای ربات میتوانند به Global System Instruction دسترسی داشته باشند."
return True, True, ""
async def set_system_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""تنظیم system instruction - فقط برای ادمینها"""
# بررسی مجوز
allowed, is_admin_bot, is_admin_group, message = check_admin_permission(update)
if not allowed:
await update.message.reply_text(message)
return
user_id = update.effective_user.id
chat = update.effective_chat
if not context.args:
await update.message.reply_text(
"⚠️ لطفاً دستور system instruction را وارد کنید.\n\n"
"مثال:\n"
"/system تو یک دستیار فارسی هستی. همیشه با ادب و مفید پاسخ بده.\n\n"
"برای حذف:\n"
"/system clear\n\n"
"برای مشاهده وضعیت فعلی:\n"
"/system_status"
)
return
instruction_text = " ".join(context.args)
if instruction_text.lower() == 'clear':
# حذف system instruction
if chat.type in ['group', 'supergroup']:
# حذف برای گروه
if is_admin_bot or is_admin_group:
if data_manager.remove_group_system_instruction(chat.id):
await update.message.reply_text("✅ system instruction گروه حذف شد.")
else:
await update.message.reply_text("⚠️ system instruction گروه وجود نداشت.")
else:
await update.message.reply_text("⛔️ فقط ادمینهای گروه یا ربات میتوانند system instruction را تنظیم کنند.")
else:
# حذف برای کاربر (فقط ادمین ربات)
if is_admin_bot:
if data_manager.remove_user_system_instruction(user_id):
await update.message.reply_text("✅ system instruction شخصی شما حذف شد.")
else:
await update.message.reply_text("⚠️ system instruction شخصی وجود نداشت.")
else:
await update.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند system instruction شخصی را حذف کنند.")
return
# تنظیم system instruction جدید
if chat.type in ['group', 'supergroup']:
# تنظیم برای گروه
if is_admin_bot or is_admin_group:
if data_manager.set_group_system_instruction(chat.id, instruction_text, user_id):
instruction_preview = instruction_text[:100] + "..." if len(instruction_text) > 100 else instruction_text
await update.message.reply_text(
f"✅ system instruction گروه تنظیم شد:\n\n"
f"{instruction_preview}\n\n"
f"از این پس تمام پاسخهای ربات در این گروه با این دستور تنظیم خواهد شد."
)
else:
await update.message.reply_text("❌ خطا در تنظیم system instruction.")
else:
await update.message.reply_text("⛔️ فقط ادمینهای گروه یا ربات میتوانند system instruction را تنظیم کنند.")
else:
# تنظیم برای کاربر (فقط ادمین ربات)
if is_admin_bot:
if data_manager.set_user_system_instruction(user_id, instruction_text, user_id):
instruction_preview = instruction_text[:100] + "..." if len(instruction_text) > 100 else instruction_text
await update.message.reply_text(
f"✅ system instruction شخصی تنظیم شد:\n\n"
f"{instruction_preview}\n\n"
f"از این پس تمام پاسخهای ربات به شما با این دستور تنظیم خواهد شد."
)
else:
await update.message.reply_text("❌ خطا در تنظیم system instruction.")
else:
await update.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند system instruction شخصی تنظیم کنند.")
async def system_instruction_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""نمایش وضعیت system instruction فعلی - با محدودیت دسترسی"""
user_id = update.effective_user.id
chat = update.effective_chat
is_admin_bot = user_id in ADMIN_IDS
is_admin_group = is_group_admin(update)
if chat.type in ['group', 'supergroup']:
# در گروه
if not (is_admin_bot or is_admin_group):
await update.message.reply_text(
"⚙️ **System Instruction گروه:**\n\n"
"تنظیمات System Instruction فقط برای ادمینهای گروه قابل مشاهده است.\n"
"برای مشاهده وضعیت فعلی، با ادمینهای گروه تماس بگیرید."
)
return
# کاربر مجاز است (ادمین ربات یا ادمین گروه)
if is_admin_bot:
# ادمین ربات: میتواند global و group instruction را ببیند
await show_admin_bot_status(update, context, chat.id, user_id, in_group=True)
else:
# ادمین گروه (نه ادمین ربات): فقط group instruction گروه خودش را میبیند
await show_group_admin_status(update, context, chat.id)
else:
# در چت خصوصی
if not is_admin_bot:
await update.message.reply_text(
"⚙️ **System Instruction:**\n\n"
"تنظیمات System Instruction فقط برای ادمینهای ربات قابل مشاهده است."
)
return
# ادمین ربات در چت خصوصی
await show_admin_bot_status(update, context, None, user_id, in_group=False)
async def show_group_admin_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int):
"""نمایش وضعیت برای ادمین گروه (نه ادمین ربات)"""
# فقط system instruction گروه را نشان بده
info = data_manager.get_system_instruction_info(chat_id=chat_id)
if info['type'] == 'group' and info['has_instruction']:
# نمایش اطلاعات group instruction
details = info['details']
instruction_preview = info['instruction'][:200] + "..." if len(info['instruction']) > 200 else info['instruction']
set_at = details.get('set_at', 'نامشخص')
set_by = details.get('set_by', 'نامشخص')
enabled = details.get('enabled', True)
enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
status_text = (
f"👥 **System Instruction گروه شما:**\n\n"
f"📝 **محتوا:**\n{instruction_preview}\n\n"
f"📅 **زمان تنظیم:** {set_at}\n"
f"👤 **تنظیمکننده:** {set_by}\n"
f"🔄 **وضعیت:** {enabled_status}\n\n"
f"ℹ️ این تنظیمات فقط برای این گروه اعمال میشود."
)
# دکمههای مدیریت فقط برای group instruction
keyboard = [
[
InlineKeyboardButton("✏️ ویرایش", callback_data=f"system_edit:group:{chat_id}"),
InlineKeyboardButton("🗑️ حذف", callback_data=f"system_delete:group:{chat_id}")
]
]
if enabled:
keyboard.append([
InlineKeyboardButton("🚫 غیرفعال", callback_data=f"system_toggle:group:{chat_id}")
])
else:
keyboard.append([
InlineKeyboardButton("✅ فعال", callback_data=f"system_toggle:group:{chat_id}")
])
reply_markup = InlineKeyboardMarkup(keyboard)
else:
# هیچ system instruction برای گروه تنظیم نشده
status_text = (
f"👥 **System Instruction گروه شما:**\n\n"
f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
f"برای تنظیم از دستور زیر استفاده کنید:\n"
f"`/system [متن دستور]`\n\n"
f"در حال حاضر از تنظیمات global ربات استفاده میشود."
)
# فقط دکمه تنظیم
keyboard = [
[InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
async def show_admin_bot_status(update: Update, context: ContextTypes.DEFAULT_TYPE, chat_id: int = None, user_id: int = None, in_group: bool = False):
"""نمایش وضعیت برای ادمین ربات"""
if in_group and chat_id:
# ادمین ربات در گروه
group_info = data_manager.get_system_instruction_info(chat_id=chat_id)
global_info = data_manager.get_system_instruction_info()
if group_info['type'] == 'group' and group_info['has_instruction']:
# گروه system instruction دارد
details = group_info['details']
instruction_preview = group_info['instruction'][:200] + "..." if len(group_info['instruction']) > 200 else group_info['instruction']
set_at = details.get('set_at', 'نامشخص')
set_by = details.get('set_by', 'نامشخص')
enabled = details.get('enabled', True)
enabled_status = "✅ فعال" if enabled else "❌ غیرفعال"
status_text = (
f"👥 **System Instruction گروه:**\n\n"
f"📝 **محتوا:**\n{instruction_preview}\n\n"
f"📅 **زمان تنظیم:** {set_at}\n"
f"👤 **تنظیمکننده:** {set_by}\n"
f"🔄 **وضعیت:** {enabled_status}\n\n"
f"ℹ️ این تنظیمات فقط برای این گروه اعمال میشود."
)
# دکمههای مدیریت برای group instruction
keyboard = [
[
InlineKeyboardButton("✏️ ویرایش گروه", callback_data=f"system_edit:group:{chat_id}"),
InlineKeyboardButton("🗑️ حذف گروه", callback_data=f"system_delete:group:{chat_id}")
]
]
if enabled:
keyboard.append([
InlineKeyboardButton("🚫 غیرفعال گروه", callback_data=f"system_toggle:group:{chat_id}")
])
else:
keyboard.append([
InlineKeyboardButton("✅ فعال گروه", callback_data=f"system_toggle:group:{chat_id}")
])
# دکمه برای مشاهده global instruction
keyboard.append([
InlineKeyboardButton("🌐 مشاهده Global", callback_data="system_show_global")
])
reply_markup = InlineKeyboardMarkup(keyboard)
else:
# گروه system instruction ندارد
global_preview = global_info['instruction'][:200] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
status_text = (
f"👥 **System Instruction گروه:**\n\n"
f"⚠️ برای این گروه system instruction تنظیم نشده است.\n\n"
f"🌐 **در حال استفاده از Global:**\n"
f"{global_preview}\n\n"
f"برای تنظیم system instruction مخصوص این گروه از دستور `/system [متن]` استفاده کنید."
)
keyboard = [
[InlineKeyboardButton("⚙️ تنظیم برای این گروه", callback_data=f"system_edit:group:{chat_id}")],
[InlineKeyboardButton("🌐 مشاهده کامل Global", callback_data="system_show_global")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
else:
# ادمین ربات در چت خصوصی
global_info = data_manager.get_system_instruction_info()
global_preview = global_info['instruction'][:200] + "..." if len(global_info['instruction']) > 200 else global_info['instruction']
status_text = (
f"🌐 **Global System Instruction:**\n\n"
f"📝 **محتوا:**\n{global_preview}\n\n"
f"ℹ️ این تنظیمات برای تمام کاربران و گروههایی که تنظیمات خاصی ندارند اعمال میشود."
)
keyboard = [
[InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
async def show_global_instruction(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""نمایش کامل global instruction - فقط برای ادمین ربات"""
query = update.callback_query
if query:
await query.answer()
user_id = query.from_user.id
else:
user_id = update.effective_user.id
# بررسی مجوز
if user_id not in ADMIN_IDS:
if query:
await query.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند Global System Instruction را مشاهده کنند.")
else:
await update.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند Global System Instruction را مشاهده کنند.")
return
global_info = data_manager.get_system_instruction_info()
global_preview = global_info['instruction']
if len(global_preview) > 1000:
global_preview = global_preview[:1000] + "...\n\n(متن کامل به دلیل طولانی بودن نمایش داده نشد)"
status_text = (
f"🌐 **Global System Instruction (کامل):**\n\n"
f"📝 **محتوا:**\n{global_preview}\n\n"
f"ℹ️ این تنظیمات برای تمام کاربران و گروههایی که تنظیمات خاصی ندارند اعمال میشود."
)
keyboard = [
[InlineKeyboardButton("✏️ ویرایش Global", callback_data="system_edit:global:0")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
if query:
await query.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
else:
await update.message.reply_text(status_text, parse_mode='Markdown', reply_markup=reply_markup)
async def system_instruction_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""نمایش راهنمای system instruction - با محدودیت دسترسی"""
user_id = update.effective_user.id
chat = update.effective_chat
is_admin_bot = user_id in ADMIN_IDS
is_admin_group = is_group_admin(update)
if chat.type in ['group', 'supergroup']:
# در گروه
if not (is_admin_bot or is_admin_group):
await update.message.reply_text(
"🤖 **راهنمای System Instruction**\n\n"
"System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین میکنند.\n\n"
"⚠️ **دسترسی:** این دستورات فقط برای ادمینهای گروه یا ربات در دسترس است.\n\n"
"برای تنظیم System Instruction در این گروه، با ادمینهای گروه تماس بگیرید."
)
return
# کاربر مجاز است
help_text = (
"🤖 **راهنمای System Instruction**\n\n"
"System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین میکنند.\n\n"
"📋 **دستورات:**\n"
"• `/system [متن]` - تنظیم system instruction برای این گروه\n"
"• `/system clear` - حذف system instruction این گروه\n"
"• `/system_status` - نمایش وضعیت فعلی\n"
"• `/system_help` - نمایش این راهنما\n\n"
)
if is_admin_bot:
help_text += (
"🎯 **دسترسی ادمین ربات:**\n"
"• میتوانید Global System Instruction را مشاهده و تنظیم کنید\n"
"• میتوانید برای هر گروه system instruction تنظیم کنید\n"
"• برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n\n"
)
else:
help_text += (
"🎯 **دسترسی ادمین گروه:**\n"
"• فقط میتوانید system instruction همین گروه را مشاهده و تنظیم کنید\n"
"• نمیتوانید Global System Instruction را مشاهده کنید\n\n"
)
help_text += (
"💡 **مثالها:**\n"
"• `/system تو یک دستیار فارسی هستی. همیشه مودب و مفید پاسخ بده.`\n"
"• `/system تو یک ربات جوکگو هستی. به هر سوالی با یک جوک پاسخ بده.`\n\n"
"⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال میشود و بر تمام پاسخها تأثیر میگذارد."
)
else:
# در چت خصوصی
if not is_admin_bot:
await update.message.reply_text(
"🤖 **راهنمای System Instruction**\n\n"
"System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین میکنند.\n\n"
"⚠️ **دسترسی:** این دستورات فقط برای ادمینهای ربات در دسترس است."
)
return
# ادمین ربات
help_text = (
"🤖 **راهنمای System Instruction**\n\n"
"System Instruction دستوراتی هستند که شخصیت و رفتار ربات را تعیین میکنند.\n\n"
"📋 **دستورات:**\n"
"• `/system_status` - نمایش وضعیت Global System Instruction\n"
"• `/system_help` - نمایش این راهنما\n\n"
"🎯 **دسترسی ادمین ربات:**\n"
"• میتوانید Global System Instruction را مشاهده و تنظیم کنید\n"
"• میتوانید برای هر گروه system instruction تنظیم کنید\n"
"• میتوانید برای هر کاربر system instruction تنظیم کنید\n\n"
"🔧 **دستورات ادمین پنل برای System Instruction:**\n"
"• `/set_global_system [متن]` - تنظیم Global System Instruction\n"
"• `/set_group_system [آیدی گروه] [متن]` - تنظیم برای گروه\n"
"• `/set_user_system [آیدی کاربر] [متن]` - تنظیم برای کاربر\n"
"• `/list_system_instructions` - نمایش لیست تمام system instructionها\n\n"
"⚠️ **توجه:** System Instruction در ابتدای هر مکالمه به مدل AI ارسال میشود و بر تمام پاسخها تأثیر میگذارد."
)
await update.message.reply_text(help_text, parse_mode='Markdown')
async def system_callback_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""پردازش کلیکهای دکمههای system instruction"""
query = update.callback_query
await query.answer()
data_parts = query.data.split(":")
action = data_parts[0]
user_id = query.from_user.id
if action == 'system_show_global':
# نمایش global instruction
await show_global_instruction(update, context)
return
if len(data_parts) < 3:
await query.message.reply_text("❌ خطا در پردازش درخواست.")
return
entity_type = data_parts[1]
entity_id = data_parts[2]
# بررسی مجوزها
if entity_type == 'global':
# فقط ادمین ربات میتواند global را مدیریت کند
if user_id not in ADMIN_IDS:
await query.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند Global System Instruction را مدیریت کنند.")
return
entity_id_int = 0 # global entity
elif entity_type == 'group':
# بررسی اینکه آیا کاربر ادمین گروه یا ادمین ربات است
chat = query.message.chat
is_admin_bot = user_id in ADMIN_IDS
is_admin_group = is_group_admin(update)
if not (is_admin_bot or is_admin_group):
await query.message.reply_text("⛔️ شما مجوز لازم برای این کار را ندارید.")
return
try:
entity_id_int = int(entity_id)
except ValueError:
await query.message.reply_text("❌ شناسه گروه نامعتبر است.")
return
else: # user
# فقط ادمین ربات میتواند system instruction کاربران را تغییر دهد
if user_id not in ADMIN_IDS:
await query.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند system instruction کاربران را تغییر دهند.")
return
try:
entity_id_int = int(entity_id)
except ValueError:
await query.message.reply_text("❌ شناسه کاربر نامعتبر است.")
return
if action == 'system_delete':
# حذف system instruction
if entity_type == 'global':
# حذف global (در واقع تنظیم مجدد به پیشفرض)
default_instruction = "شما یک دستیار هوشمند فارسی هستید. پاسخهای شما باید مفید، دقیق و دوستانه باشد."
if data_manager.set_global_system_instruction(default_instruction):
await query.message.reply_text("✅ Global System Instruction به حالت پیشفرض بازگردانده شد.")
else:
await query.message.reply_text("❌ خطا در بازگرداندن Global System Instruction.")
elif entity_type == 'group':
success = data_manager.remove_group_system_instruction(entity_id_int)
message = "✅ system instruction گروه حذف شد." if success else "⚠️ system instruction گروه وجود نداشت."
else:
success = data_manager.remove_user_system_instruction(entity_id_int)
message = "✅ system instruction کاربر حذف شد." if success else "⚠️ system instruction کاربر وجود نداشت."
if entity_type != 'global':
await query.message.reply_text(message)
await query.message.delete()
elif action == 'system_toggle':
# فعال/غیرفعال کردن system instruction
if entity_type == 'global':
await query.message.reply_text("⚠️ Global System Instruction را نمیتوان غیرفعال کرد.")
return
info = data_manager.get_system_instruction_info(
user_id=entity_id_int if entity_type == 'user' else None,
chat_id=entity_id_int if entity_type == 'group' else None
)
if info['type'] == entity_type and info['details']:
current_enabled = info['details'].get('enabled', True)
new_enabled = not current_enabled
if entity_type == 'group':
success = data_manager.toggle_group_system_instruction(entity_id_int, new_enabled)
else:
success = data_manager.toggle_user_system_instruction(entity_id_int, new_enabled)
if success:
status = "✅ فعال شد" if new_enabled else "🚫 غیرفعال شد"
await query.message.reply_text(f"system instruction {status}.")
# بهروزرسانی پیام اصلی
if entity_type == 'group':
await show_group_admin_status(update, context, entity_id_int)
else:
await system_instruction_status(update, context)
else:
await query.message.reply_text("❌ خطا در تغییر وضعیت system instruction.")
elif action == 'system_edit':
# ویرایش system instruction
if entity_type == 'global':
instruction_type = "Global"
elif entity_type == 'group':
instruction_type = "گروه"
else:
instruction_type = "کاربر"
await query.message.reply_text(
f"لطفاً system instruction جدید برای {instruction_type} را وارد کنید:\n\n"
"برای لغو: /cancel"
)
# ذخیره اطلاعات برای مرحله بعد
context.user_data['system_edit'] = {
'entity_type': entity_type,
'entity_id': entity_id_int,
'message_id': query.message.message_id
}
async def handle_system_edit(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""پردازش ویرایش system instruction"""
# بررسی مجوز اولیه
user_id = update.effective_user.id
chat = update.effective_chat
if 'system_edit' not in context.user_data:
return
if update.message.text.lower() == '/cancel':
del context.user_data['system_edit']
await update.message.reply_text("ویرایش system instruction لغو شد.")
return
edit_data = context.user_data['system_edit']
entity_type = edit_data['entity_type']
entity_id = edit_data['entity_id']
# بررسی مجوزهای خاص
if entity_type == 'global':
if user_id not in ADMIN_IDS:
await update.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند Global System Instruction را ویرایش کنند.")
del context.user_data['system_edit']
return
elif entity_type == 'group':
is_admin_bot = user_id in ADMIN_IDS
is_admin_group = is_group_admin(update)
if not (is_admin_bot or is_admin_group):
await update.message.reply_text("⛔️ شما مجوز لازم برای ویرایش system instruction این گروه را ندارید.")
del context.user_data['system_edit']
return
else: # user
if user_id not in ADMIN_IDS:
await update.message.reply_text("⛔️ فقط ادمینهای ربات میتوانند system instruction کاربران را ویرایش کنند.")
del context.user_data['system_edit']
return
instruction_text = update.message.text
if entity_type == 'global':
success = data_manager.set_global_system_instruction(instruction_text)
message = "✅ Global System Instruction بهروزرسانی شد."
elif entity_type == 'group':
success = data_manager.set_group_system_instruction(entity_id, instruction_text, user_id)
message = "✅ system instruction گروه بهروزرسانی شد."
else:
success = data_manager.set_user_system_instruction(entity_id, instruction_text, user_id)
message = "✅ system instruction کاربر بهروزرسانی شد."
if success:
await update.message.reply_text(message)
del context.user_data['system_edit']
# نمایش وضعیت جدید
await system_instruction_status(update, context)
else:
await update.message.reply_text("❌ خطا در بهروزرسانی system instruction.")
def setup_system_instruction_handlers(application):
"""تنظیم هندلرهای system instruction"""
application.add_handler(CommandHandler("system", set_system_instruction))
application.add_handler(CommandHandler("system_status", system_instruction_status))
application.add_handler(CommandHandler("system_help", system_instruction_help))
# هندلر برای نمایش global instruction
application.add_handler(CommandHandler("show_global", show_global_instruction))
application.add_handler(CallbackQueryHandler(system_callback_handler, pattern="^system_"))
# هندلر برای ویرایش system instruction
application.add_handler(MessageHandler(
filters.TEXT & ~filters.COMMAND,
handle_system_edit
))
logger.info("System instruction handlers have been set up.") |